





from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


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

UpperCAmelCase     :     List[str]							=	"""
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)[\"depth\"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline(\"depth-estimation\")

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to(\"cuda\")

        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to(\"cuda\")


        >>> img = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/cat.png\"
        ... ).resize((768, 768))

        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")

        >>> prompt = \"A robot, 4k photo\"
        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"

        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)

        >>> image_emb, zero_image_emb = pipe_prior(
        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator
        ... ).to_tuple()

        >>> images = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save(\"robot_cat.png\")
        ```
"""
def 					_A	(		SCREAMING_SNAKE_CASE					:       Any	,	SCREAMING_SNAKE_CASE					:       Any	,	SCREAMING_SNAKE_CASE					:       int=8						):





  """simple docstring"""



  a__     : int  =height // scale_factor**2
  if height % scale_factor**2 != 0:
    new_height += 1
  a__     : Optional[Any]  =width // scale_factor**2
  if width % scale_factor**2 != 0:
    new_width += 1
  return new_height * scale_factor, new_width * scale_factor







class     __lowerCAmelCase	(   UpperCamelCase__):







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				)       ->						List[Any]:



        '''simple docstring'''




        super().__init__()

        self.register_modules(
            unet=lowerCAmelCase__		,				scheduler=lowerCAmelCase__		,				movq=lowerCAmelCase__		,				)
        a__     : Dict  =2 ** (len(self.movq.config.block_out_channels							) - 1)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Dict:



        '''simple docstring'''




        if latents is None:
          a__     : List[Any]  =randn_tensor(lowerCAmelCase__		,				generator=lowerCAmelCase__		,				device=lowerCAmelCase__		,				dtype=lowerCAmelCase__							)
        else:
          if latents.shape != shape:
            raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''							)
          a__     : Dict  =latents.to(lowerCAmelCase__							)

        a__     : str  =latents * scheduler.init_noise_sigma
        return latents







      def        _lowercase  (   self		,				lowerCAmelCase__=0							)       ->						Dict:



        '''simple docstring'''




        if is_accelerate_available():
          from accelerate import cpu_offload
        else:
          raise ImportError("Please install accelerate via `pip install accelerate`"							)

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

        a__     : Optional[Any]  =[
            self.unet,
            self.movq,
        ]
        for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
            cpu_offload(lowerCAmelCase__		,				lowerCAmelCase__							)







      def        _lowercase  (   self		,				lowerCAmelCase__=0							)       ->						int:



        '''simple docstring'''




        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__     : Optional[int]  =torch.device(F'''cuda:{gpu_id}'''							)

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

        a__     : List[str]  =None
        for cpu_offloaded_model in [self.unet, self.movq]:
          a__ ,							a__     : Optional[int]  =cpu_offload_with_hook(lowerCAmelCase__		,				lowerCAmelCase__		,				prev_module_hook=lowerCAmelCase__							)

        # We'll offload the last model manually.
        a__     : Any  =hook







      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def        _lowercase  (   self							)       ->						Dict:



        '''simple docstring'''




        if not hasattr(self.unet		,				"_hf_hook"							):
          return self.device
        for module in self.unet.modules():
          if (
              hasattr(lowerCAmelCase__		,				"_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







      @torch.no_grad()
      @replace_example_docstring(lowerCAmelCase__							)
      def __call__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__ = 5_1_2		,				lowerCAmelCase__ = 5_1_2		,				lowerCAmelCase__ = 1_0_0		,				lowerCAmelCase__ = 4.0		,				lowerCAmelCase__ = 1		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = None		,				lowerCAmelCase__ = "pil"		,				lowerCAmelCase__ = True		,				)       ->						List[Any]:



        '''simple docstring'''




        a__     : List[str]  =self._execution_device

        a__     : Union[str, Any]  =guidance_scale > 1.0

        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : List[Any]  =torch.cat(lowerCAmelCase__		,				dim=0							)
        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : str  =torch.cat(lowerCAmelCase__		,				dim=0							)
        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : Tuple  =torch.cat(lowerCAmelCase__		,				dim=0							)

        a__     : List[Any]  =image_embeds.shape[0] * num_images_per_prompt

        if do_classifier_free_guidance:
          a__     : List[str]  =image_embeds.repeat_interleave(lowerCAmelCase__		,				dim=0							)
          a__     : Optional[Any]  =negative_image_embeds.repeat_interleave(lowerCAmelCase__		,				dim=0							)
          a__     : str  =hint.repeat_interleave(lowerCAmelCase__		,				dim=0							)

        a__     : int  =torch.cat([negative_image_embeds, image_embeds]		,				dim=0							).to(dtype=self.unet.dtype		,				device=lowerCAmelCase__							)
        a__     : Dict  =torch.cat([hint, hint]		,				dim=0							).to(dtype=self.unet.dtype		,				device=lowerCAmelCase__							)
        self.scheduler.set_timesteps(lowerCAmelCase__		,				device=lowerCAmelCase__							)
        a__     : str  =self.scheduler.timesteps

        a__     : str  =self.movq.config.latent_channels

        a__ ,							a__     : Union[str, Any]  =downscale_height_and_width(lowerCAmelCase__		,				lowerCAmelCase__		,				self.movq_scale_factor							)

        # create initial latent
        a__     : Optional[Any]  =self.prepare_latents(
            (batch_size, num_channels_latents, height, width)		,				image_embeds.dtype		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				self.scheduler		,				)

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

          a__     : str  ={"image_embeds": image_embeds, "hint": hint}
          a__     : Dict  =self.unet(
              sample=lowerCAmelCase__		,				timestep=lowerCAmelCase__		,				encoder_hidden_states=lowerCAmelCase__		,				added_cond_kwargs=lowerCAmelCase__		,				return_dict=lowerCAmelCase__		,				)[0]

          if do_classifier_free_guidance:
            a__ ,							a__     : str  =noise_pred.split(latents.shape[1]		,				dim=1							)
            a__ ,							a__     : Optional[int]  =noise_pred.chunk(2							)
            a__ ,							a__     : Any  =variance_pred.chunk(2							)
            a__     : List[Any]  =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
            a__     : str  =torch.cat([noise_pred, variance_pred_text]		,				dim=1							)

          if not (
              hasattr(self.scheduler.config		,				"variance_type"							)
              and self.scheduler.config.variance_type in ["learned", "learned_range"]
          ):
            a__ ,							a__     : List[str]  =noise_pred.split(latents.shape[1]		,				dim=1							)

          # compute the previous noisy sample x_t -> x_t-1
          a__     : List[Any]  =self.scheduler.step(
              lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				generator=lowerCAmelCase__		,				)[0]
        # post-processing
        a__     : Dict  =self.movq.decode(lowerCAmelCase__		,				force_not_quantize=lowerCAmelCase__							)["sample"]

        if output_type not in ["pt", "np", "pil"]:
          raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''							)

        if output_type in ["np", "pil"]:
          a__     : int  =image * 0.5 + 0.5
          a__     : Optional[int]  =image.clamp(0		,				1							)
          a__     : int  =image.cpu().permute(0		,				2		,				3		,				1							).float().numpy()

        if output_type == "pil":
          a__     : int  =self.numpy_to_pil(lowerCAmelCase__							)

        if not return_dict:
          return (image,)

        return ImagePipelineOutput(images=lowerCAmelCase__							)













import inspect
import unittest

from transformers import MobileNetVaConfig
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 transformers import MobileNetVaForImageClassification, MobileNetVaModel
     from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileNetVaImageProcessor







class     __lowerCAmelCase	(   UpperCamelCase__):







      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        a__     : Optional[int]  =self.config_class(**self.inputs_dict							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,				"tf_padding"							)							)
        self.parent.assertTrue(hasattr(lowerCAmelCase__		,				"depth_multiplier"							)							)







class     __lowerCAmelCase	:







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__=1_3		,				lowerCAmelCase__=3		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__=0.25		,				lowerCAmelCase__=8		,				lowerCAmelCase__=True		,				lowerCAmelCase__=1_0_2_4		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__="relu6"		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.02		,				lowerCAmelCase__=True		,				lowerCAmelCase__=True		,				lowerCAmelCase__=1_0		,				lowerCAmelCase__=None		,				)       ->						Dict:



        '''simple docstring'''




        a__     : int  =parent
        a__     : Optional[Any]  =batch_size
        a__     : Tuple  =num_channels
        a__     : Dict  =image_size
        a__     : Union[str, Any]  =depth_multiplier
        a__     : List[str]  =min_depth
        a__     : Dict  =tf_padding
        a__     : Any  =int(last_hidden_size * depth_multiplier							)
        a__     : Tuple  =output_stride
        a__     : Optional[Any]  =hidden_act
        a__     : str  =classifier_dropout_prob
        a__     : int  =use_labels
        a__     : List[Any]  =is_training
        a__     : List[str]  =num_labels
        a__     : Dict  =initializer_range
        a__     : Tuple  =scope







      def        _lowercase  (   self							)       ->						List[str]:



        '''simple docstring'''




        a__     : Union[str, Any]  =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

        a__     : Any  =None
        a__     : List[Any]  =None
        if self.use_labels:
          a__     : Dict  =ids_tensor([self.batch_size]		,				self.num_labels							)
          a__     : Tuple  =ids_tensor([self.batch_size, self.image_size, self.image_size]		,				self.num_labels							)

        a__     : Optional[Any]  =self.get_config()

        return config, pixel_values, labels, pixel_labels







      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        return MobileNetVaConfig(
            num_channels=self.num_channels		,				image_size=self.image_size		,				depth_multiplier=self.depth_multiplier		,				min_depth=self.min_depth		,				tf_padding=self.tf_padding		,				hidden_act=self.hidden_act		,				classifier_dropout_prob=self.classifier_dropout_prob		,				initializer_range=self.initializer_range		,				)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Union[str, Any]:



        '''simple docstring'''




        a__     : Union[str, Any]  =MobileNetVaModel(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : str  =model(lowerCAmelCase__							)
        self.parent.assertEqual(
            result.last_hidden_state.shape		,				(
                self.batch_size,
                self.last_hidden_size,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )		,				)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						str:



        '''simple docstring'''




        a__     : Any  =self.num_labels
        a__     : Dict  =MobileNetVaForImageClassification(lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : Optional[int]  =model(lowerCAmelCase__		,				labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)







      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        a__     : str  =self.prepare_config_and_inputs()
        a__ ,							a__ ,							a__ ,							a__     : List[str]  =config_and_inputs
        a__     : Tuple  ={"pixel_values": pixel_values}
        return config, inputs_dict







@require_torch
class     __lowerCAmelCase	(   UpperCamelCase__						,    UpperCamelCase__						,    unittest.TestCase):
      _lowercase    : List[str]            =      (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
      _lowercase    : Optional[int]            =      (
          {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
          if is_torch_available()
          else {}
      )

      _lowercase    : Union[str, Any]            =      False
      _lowercase    : Optional[int]            =      False
      _lowercase    : List[str]            =      False
      _lowercase    : str            =      False







      def        _lowercase  (   self							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : Optional[Any]  =MobileNetVaModelTester(self							)
        a__     : Optional[Any]  =MobileNetVaConfigTester(self		,				config_class=lowerCAmelCase__		,				has_text_modality=lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Dict:



        '''simple docstring'''




        self.config_tester.run_common_tests()







      @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"							)
      def        _lowercase  (   self							)       ->						Union[str, Any]:



        '''simple docstring'''




        pass







      @unittest.skip(reason="MobileNetV1 does not support input and output embeddings"							)
      def        _lowercase  (   self							)       ->						List[str]:



        '''simple docstring'''




        pass







      @unittest.skip(reason="MobileNetV1 does not output attentions"							)
      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        pass







      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        a__ ,							a__     : Optional[int]  =self.model_tester.prepare_config_and_inputs_for_common()

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

          a__     : Union[str, Any]  =["pixel_values"]
          self.assertListEqual(arg_names[:1]		,				lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Union[str, Any]:



        '''simple docstring'''




        a__     : Optional[Any]  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						List[str]:



        '''simple docstring'''




        def check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : int  =model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()

          with torch.no_grad():
            a__     : List[Any]  =model(**self._prepare_for_class(lowerCAmelCase__		,				lowerCAmelCase__							)							)

          a__     : Optional[int]  =outputs.hidden_states

          a__     : Optional[int]  =2_6
          self.assertEqual(len(lowerCAmelCase__							)		,				lowerCAmelCase__							)

        a__ ,							a__     : Optional[Any]  =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__     : Optional[int]  =True
          check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          a__     : Union[str, Any]  =True

          check_hidden_states_output(lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        a__     : Dict  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)







      @slow
      def        _lowercase  (   self							)       ->						Any:



        '''simple docstring'''




        for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__     : List[str]  =MobileNetVaModel.from_pretrained(lowerCAmelCase__							)
          self.assertIsNotNone(lowerCAmelCase__							)
def 					_A	(		):





  """simple docstring"""



  a__     : Optional[Any]  =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
  return image







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







      @cached_property
      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




        return (
            MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224"							) if is_vision_available() else None
        )







      @slow
      def        _lowercase  (   self							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : str  =MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"							).to(lowerCAmelCase__							)

        a__     : Optional[Any]  =self.default_image_processor
        a__     : Optional[int]  =prepare_img()
        a__     : Optional[int]  =image_processor(images=lowerCAmelCase__		,				return_tensors="pt"							).to(lowerCAmelCase__							)

        # forward pass
        with torch.no_grad():
          a__     : int  =model(**lowerCAmelCase__							)

        # verify the logits
        a__     : str  =torch.Size((1, 1_0_0_1)							)
        self.assertEqual(outputs.logits.shape		,				lowerCAmelCase__							)

        a__     : int  =torch.tensor([-4.17_39, -1.12_33, 3.12_05]							).to(lowerCAmelCase__							)

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






