





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       :     int   =     logging.get_logger(__name__)  # pylint: disable=invalid-name

__lowerCamelCase       :     Dict   =     """\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 					A__   (       __snake_case			):
      _UpperCAmelCase	:Union[PIL.Image.Image, np.ndarray]



class 					A__   (       __snake_case			):





      def __init__( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_       ,							A_   ):
       '''simple docstring'''




       if latents is None:
        UpperCamelCase	:					Optional[Any]       	=   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}"""   )
        UpperCamelCase	:					Dict       	=   latents.to(SCREAMING_SNAKE_CASE_   )

       UpperCamelCase	:					List[Any]       	=   latents * scheduler.init_noise_sigma
       return latents





      def        __UpperCamelCase( self       ,							A_=0   ):
       '''simple docstring'''




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

       UpperCamelCase	:					Union[str, Any]       	=   torch.device(F"""cuda:{gpu_id}"""   )

       UpperCamelCase	:					str       	=   [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        __UpperCamelCase( 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        __UpperCamelCase( self       ,							A_       ,							A_       ,							A_       ,							A_       ,							):
       '''simple docstring'''




       if isinstance(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_   ) and isinstance(image[0]       ,							torch.Tensor   ):
        UpperCamelCase	:					Dict       	=   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   ):
        UpperCamelCase	:					Tuple       	=   self.image_processor(SCREAMING_SNAKE_CASE_       ,							return_tensors="pt"   ).pixel_values[0].unsqueeze(0   )

       UpperCamelCase	:					List[str]       	=   image.to(dtype=self.image_encoder.dtype       ,							device=SCREAMING_SNAKE_CASE_   )

       UpperCamelCase	:					List[Any]       	=   self.image_encoder(SCREAMING_SNAKE_CASE_   )["last_hidden_state"]
       UpperCamelCase	:					Any       	=   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       UpperCamelCase	:					Optional[Any]       	=   image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_       ,							dim=0   )

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

       return image_embeds





      @torch.no_grad()
      @replace_example_docstring(SCREAMING_SNAKE_CASE_   )
      def __call__( self       ,							A_       ,							A_ = 1       ,							A_ = 25       ,							A_ = None       ,							A_ = None       ,							A_ = 4.0       ,							A_ = 64       ,							A_ = "pil"       ,							A_ = True       ,							):
       '''simple docstring'''




       if isinstance(SCREAMING_SNAKE_CASE_       ,							PIL.Image.Image   ):
        UpperCamelCase	:					Tuple       	=   1
       elif isinstance(SCREAMING_SNAKE_CASE_       ,							torch.Tensor   ):
        UpperCamelCase	:					str       	=   image.shape[0]
       elif isinstance(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_   ) and isinstance(image[0]       ,							(torch.Tensor, PIL.Image.Image)   ):
        UpperCamelCase	:					str       	=   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_   )}"""   )

       UpperCamelCase	:					int       	=   self._execution_device

       UpperCamelCase	:					Optional[Any]       	=   batch_size * num_images_per_prompt

       UpperCamelCase	:					int       	=   guidance_scale > 1.0
       UpperCamelCase	:					Optional[Any]       	=   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_   )
       UpperCamelCase	:					str       	=   self.scheduler.timesteps

       UpperCamelCase	:					Optional[int]       	=   self.prior.config.num_embeddings
       UpperCamelCase	:					int       	=   self.prior.config.embedding_dim

       UpperCamelCase	:					Dict       	=   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
       UpperCamelCase	:					Union[str, Any]       	=   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
        UpperCamelCase	:					Tuple       	=   torch.cat([latents] * 2   ) if do_classifier_free_guidance else latents
        UpperCamelCase	:					Optional[int]       	=   self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_       ,							SCREAMING_SNAKE_CASE_   )

        UpperCamelCase	:					List[str]       	=   self.prior(
            SCREAMING_SNAKE_CASE_       ,							timestep=SCREAMING_SNAKE_CASE_       ,							proj_embedding=SCREAMING_SNAKE_CASE_       ,							).predicted_image_embedding

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

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

        UpperCamelCase	:					str       	=   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_   )

       UpperCamelCase	:					List[Any]       	=   []
       for i, latent in enumerate(SCREAMING_SNAKE_CASE_   ):
        print()
        UpperCamelCase	:					Dict       	=   self.renderer.decode(
            latent[None, :]       ,							SCREAMING_SNAKE_CASE_       ,							size=SCREAMING_SNAKE_CASE_       ,							ray_batch_size=4096       ,							n_coarse_samples=64       ,							n_fine_samples=128       ,							)

        images.append(SCREAMING_SNAKE_CASE_   )

       UpperCamelCase	:					Optional[Any]       	=   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}"""   )

       UpperCamelCase	:					List[str]       	=   images.cpu().numpy()

       if output_type == "pil":
        UpperCamelCase	:					List[str]       	=   [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_   )


import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
						import bitsandbytes as bnb
						import torch
						import torch.nn as nn

						from ..pytorch_utils import ConvaD

if is_accelerate_available():
						from accelerate import init_empty_weights
						from accelerate.utils import find_tied_parameters

__a  			=					logging.get_logger(__name__)




def 				a						(							snake_case__:					Optional[int]						,   snake_case__:					Dict						,   snake_case__:					int						,   snake_case__:					List[str]=None						,   snake_case__:					List[Any]=None					):


				'''simple docstring'''
				# Recurse if needed
				if "." in tensor_name:
								lowercase_       =					tensor_name.split('''.'''					)
								for split in splits[:-1]:
												lowercase_       =					getattr(snake_case__						,   snake_case__					)
												if new_module is None:
																raise ValueError(F'''{module} has no attribute {split}.'''					)
												lowercase_       =					new_module
								lowercase_       =					splits[-1]

				if tensor_name not in module._parameters and tensor_name not in module._buffers:
								raise ValueError(F'''{module} does not have a parameter or a buffer named {tensor_name}.'''					)
				lowercase_       =					tensor_name in module._buffers
				lowercase_       =					getattr(snake_case__						,   snake_case__					)

				if old_value.device == torch.device('''meta'''					) and device not in ["meta", torch.device('''meta'''					)] and value is None:
								raise ValueError(F'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.'''					)

				lowercase_       =					False
				lowercase_       =					False
				if is_buffer or not is_bitsandbytes_available():
								lowercase_       =					False
								lowercase_       =					False
				else:
								lowercase_       =					hasattr(bnb.nn						,   '''Params4bit'''					) and isinstance(module._parameters[tensor_name]						,   bnb.nn.Paramsabit					)
								lowercase_       =					isinstance(module._parameters[tensor_name]						,   bnb.nn.IntaParams					)

				if is_abit or is_abit:
								lowercase_       =					module._parameters[tensor_name]
								if param.device.type != "cuda":
												if value is None:
																lowercase_       =					old_value.to(snake_case__					)
												elif isinstance(snake_case__						,   torch.Tensor					):
																lowercase_       =					value.to('''cpu'''					)
																if value.dtype == torch.inta:
																				lowercase_       =					version.parse(importlib.metadata.version('''bitsandbytes'''					)					) > version.parse(
																				    '''0.37.2'''					)
																				if not is_abit_serializable:
																								raise ValueError(
																								    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
																								    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''					)
												else:
																lowercase_       =					torch.tensor(snake_case__						,   device='''cpu'''					)

												# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
												# Since weights are saved in the correct "orientation", we skip transposing when loading.
												if issubclass(module.source_cls						,   snake_case__					) and fpaa_statistics is None:
																lowercase_       =					new_value.T

												lowercase_       =					old_value.__dict__
												if is_abit:
																lowercase_       =					bnb.nn.IntaParams(snake_case__						,   requires_grad=snake_case__						,   **snake_case__					).to(snake_case__					)
												elif is_abit:
																lowercase_       =					bnb.nn.Paramsabit(snake_case__						,   requires_grad=snake_case__						,   **snake_case__					).to(snake_case__					)

												lowercase_       =					new_value
												if fpaa_statistics is not None:
																setattr(module.weight						,   '''SCB'''						,   fpaa_statistics.to(snake_case__					)					)

				else:
								if value is None:
												lowercase_       =					old_value.to(snake_case__					)
								elif isinstance(snake_case__						,   torch.Tensor					):
												lowercase_       =					value.to(snake_case__					)
								else:
												lowercase_       =					torch.tensor(snake_case__						,   device=snake_case__					)

								if is_buffer:
												lowercase_       =					new_value
								else:
												lowercase_       =					nn.Parameter(snake_case__						,   requires_grad=old_value.requires_grad					)
												lowercase_       =					new_value




def 				a						(							snake_case__:					str						,   snake_case__:					Union[str, Any]=None						,   snake_case__:					Any=None						,   snake_case__:					List[str]=None						,   snake_case__:					Optional[Any]=False					):


				'''simple docstring'''
				for name, module in model.named_children():
								if current_key_name is None:
												lowercase_       =					[]
								current_key_name.append(snake_case__					)

								if (isinstance(snake_case__						,   nn.Linear					) or isinstance(snake_case__						,   snake_case__					)) and name not in modules_to_not_convert:
												# Check if the current key is not in the `modules_to_not_convert`
												if not any(key in '''.'''.join(snake_case__					) for key in modules_to_not_convert					):
																with init_empty_weights():
																				if isinstance(snake_case__						,   snake_case__					):
																								lowercase_  ,	lowercase_       =					module.weight.shape
																				else:
																								lowercase_       =					module.in_features
																								lowercase_       =					module.out_features

																				if quantization_config.quantization_method() == "llm_int8":
																								lowercase_       =					bnb.nn.LinearabitLt(
																								    snake_case__						,   snake_case__						,   module.bias is not None						,   has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight						,   threshold=quantization_config.llm_inta_threshold						,   )
																								lowercase_       =					True
																				else:
																								if (
																								    quantization_config.llm_inta_skip_modules is not None
																								    and name in quantization_config.llm_inta_skip_modules
																								):
																												pass
																								else:
																												lowercase_       =					bnb.nn.Linearabit(
																												    snake_case__						,   snake_case__						,   module.bias is not None						,   quantization_config.bnb_abit_compute_dtype						,   compress_statistics=quantization_config.bnb_abit_use_double_quant						,   quant_type=quantization_config.bnb_abit_quant_type						,   )
																												lowercase_       =					True
                    # Store the module class in case we need to transpose the weight later
																				lowercase_       =					type(snake_case__					)
																				# Force requires grad to False to avoid unexpected errors
																				model._modules[name].requires_grad_(snake_case__					)
								if len(list(module.children()					)					) > 0:
												lowercase_  ,	lowercase_       =					_replace_with_bnb_linear(
												    snake_case__						,   snake_case__						,   snake_case__						,   snake_case__						,   has_been_replaced=snake_case__						,   )
								# Remove the last key for recursion
								current_key_name.pop(-1					)
				return model, has_been_replaced




def 				a						(							snake_case__:					Any						,   snake_case__:					Any=None						,   snake_case__:					Union[str, Any]=None						,   snake_case__:					str=None					):


				'''simple docstring'''
				lowercase_       =					['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
				lowercase_  ,	lowercase_       =					_replace_with_bnb_linear(
				    snake_case__						,   snake_case__						,   snake_case__						,   snake_case__					)

				if not has_been_replaced:
								logger.warning(
								    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
								    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
								    ''' a bug.'''					)

				return model




def 				a						(							*snake_case__:					str						,   **snake_case__:					Dict					):


				'''simple docstring'''
				warnings.warn(
				    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''						,   snake_case__						,   )
				return replace_with_bnb_linear(*snake_case__						,   **snake_case__					)




def 				a						(							*snake_case__:					Any						,   **snake_case__:					List[Any]					):


				'''simple docstring'''
				warnings.warn(
				    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''						,   snake_case__						,   )
				return set_module_quantized_tensor_to_device(*snake_case__						,   **snake_case__					)




def 				a						(							snake_case__:					Optional[Any]					):


				'''simple docstring'''
				lowercase_       =					deepcopy(snake_case__					)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
				tied_model.tie_weights()

				lowercase_       =					find_tied_parameters(snake_case__					)
				# For compatibility with Accelerate < 0.18
				if isinstance(snake_case__						,   snake_case__					):
								lowercase_       =					sum(list(tied_params.values()					)						,   []					) + list(tied_params.keys()					)
				else:
								lowercase_       =					sum(snake_case__						,   []					)
				lowercase_       =					len(snake_case__					) > 0

				# Check if it is a base model
				lowercase_       =					not hasattr(snake_case__						,   model.base_model_prefix					)

				# Ignore this for base models (BertModel, GPT2Model, etc.)
				if (not has_tied_params) and is_base_model:
								return []

				# otherwise they have an attached head
				lowercase_       =					list(model.named_children()					)
				lowercase_       =					[list_modules[-1][0]]

				# add last module together with tied weights
				lowercase_       =					set(snake_case__					) - set(snake_case__					)
				lowercase_       =					list(set(snake_case__					)					) + list(snake_case__					)

				# remove ".weight" from the keys
				lowercase_       =					['''.weight''', '''.bias''']
				lowercase_       =					[]
				for name in list_untouched:
								for name_to_remove in names_to_remove:
												if name_to_remove in name:
																lowercase_       =					name.replace(snake_case__						,   ''''''					)
								filtered_module_names.append(snake_case__					)

				return filtered_module_names




