






"""simple docstring"""





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


A__       :			List[Any]=						logging.get_logger(__name__)  # pylint: disable=invalid-name

A__       :			Dict=						"""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""
@dataclass
class  __lowerCamelCase     (	_a	):
   a   :					Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class  __lowerCamelCase     (	_a	):

   def __init__(       self			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_			,					)		->							Union[str, Any]:
       super().__init__()

       self.register_modules(
           prior=snake_case_			,					text_encoder=snake_case_			,					tokenizer=snake_case_			,					scheduler=snake_case_			,					renderer=snake_case_			,					)

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_   )		->							Tuple:
       if latents is None:
           UpperCamelCase__								=     randn_tensor(snake_case_			,					generator=snake_case_			,					device=snake_case_			,					dtype=snake_case_   )
       else:
           if latents.shape != shape:
               raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'   )
           UpperCamelCase__								=     latents.to(snake_case_   )

       UpperCamelCase__								=     latents * scheduler.init_noise_sigma
       return latents

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_=0   )		->							Optional[int]:
       if is_accelerate_available():
           from accelerate import cpu_offload
       else:
           raise ImportError('Please install accelerate via `pip install accelerate`'   )

       UpperCamelCase__								=     torch.device(F'cuda:{gpu_id}'   )

       UpperCamelCase__								=     [self.text_encoder, self.prior]
       for cpu_offloaded_model in models:
           if cpu_offloaded_model is not None:
               cpu_offload(snake_case_			,					snake_case_   )

   def     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_=0   )		->							List[str]:
       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__								=     torch.device(F'cuda:{gpu_id}'   )

       if self.device.type != "cpu":
           self.to('cpu'			,					silence_dtype_warnings=snake_case_   )
           torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

       UpperCamelCase__								=     None
       for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
           UpperCamelCase__							,    UpperCamelCase__								=     cpu_offload_with_hook(snake_case_			,					snake_case_			,					prev_module_hook=snake_case_   )

       if self.safety_checker is not None:
           UpperCamelCase__							,    UpperCamelCase__								=     cpu_offload_with_hook(self.safety_checker			,					snake_case_			,					prev_module_hook=snake_case_   )

       # We'll offload the last model manually.
       UpperCamelCase__								=     hook

   @property
   def     SCREAMING_SNAKE_CASE__			(       self   )		->							Dict:
       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(snake_case_			,					'_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     SCREAMING_SNAKE_CASE__			(       self			,					snake_case_			,					snake_case_			,					snake_case_			,					snake_case_			,					)		->							Dict:
       len(snake_case_   ) if isinstance(snake_case_			,					snake_case_   ) else 1

       # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
       UpperCamelCase__								=     0
       # get prompt text embeddings
       UpperCamelCase__								=     self.tokenizer(
           snake_case_			,					padding='max_length'			,					max_length=self.tokenizer.model_max_length			,					truncation=snake_case_			,					return_tensors='pt'			,					)
       UpperCamelCase__								=     text_inputs.input_ids
       UpperCamelCase__								=     self.tokenizer(snake_case_			,					padding='longest'			,					return_tensors='pt'   ).input_ids

       if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(snake_case_			,					snake_case_   ):
           UpperCamelCase__								=     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__								=     self.text_encoder(text_input_ids.to(snake_case_   )   )
       UpperCamelCase__								=     text_encoder_output.text_embeds

       UpperCamelCase__								=     prompt_embeds.repeat_interleave(snake_case_			,					dim=0   )
       # in Shap-E it normalize the prompt_embeds and then later rescale it
       UpperCamelCase__								=     prompt_embeds / torch.linalg.norm(snake_case_			,					dim=-1			,					keepdim=snake_case_   )

       if do_classifier_free_guidance:
           UpperCamelCase__								=     torch.zeros_like(snake_case_   )

           # 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__								=     torch.cat([negative_prompt_embeds, prompt_embeds]   )

       # Rescale the features to have unit variance
       UpperCamelCase__								=     math.sqrt(prompt_embeds.shape[1]   ) * prompt_embeds

       return prompt_embeds







   @torch.no_grad()
   @replace_example_docstring(snake_case_   )
   def __call__(       self			,					snake_case_			,					snake_case_ = 1			,					snake_case_ = 25			,					snake_case_ = None			,					snake_case_ = None			,					snake_case_ = 4.0			,					snake_case_ = 64			,					snake_case_ = "pil"			,					snake_case_ = True			,					)		->							Optional[int]:

       if isinstance(snake_case_			,					snake_case_   ):
           UpperCamelCase__								=     1
       elif isinstance(snake_case_			,					snake_case_   ):
           UpperCamelCase__								=     len(snake_case_   )
       else:
           raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(snake_case_   )}'   )

       UpperCamelCase__								=     self._execution_device

       UpperCamelCase__								=     batch_size * num_images_per_prompt

       UpperCamelCase__								=     guidance_scale > 1.0
       UpperCamelCase__								=     self._encode_prompt(snake_case_			,					snake_case_			,					snake_case_			,					snake_case_   )

       # prior

       self.scheduler.set_timesteps(snake_case_			,					device=snake_case_   )
       UpperCamelCase__								=     self.scheduler.timesteps

       UpperCamelCase__								=     self.prior.config.num_embeddings
       UpperCamelCase__								=     self.prior.config.embedding_dim

       UpperCamelCase__								=     self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)			,					prompt_embeds.dtype			,					snake_case_			,					snake_case_			,					snake_case_			,					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__								=     latents.reshape(latents.shape[0]			,					snake_case_			,					snake_case_   )

       for i, t in enumerate(self.progress_bar(snake_case_   )   ):
           # expand the latents if we are doing classifier free guidance
           UpperCamelCase__								=     torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
           UpperCamelCase__								=     self.scheduler.scale_model_input(snake_case_			,					snake_case_   )

           UpperCamelCase__								=     self.prior(
               snake_case_			,					timestep=snake_case_			,					proj_embedding=snake_case_			,					).predicted_image_embedding

           # remove the variance
           UpperCamelCase__							,    UpperCamelCase__								=     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__								=     noise_pred.chunk(2   )
               UpperCamelCase__								=     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

           UpperCamelCase__								=     self.scheduler.step(
               snake_case_			,					timestep=snake_case_			,					sample=snake_case_			,					).prev_sample

       if output_type == "latent":
           return ShapEPipelineOutput(images=snake_case_   )

       UpperCamelCase__								=     []
       for i, latent in enumerate(snake_case_   ):
           UpperCamelCase__								=     self.renderer.decode(
               latent[None, :]			,					snake_case_			,					size=snake_case_			,					ray_batch_size=4096			,					n_coarse_samples=64			,					n_fine_samples=128			,					)
           images.append(snake_case_   )

       UpperCamelCase__								=     torch.stack(snake_case_   )

       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__								=     images.cpu().numpy()

       if output_type == "pil":
           UpperCamelCase__								=     [self.numpy_to_pil(snake_case_   ) 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=snake_case_   )












"""simple docstring"""





import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE=0       )       ->						str:
    """simple docstring"""

    if name is None:
        UpperCamelCase__								=     None
    else:
        UpperCamelCase__								=     '.' * max(0			,						spaces - 2       ) + '# {:' + str(50 - spaces       ) + 's}'
        UpperCamelCase__								=     fmt.format(SCREAMING_SNAKE_CASE       )

    # Print and recurse (if needed).
    if isinstance(SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       ):
        if msg is not None:
            print(SCREAMING_SNAKE_CASE       )
        for k in val.keys():
            recursive_print(SCREAMING_SNAKE_CASE			,						val[k]			,						spaces + 2       )
    elif isinstance(SCREAMING_SNAKE_CASE			,						torch.Tensor       ):
        print(SCREAMING_SNAKE_CASE			,						':'			,						val.size()       )
    else:
        print(SCREAMING_SNAKE_CASE			,						':'			,						SCREAMING_SNAKE_CASE       )







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )       ->						Tuple:
    """simple docstring"""

    UpperCamelCase__								=     param.size()
    # other versions store [num_heads * num_splits * hidden_size, :]
    UpperCamelCase__								=     (num_heads, num_splits, hidden_size) + input_shape[1:]
    UpperCamelCase__								=     param.view(*SCREAMING_SNAKE_CASE       )
    UpperCamelCase__								=     param.transpose(0			,						1       ).contiguous()
    UpperCamelCase__								=     param.view(*SCREAMING_SNAKE_CASE       )
    return param







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )       ->						Any:
    """simple docstring"""

    UpperCamelCase__								=     config.n_positions
    UpperCamelCase__								=     config.n_layer
    UpperCamelCase__								=     config.vocab_size
    UpperCamelCase__								=     config.n_head
    UpperCamelCase__								=     config.n_embd // config.n_head

    UpperCamelCase__								=     sd_megatron['model.language_model.embedding.word_embeddings.weight'][:vocab_size, :]
    UpperCamelCase__								=     {
        'transformer.wte.weight': word_embeddings,
        'transformer.wpe.weight': sd_megatron['model.language_model.embedding.position_embeddings.weight'],
        'transformer.ln_f.weight': sd_megatron['model.language_model.encoder.final_layernorm.weight'],
        'transformer.ln_f.bias': sd_megatron['model.language_model.encoder.final_layernorm.bias'],
    }

    UpperCamelCase__								=     'model.language_model.encoder.layers.'
    for i in range(SCREAMING_SNAKE_CASE       ):
        UpperCamelCase__								=     torch.tril(torch.ones((n_positions, n_positions)			,						dtype=torch.bool       )       )
        UpperCamelCase__								=     causal_mask.view(1			,						1			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )
        UpperCamelCase__								=     causal_mask
        UpperCamelCase__								=     torch.tensor(-1E4			,						dtype=torch.bfloataa       )

        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.input_layernorm.weight']
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.input_layernorm.bias']

        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.self_attention.query_key_value.weight']
        UpperCamelCase__								=     fix_query_key_value_ordering(SCREAMING_SNAKE_CASE			,						3			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )
        UpperCamelCase__								=     vala.transpose(0			,						1       ).contiguous()

        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.self_attention.query_key_value.bias']
        UpperCamelCase__								=     fix_query_key_value_ordering(SCREAMING_SNAKE_CASE			,						3			,						SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )
        UpperCamelCase__								=     vala

        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.self_attention.dense.weight'].transpose(
            0			,						1       )
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.self_attention.dense.bias']
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.post_attention_layernorm.weight']
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.post_attention_layernorm.bias']
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.mlp.dense_h_to_4h.weight'].transpose(0			,						1       )
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.mlp.dense_h_to_4h.bias']
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.mlp.dense_4h_to_h.weight'].transpose(
            0			,						1       )
        UpperCamelCase__								=     sd_megatron[F'{pf}{i}.mlp.dense_4h_to_h.bias']

    # For LM head, transformers' wants the matrix to weight embeddings.
    UpperCamelCase__								=     word_embeddings

    return sd_hf







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )       ->						int:
    """simple docstring"""

    UpperCamelCase__								=     6_40_00
    UpperCamelCase__								=     config_megatron['encoder_seq_length']
    UpperCamelCase__								=     config_megatron['hidden_size']
    UpperCamelCase__								=     config_megatron['num_layers']
    UpperCamelCase__								=     config_megatron['num_attention_heads']
    UpperCamelCase__								=     config_megatron['ffn_hidden_size']
    UpperCamelCase__								=     'gelu'
    UpperCamelCase__								=     0.1
    UpperCamelCase__								=     0.1
    UpperCamelCase__								=     0.1
    UpperCamelCase__								=     config_megatron['layernorm_epsilon']  # 1e-5
    UpperCamelCase__								=     config_megatron['init_method_std']  # 0.02
    UpperCamelCase__								=     config_megatron['apply_query_key_layer_scaling']  # True
    UpperCamelCase__								=     True
    UpperCamelCase__								=     True

    # This identifies the 6.7B (7B) model which uses a different tokenizer
    if config_megatron["hidden_size"] == 40_96:
        UpperCamelCase__								=     1  # <|endoftext|>
        UpperCamelCase__								=     1  # <|endoftext|>
        UpperCamelCase__								=     0  # <unk>
    else:
        UpperCamelCase__								=     2  # <s>
        UpperCamelCase__								=     3  # <|endoftext|>
        UpperCamelCase__								=     0  # <pad>

    return config_hf







def 	lowerCAmelCase_(			SCREAMING_SNAKE_CASE       )       ->						str:
    """simple docstring"""

    print(SCREAMING_SNAKE_CASE       )

    UpperCamelCase__								=     args.checkpoint_path
    UpperCamelCase__								=     args.save_path
    if isfile(SCREAMING_SNAKE_CASE       ):
        raise FileNotFoundError(F'ERROR! could not find file {checkpoint_path}'       )

    # Load the model.
    UpperCamelCase__								=     torch.load(SCREAMING_SNAKE_CASE			,						map_location='cpu'       )

    # Load the config.
    UpperCamelCase__								=     checkpoint['hyper_parameters']['cfg']
    UpperCamelCase__								=     GPTaConfig()
    UpperCamelCase__								=     copy_config(config_hf=SCREAMING_SNAKE_CASE			,						config_megatron=SCREAMING_SNAKE_CASE       )
    UpperCamelCase__								=     ['GPT2LMHeadModel']

    UpperCamelCase__								=     checkpoint['state_dict']

    # Convert.
    print('Converting'       )
    UpperCamelCase__								=     convert_megatron_checkpoint(SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )

    # Print the structure of converted state dict.
    if args.print_checkpoint_structure:
        recursive_print(SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )

    UpperCamelCase__								=     'GPTSw3Tokenizer'

    # Store the config to file.
    print('Saving config'       )
    config_hf.save_pretrained(SCREAMING_SNAKE_CASE       )

    # Store the state_dict to file.
    UpperCamelCase__								=     os.path.join(SCREAMING_SNAKE_CASE			,						'pytorch_model.bin'       )
    print(F'Saving checkpoint to "{output_checkpoint_file}"'       )
    torch.save(SCREAMING_SNAKE_CASE			,						SCREAMING_SNAKE_CASE       )


if __name__ == "__main__":
  A__       :			Optional[Any]=						argparse.ArgumentParser()
  parser.add_argument(
      """--checkpoint_path""",
      type=str,
      required=True,
      help="""e.g. megatron_gpt--val_loss=2.42-step=38000-consumed_samples=54720000""",
  )
  parser.add_argument("""--save_path""", type=str, required=True, help="""e.g. /home/user/gpt-sw3/hf""")
  parser.add_argument("""--print-checkpoint-structure""", action="""store_true""")
  A__       :			Any=						parser.parse_args()
  main(_args)




