


import gc
import random
import unittest

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

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()







class 	lowerCAmelCase__			(							UpperCAmelCase__	,       unittest.TestCase):




     '''simple docstring'''
     __SCREAMING_SNAKE_CASE         =					KandinskyInpaintPipeline
     __SCREAMING_SNAKE_CASE         =					["prompt", "image_embeds", "negative_image_embeds", "image", "mask_image"]
     __SCREAMING_SNAKE_CASE         =					[
         "prompt",
         "negative_prompt",
         "image_embeds",
         "negative_image_embeds",
         "image",
         "mask_image",
     ]
     __SCREAMING_SNAKE_CASE         =					[
         "generator",
         "height",
         "width",
         "latents",
         "guidance_scale",
         "negative_prompt",
         "num_inference_steps",
         "return_dict",
         "guidance_scale",
         "num_images_per_prompt",
         "output_type",
         "return_dict",
     ]
     __SCREAMING_SNAKE_CASE         =					False


     @property
     def 					_lowerCamelCase					(		self)     ->							int:
            return 3_2


     @property
     def 					_lowerCamelCase					(		self)     ->							Tuple:
            return 3_2


     @property
     def 					_lowerCamelCase					(		self)     ->							Optional[int]:
            return self.time_input_dim


     @property
     def 					_lowerCamelCase					(		self)     ->							Union[str, Any]:
            return self.time_input_dim * 4


     @property
     def 					_lowerCamelCase					(		self)     ->							Optional[int]:
            return 1_0_0


     @property
     def 					_lowerCamelCase					(		self)     ->							Tuple:
            _A :			Any							       =					XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base")
            return tokenizer


     @property
     def 					_lowerCamelCase					(		self)     ->							Optional[Any]:
            torch.manual_seed(0)
            _A :			str							       =					MCLIPConfig(
                numDims=self.cross_attention_dim					,		transformerDimensions=self.text_embedder_hidden_size					,		hidden_size=self.text_embedder_hidden_size					,		intermediate_size=3_7					,		num_attention_heads=4					,		num_hidden_layers=5					,		vocab_size=1_0_0_5					,		)

            _A :			str							       =					MultilingualCLIP(__lowercase)
            _A :			str							       =					text_encoder.eval()

            return text_encoder


     @property
     def 					_lowerCamelCase					(		self)     ->							Any:
            torch.manual_seed(0)

            _A :			Optional[Any]							       =					{
                "in_channels": 9,
                # Out channels is double in channels because predicts mean and variance
                "out_channels": 8,
                "addition_embed_type": "text_image",
                "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
                "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
                "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
                "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
                "layers_per_block": 1,
                "encoder_hid_dim": self.text_embedder_hidden_size,
                "encoder_hid_dim_type": "text_image_proj",
                "cross_attention_dim": self.cross_attention_dim,
                "attention_head_dim": 4,
                "resnet_time_scale_shift": "scale_shift",
                "class_embed_type": None,
            }

            _A :			Optional[int]							       =					UNetaDConditionModel(**__lowercase)
            return model


     @property
     def 					_lowerCamelCase					(		self)     ->							int:
            return {
                "block_out_channels": [3_2, 6_4],
                "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
                "in_channels": 3,
                "latent_channels": 4,
                "layers_per_block": 1,
                "norm_num_groups": 8,
                "norm_type": "spatial",
                "num_vq_embeddings": 1_2,
                "out_channels": 3,
                "up_block_types": [
                    "AttnUpDecoderBlock2D",
                    "UpDecoderBlock2D",
                ],
                "vq_embed_dim": 4,
            }


     @property
     def 					_lowerCamelCase					(		self)     ->							List[str]:
            torch.manual_seed(0)
            _A :			Dict							       =					VQModel(**self.dummy_movq_kwargs)
            return model


     def 					_lowerCamelCase					(		self)     ->							Dict:
            _A :			Any							       =					self.dummy_text_encoder
            _A :			Tuple							       =					self.dummy_tokenizer
            _A :			Optional[Any]							       =					self.dummy_unet
            _A :			List[str]							       =					self.dummy_movq

            _A :			int							       =					DDIMScheduler(
                num_train_timesteps=1_0_0_0					,		beta_schedule="linear"					,		beta_start=0.0_0_0_8_5					,		beta_end=0.0_1_2					,		clip_sample=__lowercase					,		set_alpha_to_one=__lowercase					,		steps_offset=1					,		prediction_type="epsilon"					,		thresholding=__lowercase					,		)

            _A :			Union[str, Any]							       =					{
                "text_encoder": text_encoder,
                "tokenizer": tokenizer,
                "unet": unet,
                "scheduler": scheduler,
                "movq": movq,
            }

            return components


     def 					_lowerCamelCase					(		self					,		__lowerCamelCase					,		__lowerCamelCase=0)     ->							int:
            _A :			Union[str, Any]							       =					floats_tensor((1, self.cross_attention_dim)					,		rng=random.Random(__lowercase)).to(__lowercase)
            _A :			Optional[int]							       =					floats_tensor((1, self.cross_attention_dim)					,		rng=random.Random(seed + 1)).to(__lowercase)
            # create init_image
            _A :			Optional[Any]							       =					floats_tensor((1, 3, 6_4, 6_4)					,		rng=random.Random(__lowercase)).to(__lowercase)
            _A :			List[Any]							       =					image.cpu().permute(0					,		2					,		3					,		1)[0]
            _A :			int							       =					Image.fromarray(np.uinta(__lowercase)).convert("RGB").resize((2_5_6, 2_5_6))
            # create mask
            _A :			Optional[int]							       =					np.ones((6_4, 6_4)					,		dtype=np.floataa)
            _A :			Tuple							       =					0

            if str(__lowercase).startswith("mps"):
                   _A :			List[str]							       =					torch.manual_seed(__lowercase)
            else:
                   _A :			Tuple							       =					torch.Generator(device=__lowercase).manual_seed(__lowercase)
            _A :			Dict							       =					{
                "prompt": "horse",
                "image": init_image,
                "mask_image": mask,
                "image_embeds": image_embeds,
                "negative_image_embeds": negative_image_embeds,
                "generator": generator,
                "height": 6_4,
                "width": 6_4,
                "num_inference_steps": 2,
                "guidance_scale": 4.0,
                "output_type": "np",
            }
            return inputs


     def 					_lowerCamelCase					(		self)     ->							Tuple:
            _A :			Union[str, Any]							       =					"cpu"

            _A :			str							       =					self.get_dummy_components()

            _A :			str							       =					self.pipeline_class(**__lowercase)
            _A :			Dict							       =					pipe.to(__lowercase)

            pipe.set_progress_bar_config(disable=__lowercase)

            _A :			List[Any]							       =					pipe(**self.get_dummy_inputs(__lowercase))
            _A :			Optional[Any]							       =					output.images

            _A :			List[str]							       =					pipe(
                **self.get_dummy_inputs(__lowercase)					,		return_dict=__lowercase					,		)[0]

            _A :			List[str]							       =					image[0, -3:, -3:, -1]
            _A :			str							       =					image_from_tuple[0, -3:, -3:, -1]

            print(F"image.shape {image.shape}")

            assert image.shape == (1, 6_4, 6_4, 3)

            _A :			Tuple							       =					np.array(
                [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6])

            assert (
                np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
            ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}"
            assert (
                np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
            ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"


     def 					_lowerCamelCase					(		self)     ->							str:
            super().test_inference_batch_single_identical(expected_max_diff=3e-3)







@slow
@require_torch_gpu
class 	lowerCAmelCase__			(							unittest.TestCase):




     '''simple docstring'''


     def 					_lowerCamelCase					(		self)     ->							List[Any]:
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()


     def 					_lowerCamelCase					(		self)     ->							Dict:
            _A :			Any							       =					load_numpy(
                "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                "/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy")

            _A :			Union[str, Any]							       =					load_image(
                "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png")
            _A :			Optional[Any]							       =					np.ones((7_6_8, 7_6_8)					,		dtype=np.floataa)
            _A :			Optional[int]							       =					0

            _A :			int							       =					"a hat"

            _A :			List[Any]							       =					KandinskyPriorPipeline.from_pretrained(
                "kandinsky-community/kandinsky-2-1-prior"					,		torch_dtype=torch.floataa)
            pipe_prior.to(__lowercase)

            _A :			List[Any]							       =					KandinskyInpaintPipeline.from_pretrained(
                "kandinsky-community/kandinsky-2-1-inpaint"					,		torch_dtype=torch.floataa)
            _A :			Tuple							       =					pipeline.to(__lowercase)
            pipeline.set_progress_bar_config(disable=__lowercase)

            _A :			Optional[Any]							       =					torch.Generator(device="cpu").manual_seed(0)
            _A       ,     _A :			Dict							       =					pipe_prior(
                __lowercase					,		generator=__lowercase					,		num_inference_steps=5					,		negative_prompt=""					,		).to_tuple()

            _A :			Optional[Any]							       =					pipeline(
                __lowercase					,		image=__lowercase					,		mask_image=__lowercase					,		image_embeds=__lowercase					,		negative_image_embeds=__lowercase					,		generator=__lowercase					,		num_inference_steps=1_0_0					,		height=7_6_8					,		width=7_6_8					,		output_type="np"					,		)

            _A :			Any							       =					output.images[0]

            assert image.shape == (7_6_8, 7_6_8, 3)

            assert_mean_pixel_difference(__lowercase					,		__lowercase)






import json
import os
import subprocess
import unittest
from ast import literal_eval

import pytest
from parameterized import parameterized, parameterized_class

from . import is_sagemaker_available


if is_sagemaker_available():
		from sagemaker import Session, TrainingJobAnalytics
		from sagemaker.huggingface import HuggingFace
@pytest.mark.skipif(
    literal_eval(os.getenv('''TEST_SAGEMAKER'''			,  '''False'''     )     ) is not True			,  reason='''Skipping test because should only be run when releasing minor transformers version'''			,  )
@pytest.mark.usefixtures('''sm_env'''     )
@parameterized_class(
    [
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_glue.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6},
        },
        {
            '''framework''': '''pytorch''',
            '''script''': '''run_ddp.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.7, '''eval_loss''': 0.6},
        },
        {
            '''framework''': '''tensorflow''',
            '''script''': '''run_tf_dist.py''',
            '''model_name_or_path''': '''distilbert-base-cased''',
            '''instance_type''': '''ml.p3.16xlarge''',
            '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.6, '''eval_loss''': 0.7},
        },
    ]     )
class 						UpperCAmelCase  (							unittest.TestCase     ):







						'''simple docstring'''





						def 			snake_case__		(		self				:	Optional[Any]		):






							"""simple docstring"""






							if self.framework == "pytorch":
								subprocess.run(
								    f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split()			,      encoding="utf-8"			,      check=__lowercase			,      )
							assert hasattr(self			,      "env"		)






						def 			snake_case__		(		self				:	Dict			,      __lowercase				:	Optional[Any]		):






							"""simple docstring"""






							snake_case_						       =	f"{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}"
							# distributed data settings
							snake_case_						       =	{"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None

							# creates estimator
							return HuggingFace(
							    entry_point=self.script			,      source_dir=self.env.test_path			,      role=self.env.role			,      image_uri=self.env.image_uri			,      base_job_name=__lowercase			,      instance_count=__lowercase			,      instance_type=self.instance_type			,      debugger_hook_config=__lowercase			,      hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path}			,      metric_definitions=self.env.metric_definitions			,      distribution=__lowercase			,      py_version="py36"			,      )






						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	Tuple		):






							"""simple docstring"""






							TrainingJobAnalytics(__lowercase		).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv"		)






						@parameterized.expand([(2,)]		)
						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							snake_case_						       =	self.create_estimator(__lowercase		)

							# run training
							estimator.fit()

							# result dataframe
							snake_case_						       =	TrainingJobAnalytics(estimator.latest_training_job.name		).dataframe()

							# extract kpis
							snake_case_						       =	list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]		)
							snake_case_						       =	list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]		)
							# get train time from SageMaker job, this includes starting, preprocessing, stopping
							snake_case_						       =	(
							    Session().describe_training_job(estimator.latest_training_job.name		).get("TrainingTimeInSeconds"			,      99_99_99		)
							)

							# assert kpis
							assert train_runtime <= self.results["train_runtime"]
							assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy		)
							assert all(t <= self.results["eval_loss"] for t in eval_loss		)

							# dump tests result into json file to share in PR
							with open(f"{estimator.latest_training_job.name}.json"			,      "w"		) as outfile:
								json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}			,      __lowercase		)
