





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       : Any						    = logging.get_logger(__name__)  # pylint: disable=invalid-name

__A       : List[str]						    = "\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     lowerCamelCase(	__snake_case  ):
     '''simple docstring'''


     __magic_name__        = 42







class     lowerCamelCase(	__snake_case  ):
     '''simple docstring'''


     def __init__(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         super().__init__()

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




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_       ):
         if latents is None:
             _A    =       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}"       )
             _A    =       latents.to(snake_case_       )

         _A    =       latents * scheduler.init_noise_sigma
         return latents




     def 					lowerCAmelCase__		(						self							,    snake_case_=0       ):
         if is_accelerate_available():
             from accelerate import cpu_offload
         else:
             raise ImportError('Please install accelerate via `pip install accelerate`'       )

         _A    =       torch.device(F"cuda:{gpu_id}"       )

         _A    =       [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 					lowerCAmelCase__		(						self							,    snake_case_=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.'       )

         _A    =       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)

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

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

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




     @property
     def 					lowerCAmelCase__		(						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(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 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_							,    snake_case_							,    ):
         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
         _A    =       0
         # get prompt text embeddings
         _A    =       self.tokenizer(
             snake_case_							,    padding='max_length'							,    max_length=self.tokenizer.model_max_length							,    truncation=snake_case_							,    return_tensors='pt'							,    )
         _A    =       text_inputs.input_ids
         _A    =       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_       ):
             _A    =       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}"       )

         _A    =       self.text_encoder(text_input_ids.to(snake_case_       )       )
         _A    =       text_encoder_output.text_embeds

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

         if do_classifier_free_guidance:
             _A    =       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
             _A    =       torch.cat([negative_prompt_embeds, prompt_embeds]       )

         # Rescale the features to have unit variance
         _A    =       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							,    ):

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

         _A    =       self._execution_device

         _A    =       batch_size * num_images_per_prompt

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

         # prior

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

         _A    =       self.prior.config.num_embeddings
         _A    =       self.prior.config.embedding_dim

         _A    =       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
         _A    =       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
             _A    =       torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents
             _A    =       self.scheduler.scale_model_input(snake_case_							,    snake_case_       )

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

             # remove the variance
             _A, _A    =       noise_pred.split(
                 scaled_model_input.shape[2]							,    dim=2       )  # batch_size, num_embeddings, embedding_dim

             if do_classifier_free_guidance is not None:
                 _A, _A    =       noise_pred.chunk(2       )
                 _A    =       noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

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

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

         _A    =       []
         for i, latent in enumerate(snake_case_       ):
             _A    =       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_       )

         _A    =       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}"       )

         _A    =       images.cpu().numpy()

         if output_type == "pil":
             _A    =       [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_       )












import argparse

import torch
from flax.training.checkpoints import restore_checkpoint

from transformers import FNetConfig, FNetForPreTraining
from transformers.utils import logging


logging.set_verbosity_info()





def 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)       ->   List[str]:




    """simple docstring"""




    _A    =       FNetConfig.from_json_file(_SCREAMING_SNAKE_CASE							)
    print(F"Building PyTorch model from configuration: {config}"							)
    _A    =       FNetForPreTraining(_SCREAMING_SNAKE_CASE							)

    _A    =       restore_checkpoint(_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)
    _A    =       checkpoint_dict['target']

    # Embeddings
    # Position IDs
    _A    =       fnet_pretraining_model.state_dict()

    _A    =       state_dict['fnet.embeddings.position_ids']
    _A    =       {'fnet.embeddings.position_ids': position_ids}
    # Embedding Layers
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['word']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['position']['embedding'][0]							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['type']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['hidden_mapping_in']['kernel']							).T
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['hidden_mapping_in']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['layer_norm']['scale']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['layer_norm']['bias']							)

    # Encoder Layers
    for layer in range(config.num_hidden_layers							):
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['mixing_layer_norm']['scale']							)
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['mixing_layer_norm']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['intermediate']['kernel']							).T
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['intermediate']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['output']['kernel']							).T
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"feed_forward_{layer}"]['output']['bias']							)

        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['output_layer_norm']['scale']							)
        _A    =       torch.tensor(
            pretrained_model_params['encoder'][F"encoder_{layer}"]['output_layer_norm']['bias']							)

    # Pooler Layers
    _A    =       torch.tensor(pretrained_model_params['encoder']['pooler']['kernel']							).T
    _A    =       torch.tensor(pretrained_model_params['encoder']['pooler']['bias']							)

    # Masked LM Layers
    _A    =       torch.tensor(
        pretrained_model_params['predictions_dense']['kernel']							).T
    _A    =       torch.tensor(
        pretrained_model_params['predictions_dense']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_layer_norm']['scale']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_layer_norm']['bias']							)
    _A    =       torch.tensor(
        pretrained_model_params['encoder']['embedder']['word']['embedding']							)
    _A    =       torch.tensor(
        pretrained_model_params['predictions_output']['output_bias']							)
    _A    =       torch.tensor(pretrained_model_params['predictions_output']['output_bias']							)

    # Seq Relationship Layers
    _A    =       torch.tensor(
        pretrained_model_params['classification']['output_kernel']							)
    _A    =       torch.tensor(
        pretrained_model_params['classification']['output_bias']							)

    # Load State Dict
    fnet_pretraining_model.load_state_dict(_SCREAMING_SNAKE_CASE							)

    # Save PreTrained
    print(F"Saving pretrained model to {save_path}"							)
    fnet_pretraining_model.save_pretrained(_SCREAMING_SNAKE_CASE							)


if __name__ == "__main__":
 __A       : str						    = argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--flax_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
 )
 parser.add_argument(
     "--fnet_config_file",
     default=None,
     type=str,
     required=True,
     help=(
         "The config json file corresponding to the pre-trained FNet model. \n"
         "This specifies the model architecture."
     ),
 )
 parser.add_argument("--save_path", default=None, type=str, required=True, help="Path to the output model.")
 __A       : Any						    = parser.parse_args()
 convert_flax_checkpoint_to_pytorch(args.flax_checkpoint_path, args.fnet_config_file, args.save_path)





