
"""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 __lowerCAmelCase				(					UpperCamelCase__     ,				unittest.TestCase      ):




   """simple docstring"""







   snake_case	      =				KandinskyVaaPriorPipeline
   snake_case	      =				["""prompt"""]
   snake_case	      =				["""prompt""", """negative_prompt"""]
   snake_case	      =				[
       """num_images_per_prompt""",
       """generator""",
       """num_inference_steps""",
       """latents""",
       """negative_prompt""",
       """guidance_scale""",
       """output_type""",
       """return_dict""",
   ]
   snake_case	      =				False




   @property
   def      lowerCamelCase__     (				self						:					Optional[int]	)      -> Dict:







        """simple docstring"""
        return 32




   @property
   def      lowerCamelCase__     (				self						:					Dict	)      -> Tuple:







        """simple docstring"""
        return 32




   @property
   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> List[Any]:







        """simple docstring"""
        return self.time_input_dim




   @property
   def      lowerCamelCase__     (				self						:					Dict	)      -> str:







        """simple docstring"""
        return self.time_input_dim * 4




   @property
   def      lowerCamelCase__     (				self						:					str	)      -> str:







        """simple docstring"""
        return 100




   @property
   def      lowerCamelCase__     (				self						:					str	)      -> Tuple:







        """simple docstring"""
        A_				 =						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)
        return tokenizer




   @property
   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> List[str]:







        """simple docstring"""
        torch.manual_seed(0	)
        A_				 =						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=37       ,   layer_norm_eps=1e-05       ,   num_attention_heads=4       ,   num_hidden_layers=5       ,   pad_token_id=1       ,   vocab_size=1_000       ,   )
        return CLIPTextModelWithProjection(_snake_case	)




   @property
   def      lowerCamelCase__     (				self						:					int	)      -> Dict:







        """simple docstring"""
        torch.manual_seed(0	)

        A_				 =						{
            "num_attention_heads": 2,
            "attention_head_dim": 12,
            "embedding_dim": self.text_embedder_hidden_size,
            "num_layers": 1,
        }

        A_				 =						PriorTransformer(**_snake_case	)
        # 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
        A_				 =						nn.Parameter(torch.ones(model.clip_std.shape	)	)
        return model




   @property
   def      lowerCamelCase__     (				self						:					str	)      -> List[str]:







        """simple docstring"""
        torch.manual_seed(0	)
        A_				 =						CLIPVisionConfig(
            hidden_size=self.text_embedder_hidden_size       ,   image_size=224       ,   projection_dim=self.text_embedder_hidden_size       ,   intermediate_size=37       ,   num_attention_heads=4       ,   num_channels=3       ,   num_hidden_layers=5       ,   patch_size=14       ,   )

        A_				 =						CLIPVisionModelWithProjection(_snake_case	)
        return model




   @property
   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> Optional[Any]:







        """simple docstring"""
        A_				 =						CLIPImageProcessor(
            crop_size=224       ,   do_center_crop=_snake_case       ,   do_normalize=_snake_case       ,   do_resize=_snake_case       ,   image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]       ,   image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]       ,   resample=3       ,   size=224       ,   )

        return image_processor




   def      lowerCamelCase__     (				self						:					str	)      -> List[Any]:







        """simple docstring"""
        A_				 =						self.dummy_prior
        A_				 =						self.dummy_image_encoder
        A_				 =						self.dummy_text_encoder
        A_				 =						self.dummy_tokenizer
        A_				 =						self.dummy_image_processor

        A_				 =						UnCLIPScheduler(
            variance_type="fixed_small_log"       ,   prediction_type="sample"       ,   num_train_timesteps=1_000       ,   clip_sample=_snake_case       ,   clip_sample_range=1_0.0       ,   )

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

        return components




   def      lowerCamelCase__     (				self						:					Optional[int]       ,   _snake_case						:					List[Any]       ,   _snake_case						:					str=0	)      -> Dict:







        """simple docstring"""
        if str(_snake_case	).startswith("mps"	):
             A_				 =						torch.manual_seed(_snake_case	)
        else:
             A_				 =						torch.Generator(device=_snake_case	).manual_seed(_snake_case	)
        A_				 =						{
            "prompt": "horse",
            "generator": generator,
            "guidance_scale": 4.0,
            "num_inference_steps": 2,
            "output_type": "np",
        }
        return inputs




   def      lowerCamelCase__     (				self						:					int	)      -> int:







        """simple docstring"""
        A_				 =						"cpu"

        A_				 =						self.get_dummy_components()

        A_				 =						self.pipeline_class(**_snake_case	)
        A_				 =						pipe.to(_snake_case	)

        pipe.set_progress_bar_config(disable=_snake_case	)

        A_				 =						pipe(**self.get_dummy_inputs(_snake_case	)	)
        A_				 =						output.image_embeds

        A_				 =						pipe(
            **self.get_dummy_inputs(_snake_case	)       ,   return_dict=_snake_case       ,   )[0]

        A_				 =						image[0, -10:]
        A_				 =						image_from_tuple[0, -10:]

        assert image.shape == (1, 32)

        A_				 =						np.array(
            [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6]	)

        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      lowerCamelCase__     (				self						:					int	)      -> Optional[Any]:







        """simple docstring"""
        A_				 =						torch_device == "cpu"
        A_				 =						True
        A_				 =						False

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






   @skip_mps
   def      lowerCamelCase__     (				self						:					Optional[int]	)      -> int:







        """simple docstring"""
        A_				 =						torch_device == "cpu"
        A_				 =						False

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






"""simple docstring"""





import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class __lowerCAmelCase				(					_lowercase     ,				unittest.TestCase      ):




			"""simple docstring"""







			snake_case	      =				TransfoXLTokenizer
			snake_case	      =				False
			snake_case	      =				False




			def      lowerCamelCase__     (				self						:					Optional[int]	)      -> Optional[int]:







								"""simple docstring"""
								super().setUp()

								A_				 =						[
								    "<unk>",
								    "[CLS]",
								    "[SEP]",
								    "want",
								    "unwanted",
								    "wa",
								    "un",
								    "running",
								    ",",
								    "low",
								    "l",
								]
								A_				 =						os.path.join(self.tmpdirname       ,   VOCAB_FILES_NAMES["vocab_file"]	)
								with open(self.vocab_file       ,   "w"       ,   encoding="utf-8"	) as vocab_writer:
													vocab_writer.write("".join([x + "\n" for x in vocab_tokens]	)	)




			def      lowerCamelCase__     (				self						:					str       ,   **_snake_case						:					Any	)      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						True
								return TransfoXLTokenizer.from_pretrained(self.tmpdirname       ,   **_snake_case	)




			def      lowerCamelCase__     (				self						:					int       ,   _snake_case						:					Optional[Any]	)      -> Any:







								"""simple docstring"""
								A_				 =						"<unk> UNwanted , running"
								A_				 =						"<unk> unwanted, running"
								return input_text, output_text




			def      lowerCamelCase__     (				self						:					Dict	)      -> int:







								"""simple docstring"""
								A_				 =						TransfoXLTokenizer(vocab_file=self.vocab_file       ,   lower_case=_snake_case	)

								A_				 =						tokenizer.tokenize("<unk> UNwanted , running"	)
								self.assertListEqual(_snake_case       ,   ["<unk>", "unwanted", ",", "running"]	)

								self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case	)       ,   [0, 4, 8, 7]	)




			def      lowerCamelCase__     (				self						:					List[str]	)      -> int:







								"""simple docstring"""
								A_				 =						TransfoXLTokenizer(lower_case=_snake_case	)

								self.assertListEqual(
								    tokenizer.tokenize(" \tHeLLo ! how  \n Are yoU ?  "	)       ,   ["hello", "!", "how", "are", "you", "?"]	)




			def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> str:







								"""simple docstring"""
								A_				 =						TransfoXLTokenizer(lower_case=_snake_case	)

								self.assertListEqual(
								    tokenizer.tokenize(" \tHeLLo ! how  \n Are yoU ?  "	)       ,   ["HeLLo", "!", "how", "Are", "yoU", "?"]	)




			def      lowerCamelCase__     (				self						:					Dict	)      -> Tuple:







								"""simple docstring"""
								A_				 =						TransfoXLTokenizer(lower_case=_snake_case	)
								A_				 =						"Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?"
								A_				 =						[
								    "Hello",
								    "(",
								    "bracket",
								    ")",
								    "and",
								    "side",
								    "@-@",
								    "scrolled",
								    "[",
								    "and",
								    "]",
								    "Henry",
								    "'s",
								    "$",
								    "5",
								    "@,@",
								    "000",
								    "with",
								    "3",
								    "@.@",
								    "34",
								    "m",
								    ".",
								    "What",
								    "'s",
								    "up",
								    "!",
								    "?",
								]

								self.assertListEqual(tokenizer.tokenize(_snake_case	)       ,   _snake_case	)

								self.assertEqual(tokenizer.convert_tokens_to_string(_snake_case	)       ,   _snake_case	)






			def      lowerCamelCase__     (				self						:					List[Any]	)      -> Optional[Any]:







								"""simple docstring"""
								A_				 =						self.get_tokenizer()
								A_				 =						len(_snake_case	)

								tokenizer.add_tokens(["new1", "new2"]	)
								tokenizer.move_added_token("new1"       ,   1	)

								# Check that moved token is not copied (duplicate)
								self.assertEqual(len(_snake_case	)       ,   original_len + 2	)
								# Check that token is moved to specified id
								self.assertEqual(tokenizer.encode("new1"	)       ,   [1]	)
								self.assertEqual(tokenizer.decode([1]	)       ,   "new1"	)




