






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

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


UpperCamelCase__ =			logging.get_logger(__name__)

UpperCamelCase__ =			{
    'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json',
    'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json',
    'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json',
    'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json',
    'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json',
    'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json',
    'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json',
    'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json',
    'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json',
    'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json',
}


class        _UpperCAmelCase						(		snake_case			):
    __lowerCamelCase:   List[str]		       =    'xlm'
    __lowerCamelCase:   Any		       =    {
        'hidden_size': 'emb_dim',
        'num_attention_heads': 'n_heads',
        'num_hidden_layers': 'n_layers',
        'n_words': 'vocab_size',  # For backward compatibility
    }




    def __init__(			self  :       Any  ,     a  :       str=3_0_1_4_5  ,     a  :       List[str]=2_0_4_8  ,     a  :       int=1_2  ,     a  :       int=1_6  ,     a  :       Optional[int]=0.1  ,     a  :       Optional[Any]=0.1  ,     a  :       List[Any]=True  ,     a  :       Optional[Any]=False  ,     a  :       Dict=False  ,     a  :       Union[str, Any]=False  ,     a  :       List[str]=1  ,     a  :       Any=True  ,     a  :       List[Any]=5_1_2  ,     a  :       Union[str, Any]=2_0_4_8**-0.5  ,     a  :       str=1e-12  ,     a  :       str=0.02  ,     a  :       Optional[int]=0  ,     a  :       int=1  ,     a  :       Optional[int]=2  ,     a  :       int=3  ,     a  :       str=5  ,     a  :       List[Any]=True  ,     a  :       Tuple="first"  ,     a  :       List[Any]=True  ,     a  :       str=None  ,     a  :       int=True  ,     a  :       Dict=0.1  ,     a  :       Any=5  ,     a  :       Tuple=5  ,     a  :       Dict=0  ,     a  :       List[str]=0  ,     a  :       Union[str, Any]=2  ,     a  :       str=0  ,     **a  :       Optional[Any]  ,     ):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     vocab_size
       lowercase_	:    str           =     emb_dim
       lowercase_	:    Any           =     n_layers
       lowercase_	:    Tuple           =     n_heads
       lowercase_	:    Union[str, Any]           =     dropout
       lowercase_	:    Optional[Any]           =     attention_dropout
       lowercase_	:    Union[str, Any]           =     gelu_activation
       lowercase_	:    Dict           =     sinusoidal_embeddings
       lowercase_	:    List[Any]           =     causal
       lowercase_	:    Dict           =     asm
       lowercase_	:    List[str]           =     n_langs
       lowercase_	:    int           =     use_lang_emb
       lowercase_	:    Union[str, Any]           =     layer_norm_eps
       lowercase_	:    List[Any]           =     bos_index
       lowercase_	:    Any           =     eos_index
       lowercase_	:    int           =     pad_index
       lowercase_	:    Dict           =     unk_index
       lowercase_	:    List[str]           =     mask_index
       lowercase_	:    Union[str, Any]           =     is_encoder
       lowercase_	:    Any           =     max_position_embeddings
       lowercase_	:    int           =     embed_init_std
       lowercase_	:    List[str]           =     init_std
       lowercase_	:    int           =     summary_type
       lowercase_	:    List[Any]           =     summary_use_proj
       lowercase_	:    Optional[Any]           =     summary_activation
       lowercase_	:    Dict           =     summary_proj_to_labels
       lowercase_	:    Any           =     summary_first_dropout
       lowercase_	:    Union[str, Any]           =     start_n_top
       lowercase_	:    List[Any]           =     end_n_top
       lowercase_	:    Optional[int]           =     mask_token_id
       lowercase_	:    List[Any]           =     lang_id

       if "n_words" in kwargs:
          lowercase_	:    str           =     kwargs["n_words"]

       super().__init__(pad_token_id=a  ,     bos_token_id=a  ,     **a			)


class        _UpperCAmelCase						(		snake_case			):




    @property
    def 				lowerCAmelCase__				(			self  :       Any			):






       '''simple docstring'''






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












'''simple docstring'''
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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

UpperCamelCase__ =			'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "A red cartoon frog, 4k"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to("cuda")\n\n        >>> init_image = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/frog.png"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save("red_frog.png")\n        ```\n'




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase=8							):


   """simple docstring"""




   lowercase_	:    Union[str, Any]           =     height // scale_factor**2
   if height % scale_factor**2 != 0:
      new_height += 1
   lowercase_	:    Union[str, Any]           =     width // scale_factor**2
   if width % scale_factor**2 != 0:
      new_width += 1
   return new_height * scale_factor, new_width * scale_factor




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase=512						,		_UpperCamelCase=512							):


   """simple docstring"""




   lowercase_	:    Union[str, Any]           =     pil_image.resize((w, h)						,		resample=Image.BICUBIC						,		reducing_gap=1							)
   lowercase_	:    str           =     np.array(pil_image.convert("RGB"							)							)
   lowercase_	:    Optional[int]           =     arr.astype(np.floataa							) / 127.5 - 1
   lowercase_	:    int           =     np.transpose(_UpperCamelCase						,		[2, 0, 1]							)
   lowercase_	:    str           =     torch.from_numpy(_UpperCamelCase							).unsqueeze(0							)
   return image





class        _UpperCAmelCase						(		snake_case			):




    def __init__(			self  :       List[Any]  ,     a  :       UNetaDConditionModel  ,     a  :       DDPMScheduler  ,     a  :       VQModel  ,     ):






       '''simple docstring'''






       super().__init__()

       self.register_modules(
           unet=a  ,     scheduler=a  ,     movq=a  ,     )
       lowercase_	:    Dict           =     2 ** (len(self.movq.config.block_out_channels			) - 1)




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       Tuple  ,     a  :       List[str]  ,     a  :       List[Any]			):






       '''simple docstring'''






       lowercase_	:    Dict           =     min(int(num_inference_steps * strength			)  ,     a			)

       lowercase_	:    str           =     max(num_inference_steps - init_timestep  ,     0			)
       lowercase_	:    Tuple           =     self.scheduler.timesteps[t_start:]

       return timesteps, num_inference_steps - t_start




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       int  ,     a  :       List[Any]  ,     a  :       Tuple  ,     a  :       Union[str, Any]  ,     a  :       int  ,     a  :       Tuple  ,     a  :       Optional[Any]=None			):






       '''simple docstring'''






       if not isinstance(a  ,     (torch.Tensor, PIL.Image.Image, list)			):
          raise ValueError(
              f"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a			)}"""			)

       lowercase_	:    str           =     image.to(device=a  ,     dtype=a			)

       lowercase_	:    Any           =     batch_size * num_images_per_prompt

       if image.shape[1] == 4:
          lowercase_	:    str           =     image

       else:
          if isinstance(a  ,     a			) and len(a			) != batch_size:
             raise ValueError(
                 f"""You have passed a list of generators of length {len(a			)}, but requested an effective batch"""
                 f""" size of {batch_size}. Make sure the batch size matches the length of the generators."""			)

          elif isinstance(a  ,     a			):
             lowercase_	:    str           =     [
                 self.movq.encode(image[i : i + 1]			).latent_dist.sample(generator[i]			) for i in range(a			)
             ]
             lowercase_	:    List[Any]           =     torch.cat(a  ,     dim=0			)
          else:
             lowercase_	:    Tuple           =     self.movq.encode(a			).latent_dist.sample(a			)

          lowercase_	:    Union[str, Any]           =     self.movq.config.scaling_factor * init_latents

       lowercase_	:    Tuple           =     torch.cat([init_latents]  ,     dim=0			)

       lowercase_	:    List[Any]           =     init_latents.shape
       lowercase_	:    Union[str, Any]           =     randn_tensor(a  ,     generator=a  ,     device=a  ,     dtype=a			)

       # get latents
       lowercase_	:    Dict           =     self.scheduler.add_noise(a  ,     a  ,     a			)

       lowercase_	:    Tuple           =     init_latents

       return latents




    def 				lowerCAmelCase__				(			self  :       List[Any]  ,     a  :       str=0			):






       '''simple docstring'''






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

       lowercase_	:    Optional[Any]           =     torch.device(f"""cuda:{gpu_id}"""			)

       lowercase_	:    Optional[Any]           =     [
           self.unet,
           self.movq,
       ]
       for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
             cpu_offload(a  ,     a			)




    def 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       Union[str, Any]=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."			)

       lowercase_	:    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)

       lowercase_	:    Optional[int]           =     None
       for cpu_offloaded_model in [self.unet, self.movq]:
          lowercase_    ,		lowercase_	:    Union[str, Any]           =     cpu_offload_with_hook(a  ,     a  ,     prev_module_hook=a			)

       # We'll offload the last model manually.
       lowercase_	:    List[Any]           =     hook




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






       '''simple docstring'''






       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  :       Optional[int]  ,     a  :       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,     a  :       Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]  ,     a  :       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,     a  :       int = 5_1_2  ,     a  :       int = 5_1_2  ,     a  :       int = 1_0_0  ,     a  :       float = 4.0  ,     a  :       float = 0.3  ,     a  :       int = 1  ,     a  :       Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,     a  :       Optional[str] = "pil"  ,     a  :       bool = True  ,     ):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     self._execution_device

       lowercase_	:    Dict           =     guidance_scale > 1.0

       if isinstance(a  ,     a			):
          lowercase_	:    Dict           =     torch.cat(a  ,     dim=0			)
       lowercase_	:    Dict           =     image_embeds.shape[0]
       if isinstance(a  ,     a			):
          lowercase_	:    str           =     torch.cat(a  ,     dim=0			)

       if do_classifier_free_guidance:
          lowercase_	:    Optional[Any]           =     image_embeds.repeat_interleave(a  ,     dim=0			)
          lowercase_	:    int           =     negative_image_embeds.repeat_interleave(a  ,     dim=0			)

       lowercase_	:    int           =     torch.cat([negative_image_embeds, image_embeds]  ,     dim=0			).to(dtype=self.unet.dtype  ,     device=a			)

       if not isinstance(a  ,     a			):
          lowercase_	:    List[Any]           =     [image]
       if not all(isinstance(a  ,     (PIL.Image.Image, torch.Tensor)			) for i in image			):
          raise ValueError(
              f"""Input is in incorrect format: {[type(a			) for i in image]}. Currently, we only support  PIL image and pytorch tensor"""			)

       lowercase_	:    List[Any]           =     torch.cat([prepare_image(a  ,     a  ,     a			) for i in image]  ,     dim=0			)
       lowercase_	:    List[Any]           =     image.to(dtype=image_embeds.dtype  ,     device=a			)

       lowercase_	:    Optional[int]           =     self.movq.encode(a			)["latents"]
       lowercase_	:    Dict           =     latents.repeat_interleave(a  ,     dim=0			)
       self.scheduler.set_timesteps(a  ,     device=a			)
       lowercase_    ,		lowercase_	:    List[Any]           =     self.get_timesteps(a  ,     a  ,     a			)
       lowercase_	:    Tuple           =     timesteps[:1].repeat(batch_size * num_images_per_prompt			)
       lowercase_    ,		lowercase_	:    Optional[Any]           =     downscale_height_and_width(a  ,     a  ,     self.movq_scale_factor			)
       lowercase_	:    Tuple           =     self.prepare_latents(
           a  ,     a  ,     a  ,     a  ,     image_embeds.dtype  ,     a  ,     a			)
       for i, t in enumerate(self.progress_bar(a			)			):
          # expand the latents if we are doing classifier free guidance
          lowercase_	:    Tuple           =     torch.cat([latents] * 2			) if do_classifier_free_guidance else latents

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

          # compute the previous noisy sample x_t -> x_t-1
          lowercase_	:    Dict           =     self.scheduler.step(
              a  ,     a  ,     a  ,     generator=a  ,     )[0]

       # post-processing
       lowercase_	:    Optional[Any]           =     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"]:
          lowercase_	:    Tuple           =     image * 0.5 + 0.5
          lowercase_	:    Any           =     image.clamp(0  ,     1			)
          lowercase_	:    Any           =     image.cpu().permute(0  ,     2  ,     3  ,     1			).float().numpy()

       if output_type == "pil":
          lowercase_	:    Tuple           =     self.numpy_to_pil(a			)

       if not return_dict:
          return (image,)

       return ImagePipelineOutput(images=a			)




