code: 
  
  
  import argparse
  import logging
  import os
  from datetime import datetime
  
  import numpy as np
  import torch
  from torch import nn
  from torch.utils.data import DataLoader, SequentialSampler, Subset
  from torch.utils.data.distributed import DistributedSampler
  from tqdm import tqdm
  
  import transformers
  from transformers import (
      AutoConfig,
      AutoModelForSequenceClassification,
      AutoTokenizer,
      GlueDataset,
      default_data_collator,
      glue_compute_metrics,
      glue_output_modes,
      glue_processors,
      set_seed,
  )
  from transformers.trainer_utils import is_main_process
  
  
  SCREAMING_SNAKE_CASE__				:    List[str]         =    logging.getLogger(__name__)
  
  
  
  
  def       a__						(		snake_case__				:       Tuple    ):
    _UpperCAmelCase		:       Optional[Any]       =    p * torch.log(snake_case__    )
    _UpperCAmelCase		:       Union[str, Any]       =    0
    return -plogp.sum(dim=-1    )
  
  
  
  
  def       a__						(		snake_case__				:       List[str]    ):
    logger.info("""lv, h >\t""" + """\t""".join(f'''{x + 1}''' for x in range(len(snake_case__    )    )    )    )
    for row in range(len(snake_case__    )    ):
      if tensor.dtype != torch.long:
        logger.info(f'''layer {row + 1}:\t''' + """\t""".join(f'''{x:.5f}''' for x in tensor[row].cpu().data    )    )
      else:
        logger.info(f'''layer {row + 1}:\t''' + """\t""".join(f'''{x:d}''' for x in tensor[row].cpu().data    )    )
  
  
  
  
  def       a__						(		snake_case__				:       List[Any]	,      snake_case__				:       Any	,      snake_case__				:       Union[str, Any]	,      snake_case__				:       List[Any]=True	,      snake_case__				:       Optional[Any]=True	,      snake_case__				:       int=None	,      snake_case__				:       str=False    ):
    _UpperCAmelCase,_UpperCAmelCase		:       str       =    model.config.num_hidden_layers, model.config.num_attention_heads
    _UpperCAmelCase		:       List[Any]       =    torch.zeros(snake_case__	,      snake_case__    ).to(args.device    )
    _UpperCAmelCase		:       Tuple       =    torch.zeros(snake_case__	,      snake_case__    ).to(args.device    )
  
    if head_mask is None:
      _UpperCAmelCase		:       Dict       =    torch.ones(snake_case__	,      snake_case__    ).to(args.device    )
  
    head_mask.requires_grad_(requires_grad=snake_case__    )
    # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
    if actually_pruned:
      _UpperCAmelCase		:       Dict       =    None
  
    _UpperCAmelCase		:       Tuple       =    None
    _UpperCAmelCase		:       Optional[Any]       =    None
    _UpperCAmelCase		:       Dict       =    0.0
  
    for step, inputs in enumerate(tqdm(snake_case__	,      desc="""Iteration"""	,      disable=args.local_rank not in [-1, 0]    )    ):
      for k, v in inputs.items():
        _UpperCAmelCase		:       List[Any]       =    v.to(args.device    )
  
      # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
      _UpperCAmelCase		:       List[str]       =    model(**snake_case__	,      head_mask=snake_case__    )
      _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       int       =    (
          outputs[0],
          outputs[1],
          outputs[-1],
      )  # Loss and logits are the first, attention the last
      loss.backward()  # Backpropagate to populate the gradients in the head mask
  
      if compute_entropy:
        for layer, attn in enumerate(snake_case__    ):
          _UpperCAmelCase		:       Tuple       =    entropy(attn.detach()    ) * inputs["""attention_mask"""].float().unsqueeze(1    )
          attn_entropy[layer] += masked_entropy.sum(-1    ).sum(0    ).detach()
  
      if compute_importance:
        head_importance += head_mask.grad.abs().detach()
  
      # Also store our logits/labels if we want to compute metrics afterwards
      if preds is None:
        _UpperCAmelCase		:       int       =    logits.detach().cpu().numpy()
        _UpperCAmelCase		:       str       =    inputs["""labels"""].detach().cpu().numpy()
      else:
        _UpperCAmelCase		:       int       =    np.append(snake_case__	,      logits.detach().cpu().numpy()	,      axis=0    )
        _UpperCAmelCase		:       Tuple       =    np.append(snake_case__	,      inputs["""labels"""].detach().cpu().numpy()	,      axis=0    )
  
      tot_tokens += inputs["attention_mask"].float().detach().sum().data
  
    # Normalize
    attn_entropy /= tot_tokens
    head_importance /= tot_tokens
    # Layerwise importance normalization
    if not args.dont_normalize_importance_by_layer:
      _UpperCAmelCase		:       List[str]       =    2
      _UpperCAmelCase		:       List[str]       =    torch.pow(torch.pow(snake_case__	,      snake_case__    ).sum(-1    )	,      1 / exponent    )
      head_importance /= norm_by_layer.unsqueeze(-1    ) + 1e-2_0
  
    if not args.dont_normalize_global_importance:
      _UpperCAmelCase		:       str       =    (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())
  
    # Print/save matrices
    np.save(os.path.join(args.output_dir	,      """attn_entropy.npy"""    )	,      attn_entropy.detach().cpu().numpy()    )
    np.save(os.path.join(args.output_dir	,      """head_importance.npy"""    )	,      head_importance.detach().cpu().numpy()    )
  
    logger.info("""Attention entropies"""    )
    print_ad_tensor(snake_case__    )
    logger.info("""Head importance scores"""    )
    print_ad_tensor(snake_case__    )
    logger.info("""Head ranked by importance scores"""    )
    _UpperCAmelCase		:       Dict       =    torch.zeros(head_importance.numel()	,      dtype=torch.long	,      device=args.device    )
    _UpperCAmelCase		:       Optional[Any]       =    torch.arange(
        head_importance.numel()	,      device=args.device    )
    _UpperCAmelCase		:       List[Any]       =    head_ranks.view_as(snake_case__    )
    print_ad_tensor(snake_case__    )
  
    return attn_entropy, head_importance, preds, labels
  
  
  
  
  def       a__						(		snake_case__				:       Any	,      snake_case__				:       List[str]	,      snake_case__				:       List[str]    ):
    _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       List[Any]       =    compute_heads_importance(snake_case__	,      snake_case__	,      snake_case__	,      compute_entropy=snake_case__    )
    _UpperCAmelCase		:       int       =    np.argmax(snake_case__	,      axis=1    ) if args.output_mode == """classification""" else np.squeeze(snake_case__    )
    _UpperCAmelCase		:       Any       =    glue_compute_metrics(args.task_name	,      snake_case__	,      snake_case__    )[args.metric_name]
    logger.info("""Pruning: original score: %f, threshold: %f"""	,      snake_case__	,      original_score * args.masking_threshold    )
  
    _UpperCAmelCase		:       List[str]       =    torch.ones_like(snake_case__    )
    _UpperCAmelCase		:       Any       =    max(1	,      int(new_head_mask.numel() * args.masking_amount    )    )
  
    _UpperCAmelCase		:       List[Any]       =    original_score
    while current_score >= original_score * args.masking_threshold:
      _UpperCAmelCase		:       Dict       =    new_head_mask.clone()  # save current head mask
      # heads from least important to most - keep only not-masked heads
      _UpperCAmelCase		:       List[str]       =    float("""Inf"""    )
      _UpperCAmelCase		:       Optional[int]       =    head_importance.view(-1    ).sort()[1]
  
      if len(snake_case__    ) <= num_to_mask:
        break
  
      # mask heads
      _UpperCAmelCase		:       Optional[int]       =    current_heads_to_mask[:num_to_mask]
      logger.info("""Heads to mask: %s"""	,      str(current_heads_to_mask.tolist()    )    )
      _UpperCAmelCase		:       Optional[int]       =    new_head_mask.view(-1    )
      _UpperCAmelCase		:       Optional[int]       =    0.0
      _UpperCAmelCase		:       List[Any]       =    new_head_mask.view_as(snake_case__    )
      _UpperCAmelCase		:       Dict       =    new_head_mask.clone().detach()
      print_ad_tensor(snake_case__    )
  
      # Compute metric and head importance again
      _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       Optional[Any]       =    compute_heads_importance(
          snake_case__	,      snake_case__	,      snake_case__	,      compute_entropy=snake_case__	,      head_mask=snake_case__    )
      _UpperCAmelCase		:       Union[str, Any]       =    np.argmax(snake_case__	,      axis=1    ) if args.output_mode == """classification""" else np.squeeze(snake_case__    )
      _UpperCAmelCase		:       Any       =    glue_compute_metrics(args.task_name	,      snake_case__	,      snake_case__    )[args.metric_name]
      logger.info(
          """Masking: current score: %f, remaining heads %d (%.1f percents)"""	,      snake_case__	,      new_head_mask.sum()	,      new_head_mask.sum() / new_head_mask.numel() * 100	,      )
  
    logger.info("""Final head mask"""    )
    print_ad_tensor(snake_case__    )
    np.save(os.path.join(args.output_dir	,      """head_mask.npy"""    )	,      head_mask.detach().cpu().numpy()    )
  
    return head_mask
  
  
  
  
  def       a__						(		snake_case__				:       str	,      snake_case__				:       List[Any]	,      snake_case__				:       Any	,      snake_case__				:       str    ):
    _UpperCAmelCase		:       List[str]       =    datetime.now()
    _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       Optional[int]       =    compute_heads_importance(
        snake_case__	,      snake_case__	,      snake_case__	,      compute_entropy=snake_case__	,      compute_importance=snake_case__	,      head_mask=snake_case__    )
    _UpperCAmelCase		:       Any       =    np.argmax(snake_case__	,      axis=1    ) if args.output_mode == """classification""" else np.squeeze(snake_case__    )
    _UpperCAmelCase		:       Union[str, Any]       =    glue_compute_metrics(args.task_name	,      snake_case__	,      snake_case__    )[args.metric_name]
    _UpperCAmelCase		:       List[str]       =    datetime.now() - before_time
  
    _UpperCAmelCase		:       Union[str, Any]       =    sum(p.numel() for p in model.parameters()    )
    _UpperCAmelCase		:       str       =    {
        layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(snake_case__    )    )
    }
  
    assert sum(len(snake_case__    ) for h in heads_to_prune.values()    ) == (1 - head_mask.long()).sum().item()
    model.prune_heads(snake_case__    )
    _UpperCAmelCase		:       int       =    sum(p.numel() for p in model.parameters()    )
  
    _UpperCAmelCase		:       Optional[Any]       =    datetime.now()
    _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       str       =    compute_heads_importance(
        snake_case__	,      snake_case__	,      snake_case__	,      compute_entropy=snake_case__	,      compute_importance=snake_case__	,      head_mask=snake_case__	,      actually_pruned=snake_case__	,      )
    _UpperCAmelCase		:       str       =    np.argmax(snake_case__	,      axis=1    ) if args.output_mode == """classification""" else np.squeeze(snake_case__    )
    _UpperCAmelCase		:       str       =    glue_compute_metrics(args.task_name	,      snake_case__	,      snake_case__    )[args.metric_name]
    _UpperCAmelCase		:       Union[str, Any]       =    datetime.now() - before_time
  
    logger.info(
        """Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)"""	,      snake_case__	,      snake_case__	,      pruned_num_params / original_num_params * 100	,      )
    logger.info("""Pruning: score with masking: %f score with pruning: %f"""	,      snake_case__	,      snake_case__    )
    logger.info("""Pruning: speed ratio (new timing / original timing): %f percents"""	,      original_time / new_time * 100    )
  
  
  
  
  def       a__						(		):
    _UpperCAmelCase		:       Union[str, Any]       =    argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--data_dir"""	,      default=snake_case__	,      type=snake_case__	,      required=snake_case__	,      help="""The input data dir. Should contain the .tsv files (or other data files) for the task."""	,      )
    parser.add_argument(
        """--model_name_or_path"""	,      default=snake_case__	,      type=snake_case__	,      required=snake_case__	,      help="""Path to pretrained model or model identifier from huggingface.co/models"""	,      )
    parser.add_argument(
        """--task_name"""	,      default=snake_case__	,      type=snake_case__	,      required=snake_case__	,      help="""The name of the task to train selected in the list: """ + """, """.join(glue_processors.keys()    )	,      )
    parser.add_argument(
        """--output_dir"""	,      default=snake_case__	,      type=snake_case__	,      required=snake_case__	,      help="""The output directory where the model predictions and checkpoints will be written."""	,      )
  
    # Other parameters
    parser.add_argument(
        """--config_name"""	,      default=""""""	,      type=snake_case__	,      help="""Pretrained config name or path if not the same as model_name_or_path"""	,      )
    parser.add_argument(
        """--tokenizer_name"""	,      default=""""""	,      type=snake_case__	,      help="""Pretrained tokenizer name or path if not the same as model_name_or_path"""	,      )
    parser.add_argument(
        """--cache_dir"""	,      default=snake_case__	,      type=snake_case__	,      help="""Where do you want to store the pre-trained models downloaded from huggingface.co"""	,      )
    parser.add_argument(
        """--data_subset"""	,      type=snake_case__	,      default=-1	,      help="""If > 0: limit the data to a subset of data_subset instances."""    )
    parser.add_argument(
        """--overwrite_output_dir"""	,      action="""store_true"""	,      help="""Whether to overwrite data in output directory"""    )
    parser.add_argument(
        """--overwrite_cache"""	,      action="""store_true"""	,      help="""Overwrite the cached training and evaluation sets"""    )
  
    parser.add_argument(
        """--dont_normalize_importance_by_layer"""	,      action="""store_true"""	,      help="""Don't normalize importance score by layers"""    )
    parser.add_argument(
        """--dont_normalize_global_importance"""	,      action="""store_true"""	,      help="""Don't normalize all importance scores between 0 and 1"""	,      )
  
    parser.add_argument(
        """--try_masking"""	,      action="""store_true"""	,      help="""Whether to try to mask head until a threshold of accuracy."""    )
    parser.add_argument(
        """--masking_threshold"""	,      default=0.9	,      type=snake_case__	,      help="""masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."""	,      )
    parser.add_argument(
        """--masking_amount"""	,      default=0.1	,      type=snake_case__	,      help="""Amount to heads to masking at each masking step."""    )
    parser.add_argument("""--metric_name"""	,      default="""acc"""	,      type=snake_case__	,      help="""Metric to use for head masking."""    )
  
    parser.add_argument(
        """--max_seq_length"""	,      default=128	,      type=snake_case__	,      help=(
            """The maximum total input sequence length after WordPiece tokenization. \n"""
            """Sequences longer than this will be truncated, sequences shorter padded."""
        )	,      )
    parser.add_argument("""--batch_size"""	,      default=1	,      type=snake_case__	,      help="""Batch size."""    )
  
    parser.add_argument("""--seed"""	,      type=snake_case__	,      default=42    )
    parser.add_argument("""--local_rank"""	,      type=snake_case__	,      default=-1	,      help="""local_rank for distributed training on gpus"""    )
    parser.add_argument("""--no_cuda"""	,      action="""store_true"""	,      help="""Whether not to use CUDA when available"""    )
    parser.add_argument("""--server_ip"""	,      type=snake_case__	,      default=""""""	,      help="""Can be used for distant debugging."""    )
    parser.add_argument("""--server_port"""	,      type=snake_case__	,      default=""""""	,      help="""Can be used for distant debugging."""    )
    _UpperCAmelCase		:       int       =    parser.parse_args()
  
    if args.server_ip and args.server_port:
      # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
      import ptvsd
  
      print("""Waiting for debugger attach"""    )
      ptvsd.enable_attach(address=(args.server_ip, args.server_port)	,      redirect_output=snake_case__    )
      ptvsd.wait_for_attach()
  
    # Setup devices and distributed training
    if args.local_rank == -1 or args.no_cuda:
      _UpperCAmelCase		:       List[Any]       =    torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""    )
      _UpperCAmelCase		:       Dict       =    0 if args.no_cuda else torch.cuda.device_count()
    else:
      torch.cuda.set_device(args.local_rank    )
      _UpperCAmelCase		:       Union[str, Any]       =    torch.device("""cuda"""	,      args.local_rank    )
      _UpperCAmelCase		:       int       =    1
      torch.distributed.init_process_group(backend="""nccl"""    )  # Initializes the distributed backend
  
    # Setup logging
    logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN    )
    logger.info("""device: {} n_gpu: {}, distributed: {}""".format(args.device	,      args.n_gpu	,      bool(args.local_rank != -1    )    )    )
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(args.local_rank    ):
      transformers.utils.logging.set_verbosity_info()
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()
  
    # Set seeds
    set_seed(args.seed    )
  
    # Prepare GLUE task
    _UpperCAmelCase		:       int       =    args.task_name.lower()
    if args.task_name not in glue_processors:
      raise ValueError("""Task not found: %s""" % (args.task_name)    )
    _UpperCAmelCase		:       Dict       =    glue_processors[args.task_name]()
    _UpperCAmelCase		:       Union[str, Any]       =    glue_output_modes[args.task_name]
    _UpperCAmelCase		:       Optional[int]       =    processor.get_labels()
    _UpperCAmelCase		:       Dict       =    len(snake_case__    )
  
    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
  
    _UpperCAmelCase		:       Union[str, Any]       =    AutoConfig.from_pretrained(
        args.config_name if args.config_name else args.model_name_or_path	,      num_labels=snake_case__	,      finetuning_task=args.task_name	,      output_attentions=snake_case__	,      cache_dir=args.cache_dir	,      )
    _UpperCAmelCase		:       Optional[Any]       =    AutoTokenizer.from_pretrained(
        args.tokenizer_name if args.tokenizer_name else args.model_name_or_path	,      cache_dir=args.cache_dir	,      )
    _UpperCAmelCase		:       List[Any]       =    AutoModelForSequenceClassification.from_pretrained(
        args.model_name_or_path	,      from_tf=bool(""".ckpt""" in args.model_name_or_path    )	,      config=snake_case__	,      cache_dir=args.cache_dir	,      )
  
    # Distributed and parallel training
    model.to(args.device    )
    if args.local_rank != -1:
      _UpperCAmelCase		:       List[Any]       =    nn.parallel.DistributedDataParallel(
          snake_case__	,      device_ids=[args.local_rank]	,      output_device=args.local_rank	,      find_unused_parameters=snake_case__    )
    elif args.n_gpu > 1:
      _UpperCAmelCase		:       Any       =    nn.DataParallel(snake_case__    )
  
    # Print/save training arguments
    os.makedirs(args.output_dir	,      exist_ok=snake_case__    )
    torch.save(snake_case__	,      os.path.join(args.output_dir	,      """run_args.bin"""    )    )
    logger.info("""Training/evaluation parameters %s"""	,      snake_case__    )
  
    # Prepare dataset for the GLUE task
    _UpperCAmelCase		:       int       =    GlueDataset(snake_case__	,      tokenizer=snake_case__	,      mode="""dev"""    )
    if args.data_subset > 0:
      _UpperCAmelCase		:       Union[str, Any]       =    Subset(snake_case__	,      list(range(min(args.data_subset	,      len(snake_case__    )    )    )    )    )
    _UpperCAmelCase		:       Optional[int]       =    SequentialSampler(snake_case__    ) if args.local_rank == -1 else DistributedSampler(snake_case__    )
    _UpperCAmelCase		:       Tuple       =    DataLoader(
        snake_case__	,      sampler=snake_case__	,      batch_size=args.batch_size	,      collate_fn=snake_case__    )
  
    # Compute head entropy and importance score
    compute_heads_importance(snake_case__	,      snake_case__	,      snake_case__    )
  
    # Try head masking (set heads to zero until the score goes under a threshole)
    # and head pruning (remove masked heads and see the effect on the network)
    if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
      _UpperCAmelCase		:       Union[str, Any]       =    mask_heads(snake_case__	,      snake_case__	,      snake_case__    )
      prune_heads(snake_case__	,      snake_case__	,      snake_case__	,      snake_case__    )
  
  
  if __name__ == "__main__":
   main()
  
  
  
  
  
  
style_context: 
  
  
  import math
  from dataclasses import dataclass
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  import torch
  from transformers import CLIPTextModelWithProjection, CLIPTokenizer
  
  from ...models import PriorTransformer
  from ...pipelines import DiffusionPipeline
  from ...schedulers import HeunDiscreteScheduler
  from ...utils import (
      BaseOutput,
      is_accelerate_available,
      is_accelerate_version,
      logging,
      randn_tensor,
      replace_example_docstring,
  )
  from .renderer import ShapERenderer
  
  
  SCREAMING_SNAKE_CASE__				:    Optional[int]         =    logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  SCREAMING_SNAKE_CASE__				:    Tuple         =    '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")\n        ```\n'
  
  
  @dataclass
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						42
  
  
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
  
  
       def __init__(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				):
         super().__init__()
  
         self.register_modules(
             prior=A_       ,				text_encoder=A_       ,				tokenizer=A_       ,				scheduler=A_       ,				renderer=A_       ,				)
  
  
       def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_						):
         if latents is None:
           _UpperCAmelCase		:       List[Any]       =    randn_tensor(A_       ,				generator=A_       ,				device=A_       ,				dtype=A_						)
         else:
           if latents.shape != shape:
             raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''						)
           _UpperCAmelCase		:       Optional[int]       =    latents.to(A_						)
  
         _UpperCAmelCase		:       str       =    latents * scheduler.init_noise_sigma
         return latents
  
  
       def 					__snake_case(     self       ,				A_=0						):
         if is_accelerate_available():
           from accelerate import cpu_offload
         else:
           raise ImportError("""Please install accelerate via `pip install accelerate`"""						)
  
         _UpperCAmelCase		:       Any       =    torch.device(F'''cuda:{gpu_id}'''						)
  
         _UpperCAmelCase		:       Dict       =    [self.text_encoder, self.prior]
         for cpu_offloaded_model in models:
           if cpu_offloaded_model is not None:
             cpu_offload(A_       ,				A_						)
  
  
       def 					__snake_case(     self       ,				A_=0						):
         if is_accelerate_available() and is_accelerate_version(""">="""       ,				"""0.17.0.dev0"""						):
           from accelerate import cpu_offload_with_hook
         else:
           raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""						)
  
         _UpperCAmelCase		:       int       =    torch.device(F'''cuda:{gpu_id}'''						)
  
         if self.device.type != "cpu":
           self.to("""cpu"""       ,				silence_dtype_warnings=A_						)
           torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
         _UpperCAmelCase		:       List[str]       =    None
         for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
           _UpperCAmelCase,_UpperCAmelCase		:       List[Any]       =    cpu_offload_with_hook(A_       ,				A_       ,				prev_module_hook=A_						)
  
         if self.safety_checker is not None:
           _UpperCAmelCase,_UpperCAmelCase		:       int       =    cpu_offload_with_hook(self.safety_checker       ,				A_       ,				prev_module_hook=A_						)
  
         # We'll offload the last model manually.
         _UpperCAmelCase		:       Optional[Any]       =    hook
  
  
       @property
       def 					__snake_case(     self						):
         if self.device != torch.device("""meta"""						) or not hasattr(self.text_encoder       ,				"""_hf_hook"""						):
           return self.device
         for module in self.text_encoder.modules():
           if (
               hasattr(A_       ,				"""_hf_hook"""						)
               and hasattr(module._hf_hook       ,				"""execution_device"""						)
               and module._hf_hook.execution_device is not None
           ):
             return torch.device(module._hf_hook.execution_device						)
         return self.device
  
  
       def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				):
         len(A_						) if isinstance(A_       ,				A_						) else 1
  
         # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
         _UpperCAmelCase		:       str       =    0
         # get prompt text embeddings
         _UpperCAmelCase		:       List[str]       =    self.tokenizer(
             A_       ,				padding="""max_length"""       ,				max_length=self.tokenizer.model_max_length       ,				truncation=A_       ,				return_tensors="""pt"""       ,				)
         _UpperCAmelCase		:       Any       =    text_inputs.input_ids
         _UpperCAmelCase		:       Dict       =    self.tokenizer(A_       ,				padding="""longest"""       ,				return_tensors="""pt"""						).input_ids
  
         if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(A_       ,				A_						):
           _UpperCAmelCase		:       Union[str, Any]       =    self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]						)
           logger.warning(
               """The following part of your input was truncated because CLIP can only handle sequences up to"""
               F''' {self.tokenizer.model_max_length} tokens: {removed_text}'''						)
  
         _UpperCAmelCase		:       List[Any]       =    self.text_encoder(text_input_ids.to(A_						)						)
         _UpperCAmelCase		:       Union[str, Any]       =    text_encoder_output.text_embeds
  
         _UpperCAmelCase		:       Tuple       =    prompt_embeds.repeat_interleave(A_       ,				dim=0						)
         # in Shap-E it normalize the prompt_embeds and then later rescale it
         _UpperCAmelCase		:       Any       =    prompt_embeds / torch.linalg.norm(A_       ,				dim=-1       ,				keepdim=A_						)
  
         if do_classifier_free_guidance:
           _UpperCAmelCase		:       Union[str, Any]       =    torch.zeros_like(A_						)
  
           # For classifier free guidance, we need to do two forward passes.
           # Here we concatenate the unconditional and text embeddings into a single batch
           # to avoid doing two forward passes
           _UpperCAmelCase		:       Optional[Any]       =    torch.cat([negative_prompt_embeds, prompt_embeds]						)
  
         # Rescale the features to have unit variance
         _UpperCAmelCase		:       List[Any]       =    math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds
  
         return prompt_embeds
  
  
  
  
       @torch.no_grad()
       @replace_example_docstring(A_						)
       def __call__(     self       ,				A_       ,				A_ = 1       ,				A_ = 25       ,				A_ = None       ,				A_ = None       ,				A_ = 4.0       ,				A_ = 64       ,				A_ = "pil"       ,				A_ = True       ,				):
  
         if isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       Optional[int]       =    1
         elif isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       Union[str, Any]       =    len(A_						)
         else:
           raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A_						)}'''						)
  
         _UpperCAmelCase		:       Tuple       =    self._execution_device
  
         _UpperCAmelCase		:       List[str]       =    batch_size * num_images_per_prompt
  
         _UpperCAmelCase		:       str       =    guidance_scale > 1.0
         _UpperCAmelCase		:       Tuple       =    self._encode_prompt(A_       ,				A_       ,				A_       ,				A_						)
  
         # prior
  
         self.scheduler.set_timesteps(A_       ,				device=A_						)
         _UpperCAmelCase		:       Any       =    self.scheduler.timesteps
  
         _UpperCAmelCase		:       List[str]       =    self.prior.config.num_embeddings
         _UpperCAmelCase		:       Union[str, Any]       =    self.prior.config.embedding_dim
  
         _UpperCAmelCase		:       Optional[Any]       =    self.prepare_latents(
             (batch_size, num_embeddings * embedding_dim)       ,				prompt_embeds.dtype       ,				A_       ,				A_       ,				A_       ,				self.scheduler       ,				)
  
         # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
         _UpperCAmelCase		:       Optional[Any]       =    latents.reshape(latents.shape[0]       ,				A_       ,				A_						)
  
         for i, t in enumerate(self.progress_bar(A_						)						):
           # expand the latents if we are doing classifier free guidance
           _UpperCAmelCase		:       Optional[int]       =    torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
           _UpperCAmelCase		:       Union[str, Any]       =    self.scheduler.scale_model_input(A_       ,				A_						)
  
           _UpperCAmelCase		:       Any       =    self.prior(
               A_       ,				timestep=A_       ,				proj_embedding=A_       ,				).predicted_image_embedding
  
           # remove the variance
           _UpperCAmelCase,_UpperCAmelCase		:       Dict       =    noise_pred.split(
               scaled_model_input.shape[2]       ,				dim=2						)  # batch_size, num_embeddings, embedding_dim
  
           if do_classifier_free_guidance is not None:
             _UpperCAmelCase,_UpperCAmelCase		:       Union[str, Any]       =    noise_pred.chunk(2						)
             _UpperCAmelCase		:       List[Any]       =    noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
           _UpperCAmelCase		:       Tuple       =    self.scheduler.step(
               A_       ,				timestep=A_       ,				sample=A_       ,				).prev_sample
  
         if output_type == "latent":
           return ShapEPipelineOutput(images=A_						)
  
         _UpperCAmelCase		:       Dict       =    []
         for i, latent in enumerate(A_						):
           _UpperCAmelCase		:       int       =    self.renderer.decode(
               latent[None, :]       ,				A_       ,				size=A_       ,				ray_batch_size=40_96       ,				n_coarse_samples=64       ,				n_fine_samples=1_28       ,				)
           images.append(A_						)
  
         _UpperCAmelCase		:       List[Any]       =    torch.stack(A_						)
  
         if output_type not in ["np", "pil"]:
           raise ValueError(F'''Only the output types `pil` and `np` are supported not output_type={output_type}'''						)
  
         _UpperCAmelCase		:       str       =    images.cpu().numpy()
  
         if output_type == "pil":
           _UpperCAmelCase		:       List[str]       =    [self.numpy_to_pil(A_						) for image in images]
  
         # Offload last model to CPU
         if hasattr(self       ,				"""final_offload_hook"""						) and self.final_offload_hook is not None:
           self.final_offload_hook.offload()
  
         if not return_dict:
           return (images,)
  
         return ShapEPipelineOutput(images=A_						)
  
  
  
  
  
  