


'''simple docstring'''






import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
							import tensorflow as tf
class 						__UpperCamelCase	(						enum.Enum							):
							lowercase			:		str   		=  0
							lowercase			:		Optional[Any]   		=  1
							lowercase			:		Any   		=  2





@add_end_docstrings(lowercase__							)
class 						__UpperCamelCase	(						lowercase__							):
							lowercase			:		Any   		=  '\n    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The\n    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western\n    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision\n    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an\n    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of\n    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,\n    begging for his blessing. <eod> </s> <eos>\n    '





							def __init__(  self		:Optional[Any]  ,*_UpperCamelCase		:List[Any]  ,**_UpperCamelCase		:List[str]			):
									super().__init__(*_UpperCamelCase  ,**_UpperCamelCase			)
									self.check_model_type(
									    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING			)
									if "prefix" not in self._preprocess_params:
											# This is very specific. The logic is quite complex and needs to be done
											# as a "default".
											# It also defines both some preprocess_kwargs and generate_kwargs
											# which is why we cannot put them in their respective methods.
											snake_case_		:							Any			       =						None
											if self.model.config.prefix is not None:
													snake_case_		:							Optional[int]			       =						self.model.config.prefix
											if prefix is None and self.model.__class__.__name__ in [
											    "XLNetLMHeadModel",
											    "TransfoXLLMHeadModel",
											    "TFXLNetLMHeadModel",
											    "TFTransfoXLLMHeadModel",
											]:
													# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
													snake_case_		:							int			       =						self.XL_PREFIX
											if prefix is not None:
													# Recalculate some generate_kwargs linked to prefix.
													snake_case_       ,      snake_case_       ,      snake_case_		:							List[str]			       =						self._sanitize_parameters(prefix=_UpperCamelCase  ,**self._forward_params			)
													snake_case_		:							int			       =						{**self._preprocess_params, **preprocess_params}
													snake_case_		:							Tuple			       =						{**self._forward_params, **forward_params}





							def 		a__   (  self		:Tuple  ,_UpperCamelCase		:Union[str, Any]=None  ,_UpperCamelCase		:List[str]=None  ,_UpperCamelCase		:List[Any]=None  ,_UpperCamelCase		:int=None  ,_UpperCamelCase		:Dict=None  ,_UpperCamelCase		:Dict=None  ,_UpperCamelCase		:Dict=None  ,_UpperCamelCase		:Union[str, Any]=None  ,**_UpperCamelCase		:List[Any]  ,):
									snake_case_		:							List[Any]			       =						{}
									if prefix is not None:
											snake_case_		:							str			       =						prefix
									if prefix:
											snake_case_		:							List[Any]			       =						self.tokenizer(
											    _UpperCamelCase  ,padding=_UpperCamelCase  ,add_special_tokens=_UpperCamelCase  ,return_tensors=self.framework			)
											snake_case_		:							List[str]			       =						prefix_inputs["""input_ids"""].shape[-1]

									if handle_long_generation is not None:
											if handle_long_generation not in {"hole"}:
													raise ValueError(
													    F'''{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'''
													    """ [None, 'hole']"""			)
											snake_case_		:							Optional[Any]			       =						handle_long_generation

									preprocess_params.update(_UpperCamelCase			)
									snake_case_		:							Optional[int]			       =						generate_kwargs

									snake_case_		:							List[Any]			       =						{}
									if return_full_text is not None and return_type is None:
											if return_text is not None:
													raise ValueError("""`return_text` is mutually exclusive with `return_full_text`"""			)
											if return_tensors is not None:
													raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`"""			)
											snake_case_		:							Optional[int]			       =						ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
									if return_tensors is not None and return_type is None:
											if return_text is not None:
													raise ValueError("""`return_text` is mutually exclusive with `return_tensors`"""			)
											snake_case_		:							Optional[Any]			       =						ReturnType.TENSORS
									if return_type is not None:
											snake_case_		:							Tuple			       =						return_type
									if clean_up_tokenization_spaces is not None:
											snake_case_		:							Tuple			       =						clean_up_tokenization_spaces

									if stop_sequence is not None:
											snake_case_		:							Union[str, Any]			       =						self.tokenizer.encode(_UpperCamelCase  ,add_special_tokens=_UpperCamelCase			)
											if len(_UpperCamelCase			) > 1:
													warnings.warn(
													    """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
													    """ the stop sequence will be used as the stop sequence string in the interim."""			)
											snake_case_		:							Optional[int]			       =						stop_sequence_ids[0]

									return preprocess_params, forward_params, postprocess_params





							def 		a__   (  self		:Optional[int]  ,*_UpperCamelCase		:Optional[int]  ,**_UpperCamelCase		:Dict			):
									# Parse arguments
									if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
											kwargs.update({"""add_space_before_punct_symbol""": True}			)

									return super()._parse_and_tokenize(*_UpperCamelCase  ,**_UpperCamelCase			)





							def __call__(  self		:Optional[int]  ,_UpperCamelCase		:Dict  ,**_UpperCamelCase		:Optional[Any]			):
									return super().__call__(_UpperCamelCase  ,**_UpperCamelCase			)





							def 		a__   (  self		:Union[str, Any]  ,_UpperCamelCase		:List[Any]  ,_UpperCamelCase		:Optional[int]=""  ,_UpperCamelCase		:Optional[Any]=None  ,**_UpperCamelCase		:Union[str, Any]			):
									snake_case_		:							int			       =						self.tokenizer(
									    prefix + prompt_text  ,padding=_UpperCamelCase  ,add_special_tokens=_UpperCamelCase  ,return_tensors=self.framework			)
									snake_case_		:							List[str]			       =						prompt_text

									if handle_long_generation == "hole":
											snake_case_		:							List[Any]			       =						inputs["""input_ids"""].shape[-1]
											if "max_new_tokens" in generate_kwargs:
													snake_case_		:							List[Any]			       =						generate_kwargs["""max_new_tokens"""]
											else:
													snake_case_		:							List[Any]			       =						generate_kwargs.get("""max_length"""  ,self.model.config.max_length			) - cur_len
													if new_tokens < 0:
															raise ValueError("""We cannot infer how many new tokens are expected"""			)
											if cur_len + new_tokens > self.tokenizer.model_max_length:
													snake_case_		:							str			       =						self.tokenizer.model_max_length - new_tokens
													if keep_length <= 0:
															raise ValueError(
															    """We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
															    """ models max length"""			)

													snake_case_		:							Optional[int]			       =						inputs["""input_ids"""][:, -keep_length:]
													if "attention_mask" in inputs:
															snake_case_		:							List[Any]			       =						inputs["""attention_mask"""][:, -keep_length:]

									return inputs





							def 		a__   (  self		:Any  ,_UpperCamelCase		:str  ,**_UpperCamelCase		:List[Any]			):
									snake_case_		:							List[Any]			       =						model_inputs["""input_ids"""]
									snake_case_		:							List[str]			       =						model_inputs.get("""attention_mask"""  ,_UpperCamelCase			)
									# Allow empty prompts
									if input_ids.shape[1] == 0:
											snake_case_		:							List[str]			       =						None
											snake_case_		:							Union[str, Any]			       =						None
											snake_case_		:							Union[str, Any]			       =						1
									else:
											snake_case_		:							Dict			       =						input_ids.shape[0]
									snake_case_		:							int			       =						model_inputs.pop("""prompt_text"""			)

									# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
									# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
									snake_case_		:							int			       =						generate_kwargs.pop("""prefix_length"""  ,0			)
									if prefix_length > 0:
											snake_case_		:							Union[str, Any]			       =						"""max_new_tokens""" in generate_kwargs or (
											    """generation_config""" in generate_kwargs
											    and generate_kwargs["""generation_config"""].max_new_tokens is not None
											)
											if not has_max_new_tokens:
													snake_case_		:							Optional[Any]			       =						generate_kwargs.get("""max_length"""			) or self.model.config.max_length
													generate_kwargs["max_length"] += prefix_length
											snake_case_		:							str			       =						"""min_new_tokens""" in generate_kwargs or (
											    """generation_config""" in generate_kwargs
											    and generate_kwargs["""generation_config"""].min_new_tokens is not None
											)
											if not has_min_new_tokens and "min_length" in generate_kwargs:
													generate_kwargs["min_length"] += prefix_length

        # BS x SL
									snake_case_		:							Optional[int]			       =						self.model.generate(input_ids=_UpperCamelCase  ,attention_mask=_UpperCamelCase  ,**_UpperCamelCase			)
									snake_case_		:							Optional[Any]			       =						generated_sequence.shape[0]
									if self.framework == "pt":
											snake_case_		:							Union[str, Any]			       =						generated_sequence.reshape(_UpperCamelCase  ,out_b // in_b  ,*generated_sequence.shape[1:]			)
									elif self.framework == "tf":
											snake_case_		:							Union[str, Any]			       =						tf.reshape(_UpperCamelCase  ,(in_b, out_b // in_b, *generated_sequence.shape[1:])			)
									return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





							def 		a__   (  self		:Optional[Any]  ,_UpperCamelCase		:Dict  ,_UpperCamelCase		:str=ReturnType.FULL_TEXT  ,_UpperCamelCase		:List[Any]=True			):
									snake_case_		:							Optional[Any]			       =						model_outputs["""generated_sequence"""][0]
									snake_case_		:							Any			       =						model_outputs["""input_ids"""]
									snake_case_		:							int			       =						model_outputs["""prompt_text"""]
									snake_case_		:							Union[str, Any]			       =						generated_sequence.numpy().tolist()
									snake_case_		:							Union[str, Any]			       =						[]
									for sequence in generated_sequence:
											if return_type == ReturnType.TENSORS:
													snake_case_		:							List[str]			       =						{"""generated_token_ids""": sequence}
											elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
													# Decode text
													snake_case_		:							Any			       =						self.tokenizer.decode(
													    _UpperCamelCase  ,skip_special_tokens=_UpperCamelCase  ,clean_up_tokenization_spaces=_UpperCamelCase  ,)

													# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
													if input_ids is None:
															snake_case_		:							Dict			       =						0
													else:
															snake_case_		:							Optional[Any]			       =						len(
															    self.tokenizer.decode(
															        input_ids[0]  ,skip_special_tokens=_UpperCamelCase  ,clean_up_tokenization_spaces=_UpperCamelCase  ,)			)

													if return_type == ReturnType.FULL_TEXT:
															snake_case_		:							List[str]			       =						prompt_text + text[prompt_length:]
													else:
															snake_case_		:							str			       =						text[prompt_length:]

													snake_case_		:							int			       =						{"""generated_text""": all_text}
											records.append(_UpperCamelCase			)

									return records



'''simple docstring'''






import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 						__UpperCamelCase	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		List[str]   		=  KandinskyVaaPriorPipeline
							lowercase			:		Optional[Any]   		=  ['prompt']
							lowercase			:		Dict   		=  ['prompt', 'negative_prompt']
							lowercase			:		Dict   		=  [
							    'num_images_per_prompt',
							    'generator',
							    'num_inference_steps',
							    'latents',
							    'negative_prompt',
							    'guidance_scale',
							    'output_type',
							    'return_dict',
							]
							lowercase			:		int   		=  False





							@property
							def 		a__   (  self		:int			):
									return 3_2





							@property
							def 		a__   (  self		:Any			):
									return 3_2





							@property
							def 		a__   (  self		:Union[str, Any]			):
									return self.time_input_dim





							@property
							def 		a__   (  self		:int			):
									return self.time_input_dim * 4





							@property
							def 		a__   (  self		:Dict			):
									return 1_0_0





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							List[Any]			       =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)
									return tokenizer





							@property
							def 		a__   (  self		:int			):
									torch.manual_seed(0			)
									snake_case_		:							Optional[Any]			       =						CLIPTextConfig(
									    bos_token_id=0  ,eos_token_id=2  ,hidden_size=self.text_embedder_hidden_size  ,projection_dim=self.text_embedder_hidden_size  ,intermediate_size=3_7  ,layer_norm_eps=1E-0_5  ,num_attention_heads=4  ,num_hidden_layers=5  ,pad_token_id=1  ,vocab_size=1_0_0_0  ,)
									return CLIPTextModelWithProjection(_UpperCamelCase			)





							@property
							def 		a__   (  self		:Dict			):
									torch.manual_seed(0			)

									snake_case_		:							Tuple			       =						{
									    """num_attention_heads""": 2,
									    """attention_head_dim""": 1_2,
									    """embedding_dim""": self.text_embedder_hidden_size,
									    """num_layers""": 1,
									}

									snake_case_		:							int			       =						PriorTransformer(**_UpperCamelCase			)
									# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
									snake_case_		:							Any			       =						nn.Parameter(torch.ones(model.clip_std.shape			)			)
									return model





							@property
							def 		a__   (  self		:Optional[int]			):
									torch.manual_seed(0			)
									snake_case_		:							Any			       =						CLIPVisionConfig(
									    hidden_size=self.text_embedder_hidden_size  ,image_size=2_2_4  ,projection_dim=self.text_embedder_hidden_size  ,intermediate_size=3_7  ,num_attention_heads=4  ,num_channels=3  ,num_hidden_layers=5  ,patch_size=1_4  ,)

									snake_case_		:							Optional[Any]			       =						CLIPVisionModelWithProjection(_UpperCamelCase			)
									return model





							@property
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						CLIPImageProcessor(
									    crop_size=2_2_4  ,do_center_crop=_UpperCamelCase  ,do_normalize=_UpperCamelCase  ,do_resize=_UpperCamelCase  ,image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]  ,image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]  ,resample=3  ,size=2_2_4  ,)

									return image_processor





							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Tuple			       =						self.dummy_prior
									snake_case_		:							Any			       =						self.dummy_image_encoder
									snake_case_		:							Optional[int]			       =						self.dummy_text_encoder
									snake_case_		:							Any			       =						self.dummy_tokenizer
									snake_case_		:							Union[str, Any]			       =						self.dummy_image_processor

									snake_case_		:							Tuple			       =						UnCLIPScheduler(
									    variance_type="""fixed_small_log"""  ,prediction_type="""sample"""  ,num_train_timesteps=1_0_0_0  ,clip_sample=_UpperCamelCase  ,clip_sample_range=10.0  ,)

									snake_case_		:							Tuple			       =						{
									    """prior""": prior,
									    """image_encoder""": image_encoder,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """scheduler""": scheduler,
									    """image_processor""": image_processor,
									}

									return components





							def 		a__   (  self		:Dict  ,_UpperCamelCase		:str  ,_UpperCamelCase		:Union[str, Any]=0			):
									if str(_UpperCamelCase			).startswith("""mps"""			):
											snake_case_		:							Optional[int]			       =						torch.manual_seed(_UpperCamelCase			)
									else:
											snake_case_		:							int			       =						torch.Generator(device=_UpperCamelCase			).manual_seed(_UpperCamelCase			)
									snake_case_		:							Dict			       =						{
									    """prompt""": """horse""",
									    """generator""": generator,
									    """guidance_scale""": 4.0,
									    """num_inference_steps""": 2,
									    """output_type""": """np""",
									}
									return inputs





							def 		a__   (  self		:int			):
									snake_case_		:							Union[str, Any]			       =						"""cpu"""

									snake_case_		:							int			       =						self.get_dummy_components()

									snake_case_		:							int			       =						self.pipeline_class(**_UpperCamelCase			)
									snake_case_		:							Union[str, Any]			       =						pipe.to(_UpperCamelCase			)

									pipe.set_progress_bar_config(disable=_UpperCamelCase			)

									snake_case_		:							Any			       =						pipe(**self.get_dummy_inputs(_UpperCamelCase			)			)
									snake_case_		:							List[Any]			       =						output.image_embeds

									snake_case_		:							List[Any]			       =						pipe(
									    **self.get_dummy_inputs(_UpperCamelCase			)  ,return_dict=_UpperCamelCase  ,)[0]

									snake_case_		:							Dict			       =						image[0, -1_0:]
									snake_case_		:							Optional[Any]			       =						image_from_tuple[0, -1_0:]

									assert image.shape == (1, 3_2)

									snake_case_		:							Optional[int]			       =						np.array(
									    [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]			)

									assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-2
									assert np.abs(image_from_tuple_slice.flatten() - expected_slice			).max() < 1E-2





							@skip_mps
							def 		a__   (  self		:List[Any]			):
									snake_case_		:							Any			       =						torch_device == """cpu"""
									snake_case_		:							Any			       =						True
									snake_case_		:							Dict			       =						False

									self._test_inference_batch_single_identical(
									    test_max_difference=_UpperCamelCase  ,relax_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)





							@skip_mps
							def 		a__   (  self		:str			):
									snake_case_		:							str			       =						torch_device == """cpu"""
									snake_case_		:							List[str]			       =						False

									self._test_attention_slicing_forward_pass(
									    test_max_difference=_UpperCamelCase  ,test_mean_pixel_difference=_UpperCamelCase  ,)