





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


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

snake_case_     =	"""
    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 							_lowerCamelCase(  UpperCamelCase__    : Any    ,       UpperCamelCase__    : Dict    ,       UpperCamelCase__    : Tuple=8		)		->  List[str]:
    A       :       Optional[Any]							=						height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    A       :       List[str]							=						width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor





class   _lowercase						(							lowercase_				):


   def __init__( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   ):
       super().__init__()

       self.register_modules(
           unet=lowerCamelCase_    ,   scheduler=lowerCamelCase_    ,   movq=lowerCamelCase_    ,   )
       A       :       str							=						2 ** (len(self.movq.config.block_out_channels					) - 1)


   def 					snake_case				( self    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase					):



       if latents is None:
           A       :       Tuple							=						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       :       Any							=						latents * scheduler.init_noise_sigma
       return latents


   def 					snake_case				( self    ,   _UpperCAmelCase=0					):



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

       A       :       List[Any]							=						torch.device(f'''cuda:{gpu_id}'''					)

       A       :       Union[str, Any]							=						[
           self.unet,
           self.movq,
       ]
       for cpu_offloaded_model in models:
           if cpu_offloaded_model is not None:
               cpu_offload(lowerCamelCase_    ,   lowerCamelCase_					)


   def 					snake_case				( self    ,   _UpperCAmelCase=0					):



       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       :       Any							=						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       :       Union[str, Any]							=						None
       for cpu_offloaded_model in [self.unet, self.movq]:
           A       :       List[Any]							=						cpu_offload_with_hook(lowerCamelCase_    ,   lowerCamelCase_    ,   prev_module_hook=lowerCamelCase_					)

       # We'll offload the last model manually.
       A       :       str							=						hook


   @property
   # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
   def 					snake_case				( self					):



       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    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase    ,   _UpperCAmelCase = 512    ,   _UpperCAmelCase = 512    ,   _UpperCAmelCase = 100    ,   _UpperCAmelCase = 4.0    ,   _UpperCAmelCase = 1    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = None    ,   _UpperCAmelCase = "pil"    ,   _UpperCAmelCase = True    ,   ):
       A       :       str							=						self._execution_device

       A       :       Optional[int]							=						guidance_scale > 1.0

       if isinstance(lowerCamelCase_    ,   lowerCamelCase_					):
           A       :       int							=						torch.cat(lowerCamelCase_    ,   dim=0					)
       if isinstance(lowerCamelCase_    ,   lowerCamelCase_					):
           A       :       Dict							=						torch.cat(lowerCamelCase_    ,   dim=0					)
       if isinstance(lowerCamelCase_    ,   lowerCamelCase_					):
           A       :       Optional[Any]							=						torch.cat(lowerCamelCase_    ,   dim=0					)

       A       :       Any							=						image_embeds.shape[0] * num_images_per_prompt

       if do_classifier_free_guidance:
           A       :       List[Any]							=						image_embeds.repeat_interleave(lowerCamelCase_    ,   dim=0					)
           A       :       Optional[int]							=						negative_image_embeds.repeat_interleave(lowerCamelCase_    ,   dim=0					)
           A       :       Dict							=						hint.repeat_interleave(lowerCamelCase_    ,   dim=0					)

       A       :       List[Any]							=						torch.cat([negative_image_embeds, image_embeds]    ,   dim=0					).to(dtype=self.unet.dtype    ,   device=lowerCamelCase_					)
       A       :       Optional[int]							=						torch.cat([hint, hint]    ,   dim=0					).to(dtype=self.unet.dtype    ,   device=lowerCamelCase_					)
       self.scheduler.set_timesteps(lowerCamelCase_    ,   device=lowerCamelCase_					)
       A       :       Union[str, Any]							=						self.scheduler.timesteps

       A       :       Any							=						self.movq.config.latent_channels

       A       :       Optional[Any]							=						downscale_height_and_width(lowerCamelCase_    ,   lowerCamelCase_    ,   self.movq_scale_factor					)

       # create initial latent
       A       :       str							=						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       :       Dict							=						torch.cat([latents] * 2					) if do_classifier_free_guidance else latents

           A       :       Union[str, Any]							=						{"""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       :       str							=						noise_pred.split(latents.shape[1]    ,   dim=1					)
               A       :       Optional[Any]							=						noise_pred.chunk(2					)
               A       :       Union[str, Any]							=						variance_pred.chunk(2					)
               A       :       List[str]							=						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       :       Optional[Any]							=						noise_pred.split(latents.shape[1]    ,   dim=1					)

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

       if output_type == "pil":
           A       :       Any							=						self.numpy_to_pil(lowerCamelCase_					)

       if not return_dict:
           return (image,)

       return ImagePipelineOutput(images=lowerCamelCase_					)








'''simple docstring'''






def 							_lowerCamelCase(  UpperCamelCase__    : int		)		->  None:
    A       :       List[Any]							=						generate_pascal_triangle(UpperCamelCase__		)
    for row_idx in range(UpperCamelCase__		):
        # Print left spaces
        for _ in range(num_rows - row_idx - 1		):
            print(end=''' '''		)
        # Print row values
        for col_idx in range(row_idx + 1		):
            if col_idx != row_idx:
                print(triangle[row_idx][col_idx]    ,       end=''' '''		)
            else:
                print(triangle[row_idx][col_idx]    ,       end=''''''		)
        print()
def 							_lowerCamelCase(  UpperCamelCase__    : int		)		->  list[list[int]]:

    if not isinstance(UpperCamelCase__    ,       UpperCamelCase__		):
        raise TypeError('''The input value of \'num_rows\' should be \'int\''''		)

    if num_rows == 0:
        return []
    elif num_rows < 0:
        raise ValueError(
            '''The input value of \'num_rows\' should be greater than or equal to 0'''		)

    A       :       list[list[int]]							=						[]
    for current_row_idx in range(UpperCamelCase__		):
        A       :       Optional[int]							=						populate_current_row(UpperCamelCase__    ,       UpperCamelCase__		)
        triangle.append(UpperCamelCase__		)
    return triangle
def 							_lowerCamelCase(  UpperCamelCase__    : list[list[int]]    ,       UpperCamelCase__    : int		)		->  list[int]:
    A       :       Dict							=						[-1] * (current_row_idx + 1)
    # first and last elements of current row are equal to 1
    A,	A       :       Union[str, Any]							=						1, 1
    for current_col_idx in range(1    ,       UpperCamelCase__		):
        calculate_current_element(
            UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__    ,       UpperCamelCase__		)
    return current_row
def 							_lowerCamelCase(  UpperCamelCase__    : list[list[int]]    ,       UpperCamelCase__    : list[int]    ,       UpperCamelCase__    : int    ,       UpperCamelCase__    : int    ,       )		->  None:
    A       :       Dict							=						triangle[current_row_idx - 1][current_col_idx - 1]
    A       :       Any							=						triangle[current_row_idx - 1][current_col_idx]
    A       :       Optional[int]							=						above_to_left_elt + above_to_right_elt
def 							_lowerCamelCase(  UpperCamelCase__    : int		)		->  list[list[int]]:

    if not isinstance(UpperCamelCase__    ,       UpperCamelCase__		):
        raise TypeError('''The input value of \'num_rows\' should be \'int\''''		)

    if num_rows == 0:
        return []
    elif num_rows < 0:
        raise ValueError(
            '''The input value of \'num_rows\' should be greater than or equal to 0'''		)

    A       :       list[list[int]]							=						[[1]]

    for row_index in range(1    ,       UpperCamelCase__		):
        A       :       str							=						[0] + result[-1] + [0]
        A       :       Optional[Any]							=						row_index + 1
        # Calculate the number of distinct elements in a row
        A       :       str							=						sum(divmod(UpperCamelCase__    ,       2		)		)
        A       :       Optional[int]							=						[
            temp_row[i - 1] + temp_row[i] for i in range(1    ,       distinct_elements + 1		)
        ]
        A       :       Any							=						row_first_half[: (row_index + 1) // 2]
        row_second_half.reverse()
        A       :       Any							=						row_first_half + row_second_half
        result.append(UpperCamelCase__		)

    return result
def 							_lowerCamelCase(  )		->  None:
    from collections.abc import Callable
    from timeit import timeit

    def benchmark_a_function(UpperCamelCase__    : Callable    ,       UpperCamelCase__    : int		) -> None:
        A       :       Dict							=						F'''{func.__name__}({value})'''
        A       :       List[Any]							=						timeit(F'''__main__.{call}'''    ,       setup='''import __main__'''		)
        # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
        print(F'''{call:38} -- {timing:.4f} seconds'''		)

    for value in range(15		):  # (1, 7, 14):
        for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
            benchmark_a_function(UpperCamelCase__    ,       UpperCamelCase__		)
        print()


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     benchmark()
