


import logging

# standard libraries
import sys

import numpy as np
import pytest  # type: ignore

# Custom/local libraries
from matrix import matrix_operation as matop

_UpperCAmelCase     :					Dict       =[[12, 10], [3, 9]]
_UpperCAmelCase     :					Tuple       =[[3, 4], [7, 4]]
_UpperCAmelCase     :					Any       =[[3, 0, 2], [2, 0, -2], [0, 1, 1]]
_UpperCAmelCase     :					Optional[int]       =[[3, 0, -2], [2, 0, 2], [0, 1, 1]]
_UpperCAmelCase     :					List[Any]       =[[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]]
_UpperCAmelCase     :					Any       =[1]
_UpperCAmelCase     :					Dict       =[2]

_UpperCAmelCase     :					Union[str, Any]       =logging.getLogger()
_UpperCAmelCase     :					Dict       =logging.DEBUG
_UpperCAmelCase     :					Dict       =logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ('''mat1''', '''mat2''')	,				[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]	)
def      lowerCAmelCase	(						lowerCAmelCase_	,				lowerCAmelCase_	)->	Union[str, Any]:
				if (np.array(lowerCAmelCase_	)).shape < (2, 2) or (np.array(lowerCAmelCase_	)).shape < (2, 2):
								with pytest.raises(lowerCAmelCase_	):
												logger.info(f"""\n\t{test_addition.__name__} returned integer"""	)
												matop.add(lowerCAmelCase_	,				lowerCAmelCase_	)
				elif (np.array(lowerCAmelCase_	)).shape == (np.array(lowerCAmelCase_	)).shape:
								logger.info(f"""\n\t{test_addition.__name__} with same matrix dims"""	)
								lowerCAmelCase_	: Dict      			=			(np.array(lowerCAmelCase_	) + np.array(lowerCAmelCase_	)).tolist()
								lowerCAmelCase_	: str      			=			matop.add(lowerCAmelCase_	,				lowerCAmelCase_	)
								assert theo == act
				else:
								with pytest.raises(lowerCAmelCase_	):
												logger.info(f"""\n\t{test_addition.__name__} with different matrix dims"""	)
												matop.add(lowerCAmelCase_	,				lowerCAmelCase_	)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ('''mat1''', '''mat2''')	,				[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]	)
def      lowerCAmelCase	(						lowerCAmelCase_	,				lowerCAmelCase_	)->	int:
				if (np.array(lowerCAmelCase_	)).shape < (2, 2) or (np.array(lowerCAmelCase_	)).shape < (2, 2):
								with pytest.raises(lowerCAmelCase_	):
												logger.info(f"""\n\t{test_subtraction.__name__} returned integer"""	)
												matop.subtract(lowerCAmelCase_	,				lowerCAmelCase_	)
				elif (np.array(lowerCAmelCase_	)).shape == (np.array(lowerCAmelCase_	)).shape:
								logger.info(f"""\n\t{test_subtraction.__name__} with same matrix dims"""	)
								lowerCAmelCase_	: List[Any]      			=			(np.array(lowerCAmelCase_	) - np.array(lowerCAmelCase_	)).tolist()
								lowerCAmelCase_	: Any      			=			matop.subtract(lowerCAmelCase_	,				lowerCAmelCase_	)
								assert theo == act
				else:
								with pytest.raises(lowerCAmelCase_	):
												logger.info(f"""\n\t{test_subtraction.__name__} with different matrix dims"""	)
												assert matop.subtract(lowerCAmelCase_	,				lowerCAmelCase_	)



@pytest.mark.mat_ops
@pytest.mark.parametrize(
    ('''mat1''', '''mat2''')	,				[(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]	)
def      lowerCAmelCase	(						lowerCAmelCase_	,				lowerCAmelCase_	)->	Any:
				if (np.array(lowerCAmelCase_	)).shape < (2, 2) or (np.array(lowerCAmelCase_	)).shape < (2, 2):
								logger.info(f"""\n\t{test_multiplication.__name__} returned integer"""	)
								with pytest.raises(lowerCAmelCase_	):
												matop.add(lowerCAmelCase_	,				lowerCAmelCase_	)
				elif (np.array(lowerCAmelCase_	)).shape == (np.array(lowerCAmelCase_	)).shape:
								logger.info(f"""\n\t{test_multiplication.__name__} meets dim requirements"""	)
								lowerCAmelCase_	: Optional[Any]      			=			(np.matmul(lowerCAmelCase_	,				lowerCAmelCase_	)).tolist()
								lowerCAmelCase_	: str      			=			matop.multiply(lowerCAmelCase_	,				lowerCAmelCase_	)
								assert theo == act
				else:
								with pytest.raises(lowerCAmelCase_	):
												logger.info(
												    f"""\n\t{test_multiplication.__name__} does not meet dim requirements"""	)
												assert matop.subtract(lowerCAmelCase_	,				lowerCAmelCase_	)



@pytest.mark.mat_ops
def      lowerCAmelCase	(						)->	List[Any]:
				lowerCAmelCase_	: Optional[int]      			=			(3.5 * np.array(lowerCAmelCase_	)).tolist()
				lowerCAmelCase_	: Tuple      			=			matop.scalar_multiply(lowerCAmelCase_	,				3.5	)
				assert theo == act



@pytest.mark.mat_ops
def      lowerCAmelCase	(						)->	Optional[int]:
				lowerCAmelCase_	: Any      			=			(np.identity(5	)).tolist()
				lowerCAmelCase_	: Union[str, Any]      			=			matop.identity(5	)
				assert theo == act




@pytest.mark.mat_ops
@pytest.mark.parametrize('''mat'''	,				[mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]	)
def      lowerCAmelCase	(						lowerCAmelCase_	)->	Tuple:
				if (np.array(lowerCAmelCase_	)).shape < (2, 2):
								with pytest.raises(lowerCAmelCase_	):
												logger.info(f"""\n\t{test_transpose.__name__} returned integer"""	)
												matop.transpose(lowerCAmelCase_	)
				else:
								lowerCAmelCase_	: Union[str, Any]      			=			(np.transpose(lowerCAmelCase_	)).tolist()
								lowerCAmelCase_	: Any      			=			matop.transpose(lowerCAmelCase_	,				return_map=lowerCAmelCase_	)
								assert theo == act



import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

_UpperCAmelCase     :					Optional[Any]       ="""
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

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

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

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

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

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""







@dataclass
class 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__ :					Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class 			snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						def __init__(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  )   ->      Optional[Any]:
										super().__init__()

										self.register_modules(
										    prior=__lowercase				,  text_encoder=__lowercase				,  tokenizer=__lowercase				,  scheduler=__lowercase				,  renderer=__lowercase				,  )




						def   lowercase_	(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase							)   ->      Tuple:
										if latents is None:
														lowerCAmelCase_	: Dict      			=			randn_tensor(__lowercase				,  generator=__lowercase				,  device=__lowercase				,  dtype=__lowercase							)
										else:
														if latents.shape != shape:
																		raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""							)
														lowerCAmelCase_	: Dict      			=			latents.to(__lowercase							)

										lowerCAmelCase_	: Tuple      			=			latents * scheduler.init_noise_sigma
										return latents




						def   lowercase_	(			self				,  __lowercase=0							)   ->      List[Any]:
										if is_accelerate_available():
														from accelerate import cpu_offload
										else:
														raise ImportError('''Please install accelerate via `pip install accelerate`'''							)

										lowerCAmelCase_	: Tuple      			=			torch.device(f"""cuda:{gpu_id}"""							)

										lowerCAmelCase_	: Tuple      			=			[self.text_encoder, self.prior]
										for cpu_offloaded_model in models:
														if cpu_offloaded_model is not None:
																		cpu_offload(__lowercase				,  __lowercase							)




						def   lowercase_	(			self				,  __lowercase=0							)   ->      Optional[int]:
										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.'''							)

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

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

										lowerCAmelCase_	: str      			=			None
										for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
														lowerCAmelCase_			,					lowerCAmelCase_	: Optional[int]      			=			cpu_offload_with_hook(__lowercase				,  __lowercase				,  prev_module_hook=__lowercase							)

										if self.safety_checker is not None:
														lowerCAmelCase_			,					lowerCAmelCase_	: Optional[Any]      			=			cpu_offload_with_hook(self.safety_checker				,  __lowercase				,  prev_module_hook=__lowercase							)

										# We'll offload the last model manually.
										lowerCAmelCase_	: Union[str, Any]      			=			hook




						@property
						def   lowercase_	(			self							)   ->      Optional[Any]:
										if self.device != torch.device('''meta'''							) or not hasattr(self.text_encoder				,  '''_hf_hook'''							):
														return self.device
										for module in self.text_encoder.modules():
														if (
														    hasattr(__lowercase				,  '''_hf_hook'''							)
														    and hasattr(module._hf_hook				,  '''execution_device'''							)
														    and module._hf_hook.execution_device is not None
														):
																		return torch.device(module._hf_hook.execution_device							)
										return self.device




						def   lowercase_	(			self				,  __lowercase				,  __lowercase				,  __lowercase				,  __lowercase				,  )   ->      Dict:
										len(__lowercase							) if isinstance(__lowercase				,  __lowercase							) else 1

										# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
										lowerCAmelCase_	: Any      			=			0
										# get prompt text embeddings
										lowerCAmelCase_	: Any      			=			self.tokenizer(
										    __lowercase				,  padding='''max_length'''				,  max_length=self.tokenizer.model_max_length				,  truncation=__lowercase				,  return_tensors='''pt'''				,  )
										lowerCAmelCase_	: Dict      			=			text_inputs.input_ids
										lowerCAmelCase_	: Optional[Any]      			=			self.tokenizer(__lowercase				,  padding='''longest'''				,  return_tensors='''pt'''							).input_ids

										if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__lowercase				,  __lowercase							):
														lowerCAmelCase_	: List[Any]      			=			self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]							)
														logger.warning(
														    '''The following part of your input was truncated because CLIP can only handle sequences up to'''
														    f""" {self.tokenizer.model_max_length} tokens: {removed_text}"""							)

										lowerCAmelCase_	: Any      			=			self.text_encoder(text_input_ids.to(__lowercase							)							)
										lowerCAmelCase_	: Dict      			=			text_encoder_output.text_embeds

										lowerCAmelCase_	: Union[str, Any]      			=			prompt_embeds.repeat_interleave(__lowercase				,  dim=0							)
										# in Shap-E it normalize the prompt_embeds and then later rescale it
										lowerCAmelCase_	: Optional[int]      			=			prompt_embeds / torch.linalg.norm(__lowercase				,  dim=-1				,  keepdim=__lowercase							)

										if do_classifier_free_guidance:
														lowerCAmelCase_	: Optional[Any]      			=			torch.zeros_like(__lowercase							)

														# 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_	: str      			=			torch.cat([negative_prompt_embeds, prompt_embeds]							)

										# Rescale the features to have unit variance
										lowerCAmelCase_	: List[Any]      			=			math.sqrt(prompt_embeds.shape[1]							) * prompt_embeds

										return prompt_embeds




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

										if isinstance(__lowercase				,  __lowercase							):
														lowerCAmelCase_	: List[str]      			=			1
										elif isinstance(__lowercase				,  __lowercase							):
														lowerCAmelCase_	: Optional[int]      			=			len(__lowercase							)
										else:
														raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__lowercase							)}"""							)

										lowerCAmelCase_	: Union[str, Any]      			=			self._execution_device

										lowerCAmelCase_	: Dict      			=			batch_size * num_images_per_prompt

										lowerCAmelCase_	: List[str]      			=			guidance_scale > 1.0
										lowerCAmelCase_	: List[Any]      			=			self._encode_prompt(__lowercase				,  __lowercase				,  __lowercase				,  __lowercase							)

										# prior

										self.scheduler.set_timesteps(__lowercase				,  device=__lowercase							)
										lowerCAmelCase_	: Any      			=			self.scheduler.timesteps

										lowerCAmelCase_	: Union[str, Any]      			=			self.prior.config.num_embeddings
										lowerCAmelCase_	: Dict      			=			self.prior.config.embedding_dim

										lowerCAmelCase_	: List[str]      			=			self.prepare_latents(
										    (batch_size, num_embeddings * embedding_dim)				,  prompt_embeds.dtype				,  __lowercase				,  __lowercase				,  __lowercase				,  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]				,  __lowercase				,  __lowercase							)

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

														lowerCAmelCase_	: List[str]      			=			self.prior(
														    __lowercase				,  timestep=__lowercase				,  proj_embedding=__lowercase				,  ).predicted_image_embedding

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

														lowerCAmelCase_	: Optional[int]      			=			self.scheduler.step(
														    __lowercase				,  timestep=__lowercase				,  sample=__lowercase				,  ).prev_sample

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

										lowerCAmelCase_	: Any      			=			[]
										for i, latent in enumerate(__lowercase							):
														lowerCAmelCase_	: str      			=			self.renderer.decode(
														    latent[None, :]				,  __lowercase				,  size=__lowercase				,  ray_batch_size=4_0_9_6				,  n_coarse_samples=6_4				,  n_fine_samples=1_2_8				,  )
														images.append(__lowercase							)

										lowerCAmelCase_	: List[str]      			=			torch.stack(__lowercase							)

										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_	: Optional[int]      			=			images.cpu().numpy()

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