
'''simple docstring'''






import unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers.models.esm.modeling_esmfold import EsmForProteinFolding

class  UpperCAmelCase__						:



    def __init__(	self      :       Optional[int],__A      :       Union[str, Any],__A      :       Union[str, Any]=1_3,__A      :       Union[str, Any]=7,__A      :       Tuple=False,__A      :       int=True,__A      :       int=False,__A      :       List[str]=False,__A      :       int=1_9,__A      :       Optional[Any]=3_2,__A      :       int=5,__A      :       str=4,__A      :       Optional[int]=3_7,__A      :       Dict="gelu",__A      :       Union[str, Any]=0.1,__A      :       List[str]=0.1,__A      :       Optional[Any]=5_1_2,__A      :       Optional[Any]=1_6,__A      :       Union[str, Any]=2,__A      :       Union[str, Any]=0.02,__A      :       str=3,__A      :       Optional[Any]=4,__A      :       str=None,):
          _lowerCamelCase				:   Any								=   parent
          _lowerCamelCase				:   Dict								=   batch_size
          _lowerCamelCase				:   str								=   seq_length
          _lowerCamelCase				:   int								=   is_training
          _lowerCamelCase				:   Tuple								=   use_input_mask
          _lowerCamelCase				:   List[Any]								=   use_token_type_ids
          _lowerCamelCase				:   Optional[int]								=   use_labels
          _lowerCamelCase				:   Any								=   vocab_size
          _lowerCamelCase				:   Dict								=   hidden_size
          _lowerCamelCase				:   Optional[int]								=   num_hidden_layers
          _lowerCamelCase				:   int								=   num_attention_heads
          _lowerCamelCase				:   str								=   intermediate_size
          _lowerCamelCase				:   Tuple								=   hidden_act
          _lowerCamelCase				:   Union[str, Any]								=   hidden_dropout_prob
          _lowerCamelCase				:   Union[str, Any]								=   attention_probs_dropout_prob
          _lowerCamelCase				:   Optional[int]								=   max_position_embeddings
          _lowerCamelCase				:   Tuple								=   type_vocab_size
          _lowerCamelCase				:   int								=   type_sequence_label_size
          _lowerCamelCase				:   List[str]								=   initializer_range
          _lowerCamelCase				:   Optional[int]								=   num_labels
          _lowerCamelCase				:   int								=   num_choices
          _lowerCamelCase				:   Dict								=   scope



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   List[Any]								=   ids_tensor([self.batch_size, self.seq_length],self.vocab_size     )

          _lowerCamelCase				:   Optional[Any]								=   None
          if self.use_input_mask:
                _lowerCamelCase				:   Tuple								=   random_attention_mask([self.batch_size, self.seq_length]     )

          _lowerCamelCase				:   Any								=   None
          _lowerCamelCase				:   Any								=   None
          _lowerCamelCase				:   List[Any]								=   None
          if self.use_labels:
                _lowerCamelCase				:   Any								=   ids_tensor([self.batch_size],self.type_sequence_label_size     )
                _lowerCamelCase				:   Any								=   ids_tensor([self.batch_size, self.seq_length],self.num_labels     )
                _lowerCamelCase				:   Tuple								=   ids_tensor([self.batch_size],self.num_choices     )

          _lowerCamelCase				:   Union[str, Any]								=   self.get_config()

          return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   List[Any]								=   EsmConfig(
              vocab_size=3_3,hidden_size=self.hidden_size,pad_token_id=1,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,max_position_embeddings=self.max_position_embeddings,type_vocab_size=self.type_vocab_size,initializer_range=self.initializer_range,is_folding_model=__A,esmfold_config={"trunk": {"num_blocks": 2}, "fp16_esm": False},)
          return config



    def   lowerCamelCase_  (	self      :       Any,__A      :       Optional[Any],__A      :       int,__A      :       List[Any],__A      :       Tuple,__A      :       int,__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   int								=   EsmForProteinFolding(config=__A     ).float()
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   int								=   model(__A,attention_mask=__A     )
          _lowerCamelCase				:   Optional[int]								=   model(__A     )
          _lowerCamelCase				:   Optional[int]								=   model(__A     )

          self.parent.assertEqual(result.positions.shape,(8, self.batch_size, self.seq_length, 1_4, 3)     )
          self.parent.assertEqual(result.angles.shape,(8, self.batch_size, self.seq_length, 7, 2)     )



    def   lowerCamelCase_  (	self      :       Any     ):
          _lowerCamelCase				:   Union[str, Any]								=   self.prepare_config_and_inputs()
          (
              _lowerCamelCase		
          )				:   Dict								=   config_and_inputs
          _lowerCamelCase				:   List[str]								=   {"input_ids": input_ids, "attention_mask": input_mask}
          return config, inputs_dict


@require_torch
class  UpperCAmelCase__						(       A						,	A						,	unittest.TestCase ):
    lowerCAmelCase_				    =		False

    lowerCAmelCase_				    =		(EsmForProteinFolding,) if is_torch_available() else ()
    lowerCAmelCase_				    =		()
    lowerCAmelCase_				    =		{} if is_torch_available() else {}
    lowerCAmelCase_				    =		False



    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          _lowerCamelCase				:   Any								=   EsmFoldModelTester(self     )
          _lowerCamelCase				:   str								=   ConfigTester(self,config_class=__A,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          self.config_tester.run_common_tests()



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   Tuple								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__A     )



    @unittest.skip("Does not support attention outputs"     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("Esm does not support embedding resizing"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("Esm does not support embedding resizing"     )
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("ESMFold does not support passing input embeds!"     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold does not support head pruning."     )
    def   lowerCamelCase_  (	self      :       int     ):
          pass



    @unittest.skip("ESMFold does not output hidden states in the normal way."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMfold does not output hidden states in the normal way."     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip("ESMFold only has one output format."     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    @unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("ESMFold does not support input chunking."     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments."     )
    def   lowerCamelCase_  (	self      :       str     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



    @unittest.skip("ESMFold doesn't support torchscript compilation."     )
    def   lowerCamelCase_  (	self      :       List[str]     ):
          pass



    @unittest.skip("ESMFold doesn't support data parallel."     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."     )
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          pass


@require_torch
class  UpperCAmelCase__						(       A ):



    @slow
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   Any								=   EsmForProteinFolding.from_pretrained("facebook/esmfold_v1"     ).float()
          model.eval()
          _lowerCamelCase				:   Dict								=   torch.tensor([[0, 6, 4, 1_3, 5, 4, 1_6, 1_2, 1_1, 7, 2]]     )
          _lowerCamelCase				:   Tuple								=   model(__A     )["positions"]
          _lowerCamelCase				:   Optional[int]								=   torch.tensor([2.5828, 0.7993, -10.9334],dtype=torch.floataa     )
          self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0],__A,atol=1e-4     )     )

'''simple docstring'''






from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


UpperCAmelCase_       :   str   =       logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase_       :   str   =       '\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\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], "corgi_3d.gif")\n        ```\n'

@dataclass
class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		42


class  UpperCAmelCase__						(       A ):



    def __init__(	self      :       str,__A      :       PriorTransformer,__A      :       CLIPVisionModel,__A      :       CLIPImageProcessor,__A      :       HeunDiscreteScheduler,__A      :       ShapERenderer,):
          super().__init__()

          self.register_modules(
              prior=__A,image_encoder=__A,image_processor=__A,scheduler=__A,renderer=__A,)



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       str,__A      :       Tuple,__A      :       Any,__A      :       Optional[int],__A      :       Tuple,__A      :       Union[str, Any]     ):
          if latents is None:
                _lowerCamelCase				:   int								=   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}'     )
                _lowerCamelCase				:   Union[str, Any]								=   latents.to(__A     )

          _lowerCamelCase				:   Tuple								=   latents * scheduler.init_noise_sigma
          return latents



    def   lowerCamelCase_  (	self      :       List[str],__A      :       List[Any]=0     ):
          if is_accelerate_available():
                from accelerate import cpu_offload
          else:
                raise ImportError("Please install accelerate via `pip install accelerate`"     )

          _lowerCamelCase				:   List[Any]								=   torch.device(f'cuda:{gpu_id}'     )

          _lowerCamelCase				:   Tuple								=   [self.image_encoder, self.prior]
          for cpu_offloaded_model in models:
                if cpu_offloaded_model is not None:
                      cpu_offload(__A,__A     )



    @property
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          if self.device != torch.device("meta"     ) or not hasattr(self.image_encoder,"_hf_hook"     ):
                return self.device
          for module in self.image_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   lowerCamelCase_  (	self      :       Tuple,__A      :       int,__A      :       Any,__A      :       str,__A      :       int,):
          if isinstance(__A,__A     ) and isinstance(image[0],torch.Tensor     ):
                _lowerCamelCase				:   Dict								=   torch.cat(__A,axis=0     ) if image[0].ndim == 4 else torch.stack(__A,axis=0     )

          if not isinstance(__A,torch.Tensor     ):
                _lowerCamelCase				:   str								=   self.image_processor(__A,return_tensors="pt"     ).pixel_values[0].unsqueeze(0     )

          _lowerCamelCase				:   Any								=   image.to(dtype=self.image_encoder.dtype,device=__A     )

          _lowerCamelCase				:   List[str]								=   self.image_encoder(__A     )["last_hidden_state"]
          _lowerCamelCase				:   Optional[Any]								=   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

          _lowerCamelCase				:   Any								=   image_embeds.repeat_interleave(__A,dim=0     )

          if do_classifier_free_guidance:
                _lowerCamelCase				:   int								=   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
                _lowerCamelCase				:   Union[str, Any]								=   torch.cat([negative_image_embeds, image_embeds]     )

          return image_embeds



    @torch.no_grad()
    @replace_example_docstring(__A     )
    def __call__(	self      :       Tuple,__A      :       Union[PIL.Image.Image, List[PIL.Image.Image]],__A      :       int = 1,__A      :       int = 2_5,__A      :       Optional[Union[torch.Generator, List[torch.Generator]]] = None,__A      :       Optional[torch.FloatTensor] = None,__A      :       float = 4.0,__A      :       int = 6_4,__A      :       Optional[str] = "pil",__A      :       bool = True,):

          if isinstance(__A,PIL.Image.Image     ):
                _lowerCamelCase				:   Optional[int]								=   1
          elif isinstance(__A,torch.Tensor     ):
                _lowerCamelCase				:   Optional[Any]								=   image.shape[0]
          elif isinstance(__A,__A     ) and isinstance(image[0],(torch.Tensor, PIL.Image.Image)     ):
                _lowerCamelCase				:   str								=   len(__A     )
          else:
                raise ValueError(
                    f'`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__A     )}'     )

          _lowerCamelCase				:   Optional[int]								=   self._execution_device

          _lowerCamelCase				:   int								=   batch_size * num_images_per_prompt

          _lowerCamelCase				:   Union[str, Any]								=   guidance_scale > 1.0
          _lowerCamelCase				:   Tuple								=   self._encode_image(__A,__A,__A,__A     )

          # prior

          self.scheduler.set_timesteps(__A,device=__A     )
          _lowerCamelCase				:   List[Any]								=   self.scheduler.timesteps

          _lowerCamelCase				:   Dict								=   self.prior.config.num_embeddings
          _lowerCamelCase				:   Tuple								=   self.prior.config.embedding_dim

          _lowerCamelCase				:   List[str]								=   self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim),image_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
          _lowerCamelCase				:   Tuple								=   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
                _lowerCamelCase				:   Optional[int]								=   torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
                _lowerCamelCase				:   Tuple								=   self.scheduler.scale_model_input(__A,__A     )

                _lowerCamelCase				:   List[str]								=   self.prior(
                    __A,timestep=__A,proj_embedding=__A,).predicted_image_embedding

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

                if do_classifier_free_guidance is not None:
                      _lowerCamelCase						,		_lowerCamelCase				:   int								=   noise_pred.chunk(2     )
                      _lowerCamelCase				:   Optional[int]								=   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

                _lowerCamelCase				:   Any								=   self.scheduler.step(
                    __A,timestep=__A,sample=__A,).prev_sample

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

          _lowerCamelCase				:   Any								=   []
          for i, latent in enumerate(__A     ):
                print()
                _lowerCamelCase				:   int								=   self.renderer.decode(
                    latent[None, :],__A,size=__A,ray_batch_size=4_0_9_6,n_coarse_samples=6_4,n_fine_samples=1_2_8,)

                images.append(__A     )

          _lowerCamelCase				:   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}'     )

          _lowerCamelCase				:   Union[str, Any]								=   images.cpu().numpy()

          if output_type == "pil":
                _lowerCamelCase				:   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     )