
'''simple docstring'''






import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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


if is_torch_available():
 import torch

 from transformers import UperNetForSemanticSegmentation
 from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class  UpperCAmelCase__						:



    def __init__(	self      :       Optional[Any],__A      :       Union[str, Any],__A      :       Optional[Any]=1_3,__A      :       Optional[Any]=3_2,__A      :       Union[str, Any]=3,__A      :       List[Any]=4,__A      :       List[str]=[1_0, 2_0, 3_0, 4_0],__A      :       Tuple=[2, 2, 3, 2],__A      :       int=True,__A      :       List[str]=True,__A      :       Dict=3_7,__A      :       Optional[int]="gelu",__A      :       Dict=1_0,__A      :       Optional[Any]=0.02,__A      :       Any=["stage2", "stage3", "stage4"],__A      :       List[Any]=3,__A      :       Any=None,):
          _lowerCamelCase				:   Any								=   parent
          _lowerCamelCase				:   Optional[int]								=   batch_size
          _lowerCamelCase				:   Dict								=   image_size
          _lowerCamelCase				:   List[str]								=   num_channels
          _lowerCamelCase				:   Tuple								=   num_stages
          _lowerCamelCase				:   Dict								=   hidden_sizes
          _lowerCamelCase				:   Dict								=   depths
          _lowerCamelCase				:   Dict								=   is_training
          _lowerCamelCase				:   Optional[int]								=   use_labels
          _lowerCamelCase				:   List[str]								=   intermediate_size
          _lowerCamelCase				:   List[str]								=   hidden_act
          _lowerCamelCase				:   Dict								=   type_sequence_label_size
          _lowerCamelCase				:   List[str]								=   initializer_range
          _lowerCamelCase				:   List[Any]								=   out_features
          _lowerCamelCase				:   int								=   num_labels
          _lowerCamelCase				:   Union[str, Any]								=   scope
          _lowerCamelCase				:   str								=   num_stages



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   str								=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

          _lowerCamelCase				:   List[str]								=   None
          if self.use_labels:
                _lowerCamelCase				:   List[Any]								=   ids_tensor([self.batch_size],self.type_sequence_label_size     )

          _lowerCamelCase				:   str								=   self.get_config()

          return config, pixel_values, labels



    def   lowerCamelCase_  (	self      :       Dict     ):
          return ConvNextConfig(
              num_channels=self.num_channels,num_stages=self.num_stages,hidden_sizes=self.hidden_sizes,depths=self.depths,is_training=self.is_training,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,out_features=self.out_features,)



    def   lowerCamelCase_  (	self      :       List[str]     ):
          return UperNetConfig(
              backbone_config=self.get_backbone_config(),hidden_size=5_1_2,pool_scales=[1, 2, 3, 6],use_auxiliary_head=__A,auxiliary_loss_weight=0.4,auxiliary_in_channels=4_0,auxiliary_channels=2_5_6,auxiliary_num_convs=1,auxiliary_concat_input=__A,loss_ignore_index=2_5_5,num_labels=self.num_labels,)



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       List[Any],__A      :       str,__A      :       List[Any]     ):
          _lowerCamelCase				:   Union[str, Any]								=   UperNetForSemanticSegmentation(config=__A     )
          model.to(__A     )
          model.eval()
          _lowerCamelCase				:   List[str]								=   model(__A     )
          self.parent.assertEqual(
              result.logits.shape,(self.batch_size, self.num_labels, self.image_size, self.image_size)     )



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


@require_torch
class  UpperCAmelCase__						(       A						,	A						,	unittest.TestCase ):
    lowerCAmelCase_				    =		(UperNetForSemanticSegmentation,) if is_torch_available() else ()
    lowerCAmelCase_				    =		{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   int								=   UperNetModelTester(self     )
          _lowerCamelCase				:   str								=   ConfigTester(self,config_class=__A,has_text_modality=__A,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Dict     ):
          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()



    def   lowerCamelCase_  (	self      :       str     ):
          return



    def   lowerCamelCase_  (	self      :       int     ):
          _lowerCamelCase				:   Tuple								=   self.model_tester.prepare_config_and_inputs_for_common()

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

                _lowerCamelCase				:   Dict								=   ["pixel_values"]
                self.assertListEqual(arg_names[:1],__A     )



    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          _lowerCamelCase				:   Optional[int]								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*__A     )



    @unittest.skip(reason="UperNet does not use inputs_embeds"     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip(reason="UperNet does not support input and output embeddings"     )
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          pass



    @unittest.skip(reason="UperNet does not have a base model"     )
    def   lowerCamelCase_  (	self      :       Dict     ):
          pass



    @unittest.skip(reason="UperNet does not have a base model"     )
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          pass



    @require_torch_multi_gpu
    @unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"     )
    def   lowerCamelCase_  (	self      :       Any     ):
          pass



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



    def   lowerCamelCase_  (	self      :       int     ):
          def check_hidden_states_output(__A      :       int,__A      :       List[str],__A      :       Optional[int]     ):
                _lowerCamelCase				:   Any								=   model_class(__A     )
                model.to(__A     )
                model.eval()

                with torch.no_grad():
                      _lowerCamelCase				:   Dict								=   model(**self._prepare_for_class(__A,__A     )     )

                _lowerCamelCase				:   Optional[int]								=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                _lowerCamelCase				:   Any								=   self.model_tester.num_stages
                self.assertEqual(len(__A     ),expected_num_stages + 1     )

                # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]     ),[self.model_tester.image_size // 4, self.model_tester.image_size // 4],)

          _lowerCamelCase				:   int								=   self.model_tester.prepare_config_and_inputs_for_common()

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

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                _lowerCamelCase				:   List[str]								=   True

                check_hidden_states_output(__A,__A,__A     )



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   Optional[int]								=   self.model_tester.prepare_config_and_inputs_for_common()

          _lowerCamelCase				:   Optional[int]								=   _config_zero_init(__A     )
          _lowerCamelCase				:   int								=   _config_zero_init(configs_no_init.backbone_config     )
          for model_class in self.all_model_classes:
                _lowerCamelCase				:   Union[str, Any]								=   model_class(config=__A     )
                for name, param in model.named_parameters():
                      if param.requires_grad:
                            self.assertIn(
                                ((param.data.mean() * 1e9).round() / 1e9).item(),[0.0, 1.0],msg=f'Parameter {name} of model {model_class} seems not properly initialized',)



    @unittest.skip(reason="UperNet does not have tied weights"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @slow
    def   lowerCamelCase_  (	self      :       Any     ):
          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _lowerCamelCase				:   int								=   UperNetForSemanticSegmentation.from_pretrained(__A     )
                self.assertIsNotNone(__A     )







def 		A_       (	):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   hf_hub_download(
          repo_id="hf-internal-testing/fixtures_ade20k"				,	repo_type="dataset"				,	filename="ADE_val_00000001.jpg"							)
      _lowerCamelCase				:   Any								=   Image.open(_lowerCAmelCase							).convert("RGB"							)
      return image





@require_torch
@require_vision
@slow
class  UpperCAmelCase__						(       unittest.TestCase ):



    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   List[Any]								=   AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"     )
          _lowerCamelCase				:   List[Any]								=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"     ).to(__A     )

          _lowerCamelCase				:   Optional[int]								=   prepare_img()
          _lowerCamelCase				:   Dict								=   processor(images=__A,return_tensors="pt"     ).to(__A     )

          with torch.no_grad():
                _lowerCamelCase				:   Optional[int]								=   model(**__A     )

          _lowerCamelCase				:   Union[str, Any]								=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)     )
          self.assertEqual(outputs.logits.shape,__A     )

          _lowerCamelCase				:   Optional[Any]								=   torch.tensor(
              [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]     ).to(__A     )
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],__A,atol=1e-4     )     )



    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   int								=   AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"     )
          _lowerCamelCase				:   List[Any]								=   UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"     ).to(__A     )

          _lowerCamelCase				:   List[str]								=   prepare_img()
          _lowerCamelCase				:   Optional[Any]								=   processor(images=__A,return_tensors="pt"     ).to(__A     )

          with torch.no_grad():
                _lowerCamelCase				:   Any								=   model(**__A     )

          _lowerCamelCase				:   str								=   torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)     )
          self.assertEqual(outputs.logits.shape,__A     )

          _lowerCamelCase				:   Dict								=   torch.tensor(
              [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]     ).to(__A     )
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3],__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     )