'''simple docstring'''




from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .text_encoder import MultilingualCLIP


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

__SCREAMING_SNAKE_CASE       :     Tuple     =  """
    Examples:
        ```py
        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\")
        >>> pipe_prior.to(\"cuda\")

        >>> prompt = \"red cat, 4k photo\"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> negative_image_emb = out.negative_image_embeds

        >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\")
        >>> pipe.to(\"cuda\")

        >>> image = pipe(
        ...     prompt,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=negative_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ... ).images

        >>> image[0].save(\"cat.png\")
        ```
"""

def 	UpperCamelCase_							(					_UpperCAmelCase  :      int			,	_UpperCAmelCase  :      List[Any]			,	_UpperCAmelCase  :      Optional[int]=8    )    ->    Dict:


       """simple docstring"""







       _UpperCAmelCase     :  Tuple							      =    h // scale_factor**2
       if h % scale_factor**2 != 0:
              new_h += 1
       _UpperCAmelCase     :  Optional[Any]							      =    w // scale_factor**2
       if w % scale_factor**2 != 0:
              new_w += 1
       return new_h * scale_factor, new_w * scale_factor


class 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      def __init__(       self						:				int						,					A						:				MultilingualCLIP						,					A						:				XLMRobertaTokenizer						,					A						:				UNetaDConditionModel						,					A						:				Union[DDIMScheduler, DDPMScheduler]						,					A						:				VQModel						,					):
             super().__init__()

             self.register_modules(
                 text_encoder=A						,					tokenizer=A						,					unet=A						,					scheduler=A						,					movq=A						,					)
             _UpperCAmelCase     :  Any							      =    2 ** (len(self.movq.config.block_out_channels       ) - 1)




      def      _A	(       self						:				Optional[Any]						,					A						:				List[str]						,					A						:				Optional[Any]						,					A						:				int						,					A						:				Any						,					A						:				List[str]						,					A						:				Optional[int]       ):
             if latents is None:
                    _UpperCAmelCase     :  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}"""       )
                    _UpperCAmelCase     :  List[str]							      =    latents.to(A       )

             _UpperCAmelCase     :  List[Any]							      =    latents * scheduler.init_noise_sigma
             return latents




      def      _A	(       self						:				str						,					A						:				Optional[Any]						,					A						:				List[Any]						,					A						:				str						,					A						:				Any						,					A						:				int=None						,					):
             _UpperCAmelCase     :  str							      =    len(A       ) if isinstance(A						,					A       ) else 1
             # get prompt text embeddings
             _UpperCAmelCase     :  Tuple							      =    self.tokenizer(
                 A						,					padding="max_length"						,					truncation=A						,					max_length=77						,					return_attention_mask=A						,					add_special_tokens=A						,					return_tensors="pt"						,					)

             _UpperCAmelCase     :  int							      =    text_inputs.input_ids
             _UpperCAmelCase     :  Dict							      =    self.tokenizer(A						,					padding="longest"						,					return_tensors="pt"       ).input_ids

             if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(A						,					A       ):
                    _UpperCAmelCase     :  List[str]							      =    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}"""       )

             _UpperCAmelCase     :  Optional[Any]							      =    text_input_ids.to(A       )
             _UpperCAmelCase     :  Tuple							      =    text_inputs.attention_mask.to(A       )

             _UpperCAmelCase      ,  _UpperCAmelCase     :  List[Any]							      =    self.text_encoder(
                 input_ids=A						,					attention_mask=A       )

             _UpperCAmelCase     :  Optional[int]							      =    prompt_embeds.repeat_interleave(A						,					dim=0       )
             _UpperCAmelCase     :  Union[str, Any]							      =    text_encoder_hidden_states.repeat_interleave(A						,					dim=0       )
             _UpperCAmelCase     :  Optional[Any]							      =    text_mask.repeat_interleave(A						,					dim=0       )

             if do_classifier_free_guidance:
                    _UpperCAmelCase     :  List[str]
                    if negative_prompt is None:
                           _UpperCAmelCase     :  Dict							      =    [""] * batch_size
                    elif type(A       ) is not type(A       ):
                           raise TypeError(
                               F"""`negative_prompt` should be the same type to `prompt`, but got {type(A       )} !="""
                               F""" {type(A       )}."""       )
                    elif isinstance(A						,					A       ):
                           _UpperCAmelCase     :  Dict							      =    [negative_prompt]
                    elif batch_size != len(A       ):
                           raise ValueError(
                               F"""`negative_prompt`: {negative_prompt} has batch size {len(A       )}, but `prompt`:"""
                               F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
                               " the batch size of `prompt`."       )
                    else:
                           _UpperCAmelCase     :  Tuple							      =    negative_prompt

                    _UpperCAmelCase     :  Optional[Any]							      =    self.tokenizer(
                        A						,					padding="max_length"						,					max_length=77						,					truncation=A						,					return_attention_mask=A						,					add_special_tokens=A						,					return_tensors="pt"						,					)
                    _UpperCAmelCase     :  Union[str, Any]							      =    uncond_input.input_ids.to(A       )
                    _UpperCAmelCase     :  List[Any]							      =    uncond_input.attention_mask.to(A       )

                    _UpperCAmelCase      ,  _UpperCAmelCase     :  int							      =    self.text_encoder(
                        input_ids=A						,					attention_mask=A       )

                    # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

                    _UpperCAmelCase     :  Optional[int]							      =    negative_prompt_embeds.shape[1]
                    _UpperCAmelCase     :  str							      =    negative_prompt_embeds.repeat(1						,					A       )
                    _UpperCAmelCase     :  str							      =    negative_prompt_embeds.view(batch_size * num_images_per_prompt						,					A       )

                    _UpperCAmelCase     :  Optional[int]							      =    uncond_text_encoder_hidden_states.shape[1]
                    _UpperCAmelCase     :  Union[str, Any]							      =    uncond_text_encoder_hidden_states.repeat(1						,					A						,					1       )
                    _UpperCAmelCase     :  List[Any]							      =    uncond_text_encoder_hidden_states.view(
                        batch_size * num_images_per_prompt						,					A						,					-1       )
                    _UpperCAmelCase     :  Union[str, Any]							      =    uncond_text_mask.repeat_interleave(A						,					dim=0       )

                    # done duplicates

                    # 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
                    _UpperCAmelCase     :  List[Any]							      =    torch.cat([negative_prompt_embeds, prompt_embeds]       )
                    _UpperCAmelCase     :  str							      =    torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]       )

                    _UpperCAmelCase     :  Tuple							      =    torch.cat([uncond_text_mask, text_mask]       )

             return prompt_embeds, text_encoder_hidden_states, text_mask




      def      _A	(       self						:				List[Any]						,					A						:				Union[str, Any]=0       ):
             if is_accelerate_available():
                    from accelerate import cpu_offload
             else:
                    raise ImportError("Please install accelerate via `pip install accelerate`"       )

             _UpperCAmelCase     :  str							      =    torch.device(F"""cuda:{gpu_id}"""       )

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




      def      _A	(       self						:				str						,					A						:				Any=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."       )

             _UpperCAmelCase     :  Tuple							      =    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)

             _UpperCAmelCase     :  List[str]							      =    None
             for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
                    _UpperCAmelCase      ,  _UpperCAmelCase     :  int							      =    cpu_offload_with_hook(A						,					A						,					prev_module_hook=A       )

             if self.safety_checker is not None:
                    _UpperCAmelCase      ,  _UpperCAmelCase     :  Any							      =    cpu_offload_with_hook(self.safety_checker						,					A						,					prev_module_hook=A       )

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




      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def      _A	(       self						:				Optional[int]       ):
             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						:				str						,					A						:				Union[str, List[str]]						,					A						:				Union[torch.FloatTensor, List[torch.FloatTensor]]						,					A						:				Union[torch.FloatTensor, List[torch.FloatTensor]]						,					A						:				Optional[Union[str, List[str]]] = None						,					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						,					):

             if isinstance(A						,					A       ):
                    _UpperCAmelCase     :  Dict							      =    1
             elif isinstance(A						,					A       ):
                    _UpperCAmelCase     :  Tuple							      =    len(A       )
             else:
                    raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(A       )}"""       )

             _UpperCAmelCase     :  Dict							      =    self._execution_device

             _UpperCAmelCase     :  Optional[int]							      =    batch_size * num_images_per_prompt
             _UpperCAmelCase     :  Optional[int]							      =    guidance_scale > 1.0

             _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase     :  Tuple							      =    self._encode_prompt(
                 A						,					A						,					A						,					A						,					A       )

             if isinstance(A						,					A       ):
                    _UpperCAmelCase     :  Optional[int]							      =    torch.cat(A						,					dim=0       )
             if isinstance(A						,					A       ):
                    _UpperCAmelCase     :  Tuple							      =    torch.cat(A						,					dim=0       )

             if do_classifier_free_guidance:
                    _UpperCAmelCase     :  Tuple							      =    image_embeds.repeat_interleave(A						,					dim=0       )
                    _UpperCAmelCase     :  int							      =    negative_image_embeds.repeat_interleave(A						,					dim=0       )

             _UpperCAmelCase     :  List[str]							      =    torch.cat([negative_image_embeds, image_embeds]						,					dim=0       ).to(
                 dtype=prompt_embeds.dtype						,					device=A       )

             self.scheduler.set_timesteps(A						,					device=A       )
             _UpperCAmelCase     :  int							      =    self.scheduler.timesteps

             _UpperCAmelCase     :  Tuple							      =    self.unet.config.in_channels

             _UpperCAmelCase      ,  _UpperCAmelCase     :  Union[str, Any]							      =    get_new_h_w(A						,					A						,					self.movq_scale_factor       )

             # create initial latent
             _UpperCAmelCase     :  Tuple							      =    self.prepare_latents(
                 (batch_size, num_channels_latents, height, width)						,					text_encoder_hidden_states.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
                    _UpperCAmelCase     :  Tuple							      =    torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents

                    _UpperCAmelCase     :  List[Any]							      =    {"text_embeds": prompt_embeds, "image_embeds": image_embeds}
                    _UpperCAmelCase     :  Optional[Any]							      =    self.unet(
                        sample=A						,					timestep=A						,					encoder_hidden_states=A						,					added_cond_kwargs=A						,					return_dict=A						,					)[0]

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

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

             if output_type == "pil":
                    _UpperCAmelCase     :  Optional[int]							      =    self.numpy_to_pil(A       )

             if not return_dict:
                    return (image,)

             return ImagePipelineOutput(images=A       )


'''simple docstring'''




import numpy as np
from matplotlib import pyplot as plt
from sklearn.datasets import load_iris
from sklearn.metrics import ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier

def 	UpperCamelCase_							(					_UpperCAmelCase  :      dict    )    ->    tuple:


       """simple docstring"""







       return (data["data"], data["target"])

def 	UpperCamelCase_							(					_UpperCAmelCase  :      np.ndarray			,	_UpperCAmelCase  :      np.ndarray    )    ->    XGBClassifier:


       """simple docstring"""







       _UpperCAmelCase     :  Any							      =    XGBClassifier()
       classifier.fit(_UpperCAmelCase			,	_UpperCAmelCase    )
       return classifier

def 	UpperCamelCase_							(					)    ->    None:


       """simple docstring"""







       _UpperCAmelCase     :  List[str]							      =    load_iris()
       _UpperCAmelCase      ,  _UpperCAmelCase     :  Dict							      =    data_handling(_UpperCAmelCase    )
       _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase      ,  _UpperCAmelCase     :  str							      =    train_test_split(
           _UpperCAmelCase			,	_UpperCAmelCase			,	test_size=0.2_5    )

       _UpperCAmelCase     :  Optional[Any]							      =    iris["target_names"]

       # Create an XGBoost Classifier from the training data
       _UpperCAmelCase     :  Tuple							      =    xgboost(_UpperCAmelCase			,	_UpperCAmelCase    )

       # Display the confusion matrix of the classifier with both training and test sets
       ConfusionMatrixDisplay.from_estimator(
           _UpperCAmelCase			,	_UpperCAmelCase			,	_UpperCAmelCase			,	display_labels=_UpperCAmelCase			,	cmap="Blues"			,	normalize="true"			,	)
       plt.title("Normalized Confusion Matrix - IRIS Dataset"    )
       plt.show()


if __name__ == "__main__":
  import doctest

  doctest.testmod(verbose=True)
  main()

