


"""simple docstring"""


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,
)


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

__lowerCamelCase      :Dict	    =		'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n        >>> pipe_prior.to("cuda")\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n        >>> pipe.to("cuda")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save("cat.png")\n        ```\n'




def   snake_case		(     UpperCamelCase__       :						int			,				UpperCamelCase__       :						str			,				UpperCamelCase__       :						int=8    )   ->      List[str]:
      lowerCamelCase					:					Union[str, Any]        =	height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      lowerCamelCase					:					List[Any]        =	width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor






class 			A__	(						__lowercase):


     """simple docstring"""

     def __init__(	self:						Union[str, Any]     ,		__a:						UNetaDConditionModel     ,		__a:						DDPMScheduler     ,		__a:						VQModel     ,		)->    Optional[Any]:
           super().__init__()

           self.register_modules(
               unet=__a     ,		scheduler=__a     ,		movq=__a     ,		)
           lowerCamelCase					:					Optional[int]        =	2 ** (len(self.movq.config.block_out_channels	) - 1)

     def 		a__						(	self:						Optional[Any]     ,		__a:						Optional[int]     ,		__a:						Any     ,		__a:						List[Any]     ,		__a:						str     ,		__a:						List[str]     ,		__a:						Dict	)->    Dict:
           if latents is None:
                 lowerCamelCase					:					Optional[Any]        =	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					:					int        =	latents.to(__a	)

           lowerCamelCase					:					Dict        =	latents * scheduler.init_noise_sigma
           return latents

     def 		a__						(	self:						Optional[int]     ,		__a:						Optional[int]=0	)->    List[str]:
           if is_accelerate_available():
                 from accelerate import cpu_offload
           else:
                 raise ImportError("""Please install accelerate via `pip install accelerate`"""	)

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

           lowerCamelCase					:					List[str]        =	[
               self.unet,
               self.movq,
           ]
           for cpu_offloaded_model in models:
                 if cpu_offloaded_model is not None:
                       cpu_offload(__a     ,		__a	)

     def 		a__						(	self:						List[Any]     ,		__a:						List[Any]=0	)->    List[str]:
           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=__a	)
                 torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

           lowerCamelCase					:					Tuple        =	None
           for cpu_offloaded_model in [self.unet, self.movq]:
                 lowerCamelCase					:					Any        =	cpu_offload_with_hook(__a     ,		__a     ,		prev_module_hook=__a	)

           # We'll offload the last model manually.
           lowerCamelCase					:					Optional[int]        =	hook

     @property
     # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
     def 		a__						(	self:						Optional[Any]	)->    Union[str, Any]:
           if not hasattr(self.unet     ,		"""_hf_hook"""	):
                 return self.device
           for module in self.unet.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







     @torch.no_grad()
     @replace_example_docstring(__a	)
     def __call__(	self:						List[str]     ,		__a:						Union[torch.FloatTensor, List[torch.FloatTensor]]     ,		__a:						Union[torch.FloatTensor, List[torch.FloatTensor]]     ,		__a:						int = 512     ,		__a:						int = 512     ,		__a:						int = 100     ,		__a:						float = 4.0     ,		__a:						int = 1     ,		__a:						Optional[Union[torch.Generator, List[torch.Generator]]] = None     ,		__a:						Optional[torch.FloatTensor] = None     ,		__a:						Optional[str] = "pil"     ,		__a:						bool = True     ,		)->    Optional[int]:
           lowerCamelCase					:					int        =	self._execution_device

           lowerCamelCase					:					Optional[Any]        =	guidance_scale > 1.0

           if isinstance(__a     ,		__a	):
                 lowerCamelCase					:					Optional[Any]        =	torch.cat(__a     ,		dim=0	)
           lowerCamelCase					:					Tuple        =	image_embeds.shape[0] * num_images_per_prompt
           if isinstance(__a     ,		__a	):
                 lowerCamelCase					:					Union[str, Any]        =	torch.cat(__a     ,		dim=0	)

           if do_classifier_free_guidance:
                 lowerCamelCase					:					List[Any]        =	image_embeds.repeat_interleave(__a     ,		dim=0	)
                 lowerCamelCase					:					Union[str, Any]        =	negative_image_embeds.repeat_interleave(__a     ,		dim=0	)

           lowerCamelCase					:					List[Any]        =	torch.cat([negative_image_embeds, image_embeds]     ,		dim=0	).to(dtype=self.unet.dtype     ,		device=__a	)

           self.scheduler.set_timesteps(__a     ,		device=__a	)
           lowerCamelCase					:					List[str]        =	self.scheduler.timesteps

           lowerCamelCase					:					Tuple        =	self.unet.config.in_channels

           lowerCamelCase					:					Dict        =	downscale_height_and_width(__a     ,		__a     ,		self.movq_scale_factor	)

           # create initial latent
           lowerCamelCase					:					Tuple        =	self.prepare_latents(
               (batch_size, num_channels_latents, height, width)     ,		image_embeds.dtype     ,		__a     ,		__a     ,		__a     ,		self.scheduler     ,		)

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

                 lowerCamelCase					:					Tuple        =	{"""image_embeds""": image_embeds}
                 lowerCamelCase					:					Optional[int]        =	self.unet(
                     sample=__a     ,		timestep=__a     ,		encoder_hidden_states=__a     ,		added_cond_kwargs=__a     ,		return_dict=__a     ,		)[0]

                 if do_classifier_free_guidance:
                       lowerCamelCase					:					Optional[Any]        =	noise_pred.split(latents.shape[1]     ,		dim=1	)
                       lowerCamelCase					:					List[str]        =	noise_pred.chunk(2	)
                       lowerCamelCase					:					Any        =	variance_pred.chunk(2	)
                       lowerCamelCase					:					Dict        =	noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                       lowerCamelCase					:					List[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"]
                 ):
                       lowerCamelCase					:					Optional[int]        =	noise_pred.split(latents.shape[1]     ,		dim=1	)

                 # compute the previous noisy sample x_t -> x_t-1
                 lowerCamelCase					:					Any        =	self.scheduler.step(
                     __a     ,		__a     ,		__a     ,		generator=__a     ,		)[0]
           # post-processing
           lowerCamelCase					:					str        =	self.movq.decode(__a     ,		force_not_quantize=__a	)["""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"]:
                 lowerCamelCase					:					str        =	image * 0.5 + 0.5
                 lowerCamelCase					:					List[str]        =	image.clamp(0     ,		1	)
                 lowerCamelCase					:					str        =	image.cpu().permute(0     ,		2     ,		3     ,		1	).float().numpy()

           if output_type == "pil":
                 lowerCamelCase					:					Dict        =	self.numpy_to_pil(__a	)

           if not return_dict:
                 return (image,)

           return ImagePipelineOutput(images=__a	)








"""simple docstring"""


import unittest

from knapsack import greedy_knapsack as kp


class 			A__	(						unittest.TestCase):


     """simple docstring"""

     def 		a__						(	self:						Optional[int]	)->    Union[str, Any]:
           lowerCamelCase					:					Tuple        =	[10, 20, 30, 40, 50, 60]
           lowerCamelCase					:					Union[str, Any]        =	[2, 4, 6, 8, 10, 12]
           lowerCamelCase					:					Union[str, Any]        =	100
           self.assertEqual(kp.calc_profit(__a     ,		__a     ,		__a	)     ,		210	)

     def 		a__						(	self:						str	)->    str:
           self.assertRaisesRegex(__a     ,		"""max_weight must greater than zero."""	)

     def 		a__						(	self:						str	)->    List[Any]:
           self.assertRaisesRegex(__a     ,		"""Weight can not be negative."""	)

     def 		a__						(	self:						Any	)->    Dict:
           self.assertRaisesRegex(__a     ,		"""Profit can not be negative."""	)

     def 		a__						(	self:						Optional[Any]	)->    List[Any]:
           self.assertRaisesRegex(__a     ,		"""max_weight must greater than zero."""	)







     def 		a__						(	self:						Optional[Any]	)->    Tuple:
           self.assertRaisesRegex(
               __a     ,		"""The length of profit and weight must be same."""	)


if __name__ == "__main__":
    unittest.main()




