






import inspect
import unittest

import numpy as np

from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor


if is_flax_available():
 import jax

 from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel

if is_vision_available():
 from PIL import Image

 from transformers import BeitImageProcessor



class 							_UpperCamelCase			(unittest.TestCase			):


      def __init__(	self					,						__UpperCamelCase					,						__UpperCamelCase=1_0_0					,						__UpperCamelCase=1_3					,						__UpperCamelCase=3_0					,						__UpperCamelCase=2					,						__UpperCamelCase=3					,						__UpperCamelCase=True					,						__UpperCamelCase=True					,						__UpperCamelCase=3_2					,						__UpperCamelCase=5					,						__UpperCamelCase=4					,						__UpperCamelCase=3_7					,						__UpperCamelCase="gelu"					,						__UpperCamelCase=0.1					,						__UpperCamelCase=0.1					,						__UpperCamelCase=1_0					,						__UpperCamelCase=0.0_2					,						__UpperCamelCase=3					,						)->	str:
           __lowerCAmelCase								=					parent
           __lowerCAmelCase								=					vocab_size
           __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

           # in BeiT, 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	)->	Tuple:
           __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								=					BeitConfig(
               vocab_size=self.vocab_size					,						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					,						is_decoder=__UpperCamelCase					,						initializer_range=self.initializer_range					,						)

           return config, pixel_values, labels


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	int:
           __lowerCAmelCase								=					FlaxBeitModel(config=__UpperCamelCase	)
           __lowerCAmelCase								=					model(__UpperCamelCase	)
           self.parent.assertEqual(result.last_hidden_state.shape					,						(self.batch_size, self.seq_length, self.hidden_size)	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	Optional[Any]:
           __lowerCAmelCase								=					FlaxBeitForMaskedImageModeling(config=__UpperCamelCase	)
           __lowerCAmelCase								=					model(__UpperCamelCase	)
           self.parent.assertEqual(result.logits.shape					,						(self.batch_size, self.seq_length - 1, self.vocab_size)	)


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	Optional[Any]:
           __lowerCAmelCase								=					self.type_sequence_label_size
           __lowerCAmelCase								=					FlaxBeitForImageClassification(config=__UpperCamelCase	)
           __lowerCAmelCase								=					model(__UpperCamelCase	)
           self.parent.assertEqual(result.logits.shape					,						(self.batch_size, self.type_sequence_label_size)	)

           # test greyscale images
           __lowerCAmelCase								=					1
           __lowerCAmelCase								=					FlaxBeitForImageClassification(__UpperCamelCase	)

           __lowerCAmelCase								=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
           __lowerCAmelCase								=					model(__UpperCamelCase	)


      def  __UpperCAmelCase		(	self	)->	int:
           __lowerCAmelCase								=					self.prepare_config_and_inputs()
           (
               (
               __lowerCAmelCase
           )			, (
               __lowerCAmelCase
           )			, (
               __lowerCAmelCase
           )			, 
           )								=					config_and_inputs
           __lowerCAmelCase								=					{"pixel_values": pixel_values}
           return config, inputs_dict



@require_flax
class 							_UpperCamelCase			(a_							,		unittest.TestCase			):
      snake_case_  =							(
          (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
      )


      def  __UpperCAmelCase		(	self	)->	None:
           __lowerCAmelCase								=					FlaxBeitModelTester(self	)
           __lowerCAmelCase								=					ConfigTester(self					,						config_class=__UpperCamelCase					,						has_text_modality=__UpperCamelCase					,						hidden_size=3_7	)


      def  __UpperCAmelCase		(	self	)->	List[Any]:
           self.config_tester.run_common_tests()


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

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

                __lowerCAmelCase								=					["pixel_values"]
                self.assertListEqual(arg_names[:1]					,						__UpperCamelCase	)


      def  __UpperCAmelCase		(	self	)->	str:
           __lowerCAmelCase			, __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                with self.subTest(model_class.__name__	):
                     __lowerCAmelCase								=					self._prepare_for_class(__UpperCamelCase					,						__UpperCamelCase	)
                     __lowerCAmelCase								=					model_class(__UpperCamelCase	)

                     @jax.jit
                     def model_jitted(__UpperCamelCase					,						**__UpperCamelCase	):
                          return model(pixel_values=__UpperCamelCase					,						**__UpperCamelCase	)

                     with self.subTest("JIT Enabled"	):
                          __lowerCAmelCase								=					model_jitted(**__UpperCamelCase	).to_tuple()

                     with self.subTest("JIT Disabled"	):
                          with jax.disable_jit():
                               __lowerCAmelCase								=					model_jitted(**__UpperCamelCase	).to_tuple()

                     self.assertEqual(len(__UpperCamelCase	)					,						len(__UpperCamelCase	)	)
                     for jitted_output, output in zip(__UpperCamelCase					,						__UpperCamelCase	):
                          self.assertEqual(jitted_output.shape					,						output.shape	)


      def  __UpperCAmelCase		(	self	)->	Optional[Any]:
           __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__UpperCamelCase	)


      def  __UpperCAmelCase		(	self	)->	int:
           __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_lm(*__UpperCamelCase	)


      def  __UpperCAmelCase		(	self	)->	Optional[Any]:
           __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase	)


      @slow
      def  __UpperCAmelCase		(	self	)->	int:
           for model_class_name in self.all_model_classes:
                __lowerCAmelCase								=					model_class_name.from_pretrained("microsoft/beit-base-patch16-224"	)
                __lowerCAmelCase								=					model(np.ones((1, 3, 2_2_4, 2_2_4)	)	)
                self.assertIsNotNone(__UpperCamelCase	)





def       __lowerCAmelCase      (						):
     __lowerCAmelCase								=					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
     return image



@require_vision
@require_flax
class 							_UpperCamelCase			(unittest.TestCase			):


      @cached_property
      def  __UpperCAmelCase		(	self	)->	Optional[Any]:
           return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224"	) if is_vision_available() else None


      @slow
      def  __UpperCAmelCase		(	self	)->	int:
           __lowerCAmelCase								=					FlaxBeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k"	)

           __lowerCAmelCase								=					self.default_image_processor
           __lowerCAmelCase								=					prepare_img()
           __lowerCAmelCase								=					image_processor(images=__UpperCamelCase					,						return_tensors="np"	).pixel_values

           # prepare bool_masked_pos
           __lowerCAmelCase								=					np.ones((1, 1_9_6)					,						dtype=__UpperCamelCase	)

           # forward pass
           __lowerCAmelCase								=					model(pixel_values=__UpperCamelCase					,						bool_masked_pos=__UpperCamelCase	)
           __lowerCAmelCase								=					outputs.logits

           # verify the logits
           __lowerCAmelCase								=					(1, 1_9_6, 8_1_9_2)
           self.assertEqual(logits.shape					,						__UpperCamelCase	)

           __lowerCAmelCase								=					np.array(
               [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]	)

           self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3]					,						__UpperCamelCase					,						atol=1e-2	)	)


      @slow
      def  __UpperCAmelCase		(	self	)->	List[str]:
           __lowerCAmelCase								=					FlaxBeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224"	)

           __lowerCAmelCase								=					self.default_image_processor
           __lowerCAmelCase								=					prepare_img()
           __lowerCAmelCase								=					image_processor(images=__UpperCamelCase					,						return_tensors="np"	)

           # forward pass
           __lowerCAmelCase								=					model(**__UpperCamelCase	)
           __lowerCAmelCase								=					outputs.logits

           # verify the logits
           __lowerCAmelCase								=					(1, 1_0_0_0)
           self.assertEqual(logits.shape					,						__UpperCamelCase	)

           __lowerCAmelCase								=					np.array([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]	)

           self.assertTrue(np.allclose(logits[0, :3]					,						__UpperCamelCase					,						atol=1e-4	)	)

           __lowerCAmelCase								=					2_8_1
           self.assertEqual(logits.argmax(-1	).item()					,						__UpperCamelCase	)


      @slow
      def  __UpperCAmelCase		(	self	)->	Any:
           __lowerCAmelCase								=					FlaxBeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k"	)

           __lowerCAmelCase								=					self.default_image_processor
           __lowerCAmelCase								=					prepare_img()
           __lowerCAmelCase								=					image_processor(images=__UpperCamelCase					,						return_tensors="np"	)

           # forward pass
           __lowerCAmelCase								=					model(**__UpperCamelCase	)
           __lowerCAmelCase								=					outputs.logits

           # verify the logits
           __lowerCAmelCase								=					(1, 2_1_8_4_1)
           self.assertEqual(logits.shape					,						__UpperCamelCase	)

           __lowerCAmelCase								=					np.array([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]	)

           self.assertTrue(np.allclose(logits[0, :3]					,						__UpperCamelCase					,						atol=1e-4	)	)

           __lowerCAmelCase								=					2_3_9_6
           self.assertEqual(logits.argmax(-1	).item()					,						__UpperCamelCase	)














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


lowerCamelCase			:					Tuple         =	logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase			:					str         =	'''
    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 							_UpperCamelCase			(a_			):
      snake_case_  =							42



class 							_UpperCamelCase			(a_			):


      def __init__(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						)->	Dict:
           super().__init__()

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


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)->	Union[str, Any]:
           if latents is None:
                __lowerCAmelCase								=					randn_tensor(__UpperCamelCase					,						generator=__UpperCamelCase					,						device=__UpperCamelCase					,						dtype=__UpperCamelCase	)
           else:
                if latents.shape != shape:
                     raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""	)
                __lowerCAmelCase								=					latents.to(__UpperCamelCase	)

           __lowerCAmelCase								=					latents * scheduler.init_noise_sigma
           return latents


      def  __UpperCAmelCase		(	self					,						__UpperCamelCase=0	)->	str:
           if is_accelerate_available():
                from accelerate import cpu_offload
           else:
                raise ImportError("Please install accelerate via `pip install accelerate`"	)

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

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


      @property
      def  __UpperCAmelCase		(	self	)->	List[str]:
           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(__UpperCamelCase					,						"_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  __UpperCAmelCase		(	self					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						)->	Union[str, Any]:
           if isinstance(__UpperCamelCase					,						__UpperCamelCase	) and isinstance(image[0]					,						torch.Tensor	):
                __lowerCAmelCase								=					torch.cat(__UpperCamelCase					,						axis=0	) if image[0].ndim == 4 else torch.stack(__UpperCamelCase					,						axis=0	)

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

           __lowerCAmelCase								=					image.to(dtype=self.image_encoder.dtype					,						device=__UpperCamelCase	)

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

           __lowerCAmelCase								=					image_embeds.repeat_interleave(__UpperCamelCase					,						dim=0	)

           if do_classifier_free_guidance:
                __lowerCAmelCase								=					torch.zeros_like(__UpperCamelCase	)

                # 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								=					torch.cat([negative_image_embeds, image_embeds]	)

           return image_embeds


      @torch.no_grad()
      @replace_example_docstring(__UpperCamelCase	)
      def __call__(	self					,						__UpperCamelCase					,						__UpperCamelCase = 1					,						__UpperCamelCase = 2_5					,						__UpperCamelCase = None					,						__UpperCamelCase = None					,						__UpperCamelCase = 4.0					,						__UpperCamelCase = 6_4					,						__UpperCamelCase = "pil"					,						__UpperCamelCase = True					,						)->	Dict:

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

           __lowerCAmelCase								=					self._execution_device

           __lowerCAmelCase								=					batch_size * num_images_per_prompt

           __lowerCAmelCase								=					guidance_scale > 1.0
           __lowerCAmelCase								=					self._encode_image(__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase	)

           # prior

           self.scheduler.set_timesteps(__UpperCamelCase					,						device=__UpperCamelCase	)
           __lowerCAmelCase								=					self.scheduler.timesteps

           __lowerCAmelCase								=					self.prior.config.num_embeddings
           __lowerCAmelCase								=					self.prior.config.embedding_dim

           __lowerCAmelCase								=					self.prepare_latents(
               (batch_size, num_embeddings * embedding_dim)					,						image_embeds.dtype					,						__UpperCamelCase					,						__UpperCamelCase					,						__UpperCamelCase					,						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								=					latents.reshape(latents.shape[0]					,						__UpperCamelCase					,						__UpperCamelCase	)

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

                __lowerCAmelCase								=					self.prior(
                    __UpperCamelCase					,						timestep=__UpperCamelCase					,						proj_embedding=__UpperCamelCase					,						).predicted_image_embedding

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

                __lowerCAmelCase								=					self.scheduler.step(
                    __UpperCamelCase					,						timestep=__UpperCamelCase					,						sample=__UpperCamelCase					,						).prev_sample

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

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

                images.append(__UpperCamelCase	)

           __lowerCAmelCase								=					torch.stack(__UpperCamelCase	)

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

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






