


import unittest

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

from diffusers import KandinskyPriorPipeline, 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 							lowercase__(						snake_case_			,							unittest.TestCase			):






      '''simple docstring'''







      snake_case__       =					KandinskyPriorPipeline
      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    UpperCAmelCase							(		self)					->						List[Any]:







         """simple docstring"""







         return 32




      @property
      def    UpperCAmelCase							(		self)					->						Any:







         """simple docstring"""







         return 32




      @property
      def    UpperCAmelCase							(		self)					->						Optional[Any]:







         """simple docstring"""







         return self.time_input_dim




      @property
      def    UpperCAmelCase							(		self)					->						Tuple:







         """simple docstring"""







         return self.time_input_dim * 4




      @property
      def    UpperCAmelCase							(		self)					->						Dict:







         """simple docstring"""







         return 1_00




      @property
      def    UpperCAmelCase							(		self)					->						Any:







         """simple docstring"""







         UpperCamelCase__ :			Dict 						=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
         return tokenizer




      @property
      def    UpperCAmelCase							(		self)					->						int:







         """simple docstring"""







         torch.manual_seed(0)
         UpperCamelCase__ :			List[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=37   ,			layer_norm_eps=1E-05   ,			num_attention_heads=4   ,			num_hidden_layers=5   ,			pad_token_id=1   ,			vocab_size=10_00   ,			)
         return CLIPTextModelWithProjection(_A)




      @property
      def    UpperCAmelCase							(		self)					->						Any:







         """simple docstring"""







         torch.manual_seed(0)

         UpperCamelCase__ :			Any 						={
             'num_attention_heads': 2,
             'attention_head_dim': 12,
             'embedding_dim': self.text_embedder_hidden_size,
             'num_layers': 1,
         }

         UpperCamelCase__ :			Optional[Any] 						=PriorTransformer(**_A)
         # 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
         UpperCamelCase__ :			Union[str, Any] 						=nn.Parameter(torch.ones(model.clip_std.shape))
         return model




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







         """simple docstring"""







         torch.manual_seed(0)
         UpperCamelCase__ :			Optional[Any] 						=CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size   ,			image_size=2_24   ,			projection_dim=self.text_embedder_hidden_size   ,			intermediate_size=37   ,			num_attention_heads=4   ,			num_channels=3   ,			num_hidden_layers=5   ,			patch_size=14   ,			)

         UpperCamelCase__ :			Tuple 						=CLIPVisionModelWithProjection(_A)
         return model




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







         """simple docstring"""







         UpperCamelCase__ :			Optional[Any] 						=CLIPImageProcessor(
             crop_size=2_24   ,			do_center_crop=_A   ,			do_normalize=_A   ,			do_resize=_A   ,			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_24   ,			)

         return image_processor




      def    UpperCAmelCase							(		self)					->						int:







         """simple docstring"""







         UpperCamelCase__ :			Tuple 						=self.dummy_prior
         UpperCamelCase__ :			Optional[int] 						=self.dummy_image_encoder
         UpperCamelCase__ :			List[str] 						=self.dummy_text_encoder
         UpperCamelCase__ :			List[str] 						=self.dummy_tokenizer
         UpperCamelCase__ :			List[str] 						=self.dummy_image_processor

         UpperCamelCase__ :			int 						=UnCLIPScheduler(
             variance_type="fixed_small_log"   ,			prediction_type="sample"   ,			num_train_timesteps=10_00   ,			clip_sample=_A   ,			clip_sample_range=10.0   ,			)

         UpperCamelCase__ :			List[str] 						={
             'prior': prior,
             'image_encoder': image_encoder,
             'text_encoder': text_encoder,
             'tokenizer': tokenizer,
             'scheduler': scheduler,
             'image_processor': image_processor,
         }

         return components




      def    UpperCAmelCase							(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE=0)					->						List[str]:







         """simple docstring"""







         if str(_A).startswith("mps"):
            UpperCamelCase__ :			List[Any] 						=torch.manual_seed(_A)
         else:
            UpperCamelCase__ :			int 						=torch.Generator(device=_A).manual_seed(_A)
         UpperCamelCase__ :			Optional[int] 						={
             'prompt': 'horse',
             'generator': generator,
             'guidance_scale': 4.0,
             'num_inference_steps': 2,
             'output_type': 'np',
         }
         return inputs




      def    UpperCAmelCase							(		self)					->						str:







         """simple docstring"""







         UpperCamelCase__ :			Optional[Any] 						='cpu'

         UpperCamelCase__ :			Optional[Any] 						=self.get_dummy_components()

         UpperCamelCase__ :			Union[str, Any] 						=self.pipeline_class(**_A)
         UpperCamelCase__ :			str 						=pipe.to(_A)

         pipe.set_progress_bar_config(disable=_A)

         UpperCamelCase__ :			List[Any] 						=pipe(**self.get_dummy_inputs(_A))
         UpperCamelCase__ :			List[str] 						=output.image_embeds

         UpperCamelCase__ :			Optional[int] 						=pipe(
             **self.get_dummy_inputs(_A)   ,			return_dict=_A   ,			)[0]

         UpperCamelCase__ :			Tuple 						=image[0, -10:]
         UpperCamelCase__ :			Union[str, Any] 						=image_from_tuple[0, -10:]

         assert image.shape == (1, 32)

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







         """simple docstring"""







         UpperCamelCase__ :			Union[str, Any] 						=torch_device == 'cpu'
         UpperCamelCase__ :			Tuple 						=True
         UpperCamelCase__ :			str 						=False

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




      @skip_mps
      def    UpperCAmelCase							(		self)					->						Dict:







         """simple docstring"""







         UpperCamelCase__ :			List[str] 						=torch_device == 'cpu'
         UpperCamelCase__ :			Tuple 						=False

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








import os
import shutil
import unittest
from unittest.mock import patch

from transformers.testing_utils import CaptureStd, is_pt_tf_cross_test, require_torch
class SCREAMING_SNAKE_CASE_    (       unittest.TestCase       ):






						@patch('sys.argv'		, ['fakeprogrampath', 'env']						)
						def UpperCAmelCase_					(   self   :   Tuple						)				->     Dict:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							with CaptureStd() as cs:
								transformers.commands.transformers_cli.main()
							self.assertIn('Python version'		, cs.out						)
							self.assertIn('Platform'		, cs.out						)
							self.assertIn('Using distributed or parallel set-up in script?'		, cs.out						)






						@is_pt_tf_cross_test
						@patch(
						    'sys.argv'		, ['fakeprogrampath', 'pt-to-tf', '--model-name', 'hf-internal-testing/tiny-random-gptj', '--no-pr']						)
						def UpperCAmelCase_					(   self   :   Union[str, Any]						)				->     Optional[Any]:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							shutil.rmtree('/tmp/hf-internal-testing/tiny-random-gptj'		, ignore_errors=_A						)  # cleans potential past runs
							transformers.commands.transformers_cli.main()

							# The original repo has no TF weights -- if they exist, they were created by the CLI
							self.assertTrue(os.path.exists('/tmp/hf-internal-testing/tiny-random-gptj/tf_model.h5'						)						)






						@require_torch
						@patch('sys.argv'		, ['fakeprogrampath', 'download', 'hf-internal-testing/tiny-random-gptj', '--cache-dir', '/tmp']						)
						def UpperCAmelCase_					(   self   :   List[Any]						)				->     str:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							# # remove any previously downloaded model to start clean
							shutil.rmtree('/tmp/models--hf-internal-testing--tiny-random-gptj'		, ignore_errors=_A						)

							# run the command
							transformers.commands.transformers_cli.main()

							# check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--tiny-random-gptj
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/blobs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/refs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--tiny-random-gptj/snapshots'						)						)






						@require_torch
						@patch(
						    'sys.argv'		, [
						        'fakeprogrampath',
						        'download',
						        'hf-internal-testing/test_dynamic_model_with_tokenizer',
						        '--trust-remote-code',
						        '--cache-dir',
						        '/tmp',
						    ]		, )
						def UpperCAmelCase_					(   self   :   Optional[Any]						)				->     str:







							"""simple docstring"""


							import transformers.commands.transformers_cli

							# # remove any previously downloaded model to start clean
							shutil.rmtree('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer'		, ignore_errors=_A						)

							# run the command
							transformers.commands.transformers_cli.main()

							# check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/blobs'						)						)
							self.assertTrue(os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/refs'						)						)
							self.assertTrue(
							    os.path.exists('/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/snapshots'						)						)

