





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


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

__UpperCamelCase     :						Tuple						       =  '''
    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 		_SCREAMING_SNAKE_CASE			(_UpperCAmelCase					:    str  ,     _UpperCAmelCase					:    Optional[int]  ,     _UpperCAmelCase					:    Any=8			):
 lowerCAmelCase    				= height // scale_factor**2
 if height % scale_factor**2 != 0:
  new_height += 1
 lowerCAmelCase    				= width // scale_factor**2
 if width % scale_factor**2 != 0:
  new_width += 1
 return new_height * scale_factor, new_width * scale_factor







class       a							(   a__  ):



 def __init__(     self				,       _snake_case				,       _snake_case				,       _snake_case				,       ):







  """simple docstring"""






  super().__init__()

  self.register_modules(
      unet=_snake_case				,       scheduler=_snake_case				,       movq=_snake_case				,       )
  lowerCAmelCase    				= 2 ** (len(self.movq.config.block_out_channels     ) - 1)



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case     ):







  """simple docstring"""






  if latents is None:
   lowerCAmelCase    				= randn_tensor(_snake_case				,       generator=_snake_case				,       device=_snake_case				,       dtype=_snake_case     )
  else:
   if latents.shape != shape:
    raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'     )
   lowerCAmelCase    				= latents.to(_snake_case     )

  lowerCAmelCase    				= latents * scheduler.init_noise_sigma
  return latents



 def    UpperCamelCase__  (     self				,       _snake_case=0     ):







  """simple docstring"""






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

  lowerCAmelCase    				= torch.device(F'cuda:{gpu_id}'     )

  lowerCAmelCase    				= [
      self.unet,
      self.movq,
  ]
  for cpu_offloaded_model in models:
   if cpu_offloaded_model is not None:
    cpu_offload(_snake_case				,       _snake_case     )



 def    UpperCamelCase__  (     self				,       _snake_case=0     ):







  """simple docstring"""






  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    				= torch.device(F'cuda:{gpu_id}'     )

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

  lowerCAmelCase    				= None
  for cpu_offloaded_model in [self.unet, self.movq]:
   lowerCAmelCase				,lowerCAmelCase    				= cpu_offload_with_hook(_snake_case				,       _snake_case				,       prev_module_hook=_snake_case     )

  # We'll offload the last model manually.
  lowerCAmelCase    				= hook



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







  """simple docstring"""






  if not hasattr(self.unet				,       '_hf_hook'     ):
   return self.device
  for module in self.unet.modules():
   if (
       hasattr(_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



 @torch.no_grad()
 @replace_example_docstring(_snake_case     )
 def __call__(     self				,       _snake_case				,       _snake_case				,       _snake_case				,       _snake_case = 5_12				,       _snake_case = 5_12				,       _snake_case = 1_00				,       _snake_case = 4.0				,       _snake_case = 1				,       _snake_case = None				,       _snake_case = None				,       _snake_case = "pil"				,       _snake_case = True				,       ):







  """simple docstring"""






  lowerCAmelCase    				= self._execution_device

  lowerCAmelCase    				= guidance_scale > 1.0

  if isinstance(_snake_case				,       _snake_case     ):
   lowerCAmelCase    				= torch.cat(_snake_case				,       dim=0     )
  if isinstance(_snake_case				,       _snake_case     ):
   lowerCAmelCase    				= torch.cat(_snake_case				,       dim=0     )
  if isinstance(_snake_case				,       _snake_case     ):
   lowerCAmelCase    				= torch.cat(_snake_case				,       dim=0     )

  lowerCAmelCase    				= image_embeds.shape[0] * num_images_per_prompt

  if do_classifier_free_guidance:
   lowerCAmelCase    				= image_embeds.repeat_interleave(_snake_case				,       dim=0     )
   lowerCAmelCase    				= negative_image_embeds.repeat_interleave(_snake_case				,       dim=0     )
   lowerCAmelCase    				= hint.repeat_interleave(_snake_case				,       dim=0     )

  lowerCAmelCase    				= torch.cat([negative_image_embeds, image_embeds]				,       dim=0     ).to(dtype=self.unet.dtype				,       device=_snake_case     )
  lowerCAmelCase    				= torch.cat([hint, hint]				,       dim=0     ).to(dtype=self.unet.dtype				,       device=_snake_case     )
  self.scheduler.set_timesteps(_snake_case				,       device=_snake_case     )
  lowerCAmelCase    				= self.scheduler.timesteps

  lowerCAmelCase    				= self.movq.config.latent_channels

  lowerCAmelCase				,lowerCAmelCase    				= downscale_height_and_width(_snake_case				,       _snake_case				,       self.movq_scale_factor     )

  # create initial latent
  lowerCAmelCase    				= self.prepare_latents(
      (batch_size, num_channels_latents, height, width)				,       image_embeds.dtype				,       _snake_case				,       _snake_case				,       _snake_case				,       self.scheduler				,       )

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

   lowerCAmelCase    				= {'image_embeds': image_embeds, 'hint': hint}
   lowerCAmelCase    				= self.unet(
       sample=_snake_case				,       timestep=_snake_case				,       encoder_hidden_states=_snake_case				,       added_cond_kwargs=_snake_case				,       return_dict=_snake_case				,       )[0]

   if do_classifier_free_guidance:
    lowerCAmelCase				,lowerCAmelCase    				= noise_pred.split(latents.shape[1]				,       dim=1     )
    lowerCAmelCase				,lowerCAmelCase    				= noise_pred.chunk(2     )
    lowerCAmelCase				,lowerCAmelCase    				= variance_pred.chunk(2     )
    lowerCAmelCase    				= noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
    lowerCAmelCase    				= 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				,lowerCAmelCase    				= noise_pred.split(latents.shape[1]				,       dim=1     )

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

  if output_type == "pil":
   lowerCAmelCase    				= self.numpy_to_pil(_snake_case     )

  if not return_dict:
   return (image,)

  return ImagePipelineOutput(images=_snake_case     )












"""simple docstring"""
from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__UpperCamelCase     :						Union[str, Any]						       =  logging.get_logger(__name__)

__UpperCamelCase     :						Tuple						       =  {
    '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''',
    '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''',
    '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''',
    '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''',
    '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''',
    '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''',
    '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''',
    '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''',
    '''bert-large-uncased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''',
    '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''',
    '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-cased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-uncased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'''
    ),
    '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''',
    # See all BERT models at https://huggingface.co/models?filter=bert
}







class       a							(   a__  ):
 snake_case__             =       '''bert'''



 def __init__(     self				,       _snake_case=3_05_22				,       _snake_case=7_68				,       _snake_case=12				,       _snake_case=12				,       _snake_case=30_72				,       _snake_case="gelu"				,       _snake_case=0.1				,       _snake_case=0.1				,       _snake_case=5_12				,       _snake_case=2				,       _snake_case=0.02				,       _snake_case=1E-12				,       _snake_case=0				,       _snake_case="absolute"				,       _snake_case=True				,       _snake_case=None				,       **_snake_case				,       ):







  """simple docstring"""






  super().__init__(pad_token_id=_snake_case				,       **_snake_case     )

  lowerCAmelCase    				= vocab_size
  lowerCAmelCase    				= hidden_size
  lowerCAmelCase    				= num_hidden_layers
  lowerCAmelCase    				= num_attention_heads
  lowerCAmelCase    				= hidden_act
  lowerCAmelCase    				= intermediate_size
  lowerCAmelCase    				= hidden_dropout_prob
  lowerCAmelCase    				= attention_probs_dropout_prob
  lowerCAmelCase    				= max_position_embeddings
  lowerCAmelCase    				= type_vocab_size
  lowerCAmelCase    				= initializer_range
  lowerCAmelCase    				= layer_norm_eps
  lowerCAmelCase    				= position_embedding_type
  lowerCAmelCase    				= use_cache
  lowerCAmelCase    				= classifier_dropout







class       a							(   a__  ):



 @property
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  if self.task == "multiple-choice":
   lowerCAmelCase    				= {0: 'batch', 1: 'choice', 2: 'sequence'}
  else:
   lowerCAmelCase    				= {0: 'batch', 1: 'sequence'}
  return OrderedDict(
      [
          ('input_ids', dynamic_axis),
          ('attention_mask', dynamic_axis),
          ('token_type_ids', dynamic_axis),
      ]     )





