


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


A_     :       Dict   							=logging.get_logger(__name__)  # pylint: disable=invalid-name

A_     :       int   							='''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

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

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

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

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

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''





@dataclass
class 							lowercase_					(			__snake_case):






							"""simple docstring"""







							snake_case_										=		42





class 							lowercase_					(			__snake_case):






							"""simple docstring"""







							def __init__( self      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     ):







													"""simple docstring"""


													super().__init__()

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


							def     lowercase__  ( self      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase		):







													"""simple docstring"""


													if latents is None:
																			a_		      =		randn_tensor(__SCREAMING_SNAKE_CASE      ,     generator=__SCREAMING_SNAKE_CASE      ,     device=__SCREAMING_SNAKE_CASE      ,     dtype=__SCREAMING_SNAKE_CASE		)
													else:
																			if latents.shape != shape:
																									raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"		)
																			a_		      =		latents.to(__SCREAMING_SNAKE_CASE		)

													a_		      =		latents * scheduler.init_noise_sigma
													return latents


							def     lowercase__  ( self      ,     _UpperCAmelCase=0		):







													"""simple docstring"""


													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.image_encoder, self.prior]
													for cpu_offloaded_model in models:
																			if cpu_offloaded_model is not None:
																									cpu_offload(__SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		)


							@property
							def     lowercase__  ( self		):







													"""simple docstring"""


													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(__SCREAMING_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     lowercase__  ( self      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     _UpperCAmelCase      ,     ):







													"""simple docstring"""


													if isinstance(__SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		) and isinstance(image[0]      ,     torch.Tensor		):
																			a_		      =		torch.cat(__SCREAMING_SNAKE_CASE      ,     axis=0		) if image[0].ndim == 4 else torch.stack(__SCREAMING_SNAKE_CASE      ,     axis=0		)

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

													a_		      =		image.to(dtype=self.image_encoder.dtype      ,     device=__SCREAMING_SNAKE_CASE		)

													a_		      =		self.image_encoder(__SCREAMING_SNAKE_CASE		)["""last_hidden_state"""]
													a_		      =		image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

													a_		      =		image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE      ,     dim=0		)

													if do_classifier_free_guidance:
																			a_		      =		torch.zeros_like(__SCREAMING_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_image_embeds, image_embeds]		)

													return image_embeds






							@torch.no_grad()
							@replace_example_docstring(__SCREAMING_SNAKE_CASE		)
							def __call__( self      ,     _UpperCAmelCase      ,     _UpperCAmelCase = 1      ,     _UpperCAmelCase = 25      ,     _UpperCAmelCase = None      ,     _UpperCAmelCase = None      ,     _UpperCAmelCase = 4.0      ,     _UpperCAmelCase = 64      ,     _UpperCAmelCase = "pil"      ,     _UpperCAmelCase = True      ,     ):







													"""simple docstring"""


													if isinstance(__SCREAMING_SNAKE_CASE      ,     PIL.Image.Image		):
																			a_		      =		1
													elif isinstance(__SCREAMING_SNAKE_CASE      ,     torch.Tensor		):
																			a_		      =		image.shape[0]
													elif isinstance(__SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		) and isinstance(image[0]      ,     (torch.Tensor, PIL.Image.Image)		):
																			a_		      =		len(__SCREAMING_SNAKE_CASE		)
													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(__SCREAMING_SNAKE_CASE		)}"		)

													a_		      =		self._execution_device

													a_		      =		batch_size * num_images_per_prompt

													a_		      =		guidance_scale > 1.0
													a_		      =		self._encode_image(__SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		)

													# prior

													self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE      ,     device=__SCREAMING_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)      ,     image_embeds.dtype      ,     __SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE      ,     __SCREAMING_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]      ,     __SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		)

													for i, t in enumerate(self.progress_bar(__SCREAMING_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(__SCREAMING_SNAKE_CASE      ,     __SCREAMING_SNAKE_CASE		)

																			a_		      =		self.prior(
																			    __SCREAMING_SNAKE_CASE      ,     timestep=__SCREAMING_SNAKE_CASE      ,     proj_embedding=__SCREAMING_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(
																			    __SCREAMING_SNAKE_CASE      ,     timestep=__SCREAMING_SNAKE_CASE      ,     sample=__SCREAMING_SNAKE_CASE      ,     ).prev_sample

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

													a_		      =		[]
													for i, latent in enumerate(__SCREAMING_SNAKE_CASE		):
																			print()
																			a_		      =		self.renderer.decode(
																			    latent[None, :]      ,     __SCREAMING_SNAKE_CASE      ,     size=__SCREAMING_SNAKE_CASE      ,     ray_batch_size=4_096      ,     n_coarse_samples=64      ,     n_fine_samples=128      ,     )

																			images.append(__SCREAMING_SNAKE_CASE		)

													a_		      =		torch.stack(__SCREAMING_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(__SCREAMING_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=__SCREAMING_SNAKE_CASE		)







"""simple docstring"""





import inspect
import unittest

from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
  import torch
  from torch import nn

  from transformers import ViTMSNForImageClassification, ViTMSNModel
  from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import ViTImageProcessor






class 	a		:






    def __init__(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				str=13			,		__SCREAMING_SNAKE_CASE	:				int=30			,		__SCREAMING_SNAKE_CASE	:				List[Any]=2			,		__SCREAMING_SNAKE_CASE	:				Dict=3			,		__SCREAMING_SNAKE_CASE	:				List[str]=True			,		__SCREAMING_SNAKE_CASE	:				str=True			,		__SCREAMING_SNAKE_CASE	:				Any=32			,		__SCREAMING_SNAKE_CASE	:				List[str]=5			,		__SCREAMING_SNAKE_CASE	:				List[str]=4			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=37			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]="gelu"			,		__SCREAMING_SNAKE_CASE	:				List[Any]=0.1			,		__SCREAMING_SNAKE_CASE	:				Tuple=0.1			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]=10			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]=0.02			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=None			,		)	->						List[str]:
      lowerCamelCase_       	=		parent
      lowerCamelCase_       	=		batch_size
      lowerCamelCase_       	=		image_size
      lowerCamelCase_       	=		patch_size
      lowerCamelCase_       	=		num_channels
      lowerCamelCase_       	=		is_training
      lowerCamelCase_       	=		use_labels
      lowerCamelCase_       	=		hidden_size
      lowerCamelCase_       	=		num_hidden_layers
      lowerCamelCase_       	=		num_attention_heads
      lowerCamelCase_       	=		intermediate_size
      lowerCamelCase_       	=		hidden_act
      lowerCamelCase_       	=		hidden_dropout_prob
      lowerCamelCase_       	=		attention_probs_dropout_prob
      lowerCamelCase_       	=		type_sequence_label_size
      lowerCamelCase_       	=		initializer_range
      lowerCamelCase_       	=		scope

      # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
      lowerCamelCase_       	=		(image_size // patch_size) ** 2
      lowerCamelCase_       	=		num_patches + 1






    def   UpperCamelCase			(			self	:				Dict   )	->						Union[str, Any]:
      lowerCamelCase_       	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

      lowerCamelCase_       	=		None
      if self.use_labels:
        lowerCamelCase_       	=		ids_tensor([self.batch_size]			,		self.type_sequence_label_size   )

      lowerCamelCase_       	=		self.get_config()

      return config, pixel_values, labels






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Union[str, Any]:
      return ViTMSNConfig(
          image_size=self.image_size			,		patch_size=self.patch_size			,		num_channels=self.num_channels			,		hidden_size=self.hidden_size			,		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			,		initializer_range=self.initializer_range			,		)






    def   UpperCamelCase			(			self	:				int			,		__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				Any			,		__SCREAMING_SNAKE_CASE	:				int   )	->						Any:
      lowerCamelCase_       	=		ViTMSNModel(config=__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE   )
      self.parent.assertEqual(result.last_hidden_state.shape			,		(self.batch_size, self.seq_length, self.hidden_size)   )






    def   UpperCamelCase			(			self	:				int			,		__SCREAMING_SNAKE_CASE	:				Dict			,		__SCREAMING_SNAKE_CASE	:				str			,		__SCREAMING_SNAKE_CASE	:				str   )	->						List[str]:
      lowerCamelCase_       	=		self.type_sequence_label_size
      lowerCamelCase_       	=		ViTMSNForImageClassification(__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE			,		labels=__SCREAMING_SNAKE_CASE   )
      print('Pixel and labels shape: {pixel_values.shape}, {labels.shape}'   )
      print('Labels: {labels}'   )
      self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.type_sequence_label_size)   )

      # test greyscale images
      lowerCamelCase_       	=		1
      lowerCamelCase_       	=		ViTMSNForImageClassification(__SCREAMING_SNAKE_CASE   )
      model.to(__SCREAMING_SNAKE_CASE   )
      model.eval()

      lowerCamelCase_       	=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
      lowerCamelCase_       	=		model(__SCREAMING_SNAKE_CASE   )
      self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.type_sequence_label_size)   )






    def   UpperCamelCase			(			self	:				List[str]   )	->						Tuple:
      lowerCamelCase_       	=		self.prepare_config_and_inputs()
      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_       	=		config_and_inputs
      lowerCamelCase_       	=		{'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 	a		(   __snake_case    , __snake_case    , unittest.TestCase						):
    SCREAMING_SNAKE_CASE		:	str		=					(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE		:	Dict		=					(
        {"""feature-extraction""": ViTMSNModel, """image-classification""": ViTMSNForImageClassification}
        if is_torch_available()
        else {}
    )

    SCREAMING_SNAKE_CASE		:	Dict		=					False
    SCREAMING_SNAKE_CASE		:	Union[str, Any]		=					False
    SCREAMING_SNAKE_CASE		:	Optional[Any]		=					False
    SCREAMING_SNAKE_CASE		:	str		=					False






    def   UpperCamelCase			(			self	:				List[Any]   )	->						List[str]:
      lowerCamelCase_       	=		ViTMSNModelTester(self   )
      lowerCamelCase_       	=		ConfigTester(self			,		config_class=__SCREAMING_SNAKE_CASE			,		has_text_modality=__SCREAMING_SNAKE_CASE			,		hidden_size=37   )






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Optional[Any]:
      self.config_tester.run_common_tests()






    @unittest.skip(reason='ViTMSN does not use inputs_embeds'   )
    def   UpperCamelCase			(			self	:				Tuple   )	->						Union[str, Any]:
      pass






    def   UpperCamelCase			(			self	:				List[Any]   )	->						List[Any]:
      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        self.assertIsInstance(model.get_input_embeddings()			,		(nn.Module)   )
        lowerCamelCase_       	=		model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE			,		nn.Linear   )   )






    def   UpperCamelCase			(			self	:				Optional[int]   )	->						Any:
      lowerCamelCase_	,      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCamelCase_       	=		model_class(__SCREAMING_SNAKE_CASE   )
        lowerCamelCase_       	=		inspect.signature(model.forward   )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowerCamelCase_       	=		[*signature.parameters.keys()]

        lowerCamelCase_       	=		['pixel_values']
        self.assertListEqual(arg_names[:1]			,		__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Optional[Any]   )	->						List[Any]:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )






    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Optional[int]:
      lowerCamelCase_       	=		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE   )






    @slow
    def   UpperCamelCase			(			self	:				int   )	->						List[Any]:
      for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase_       	=		ViTMSNModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
        self.assertIsNotNone(__SCREAMING_SNAKE_CASE   )







def 	lowerCamelCase__			(				) ->							List[Any]:
  lowerCamelCase_       	=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
  return image






@require_torch
@require_vision
class 	a		(   unittest.TestCase						):






    @cached_property
    def   UpperCamelCase			(			self	:				Optional[int]   )	->						Any:
      return ViTImageProcessor.from_pretrained('facebook/vit-msn-small'   ) if is_vision_available() else None






    @slow
    def   UpperCamelCase			(			self	:				Dict   )	->						Any:
      torch.manual_seed(2   )
      lowerCamelCase_       	=		ViTMSNForImageClassification.from_pretrained('facebook/vit-msn-small'   ).to(__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		self.default_image_processor
      lowerCamelCase_       	=		prepare_img()
      lowerCamelCase_       	=		image_processor(images=__SCREAMING_SNAKE_CASE			,		return_tensors='pt'   ).to(__SCREAMING_SNAKE_CASE   )

      # forward pass
      with torch.no_grad():
        lowerCamelCase_       	=		model(**__SCREAMING_SNAKE_CASE   )

      # verify the logits
      lowerCamelCase_       	=		torch.Size((1, 1000)   )
      self.assertEqual(outputs.logits.shape			,		__SCREAMING_SNAKE_CASE   )

      lowerCamelCase_       	=		torch.tensor([-0.0_803, -0.4_454, -0.2_375]   ).to(__SCREAMING_SNAKE_CASE   )

      self.assertTrue(torch.allclose(outputs.logits[0, :3]			,		__SCREAMING_SNAKE_CASE			,		atol=1e-4   )   )




