



import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import numpy as np
import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForMaskedImageModeling,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
snake_case__					:     Union[str, Any]    		=   logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""")

snake_case__					:     Tuple    		=   list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys())
snake_case__					:     str    		=   tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class   _A   :


						'''simple docstring'''





						_snake_case			:     Optional[str]      							=      field(
						    default="""cifar10"""  ,						metadata={"""help""": """Name of a dataset from the datasets package"""}	)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """The column name of the images in the files. If not set, will try to use 'image' or 'img'."""}  ,						)
						_snake_case			:     Optional[str]      							=      field(default=_UpperCAmelCase  ,						metadata={"""help""": """A folder containing the training data."""}	)
						_snake_case			:     Optional[str]      							=      field(default=_UpperCAmelCase  ,						metadata={"""help""": """A folder containing the validation data."""}	)
						_snake_case			:     Optional[float]      							=      field(
						    default=0.1_5  ,						metadata={"""help""": """Percent to split off of train for validation."""}	)
						_snake_case			:     int      							=      field(default=32  ,						metadata={"""help""": """The size of the square patches to use for masking."""}	)
						_snake_case			:     float      							=      field(
						    default=0.6  ,						metadata={"""help""": """Percentage of patches to mask."""}  ,						)
						_snake_case			:     Optional[int]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of training examples to this """
						            """value if set."""
						        )
						    }  ,						)
						_snake_case			:     Optional[int]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
						            """value if set."""
						        )
						    }  ,						)



						def     _snake_case	(	self	:							List[str]	):






							'''simple docstring'''



							__lowercase		       =			{}
							if self.train_dir is not None:
								__lowercase		       =			self.train_dir
							if self.validation_dir is not None:
								__lowercase		       =			self.validation_dir
							__lowercase		       =			data_files if data_files else None

@dataclass
class   _A   :


						'''simple docstring'''





						_snake_case			:     str      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a """
						            """checkpoint identifier on the hub. """
						            """Don't set if you want to train a model from scratch."""
						        )
						    }  ,						)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """If training from scratch, pass a model type from the list: """ + """, """.join(_UpperCAmelCase	)}  ,						)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}	)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """Override some existing default config settings when a model is trained from scratch. Example: """
						            """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"""
						        )
						    }  ,						)
						_snake_case			:     Optional[str]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """Where do you want to store (cache) the pretrained models/datasets downloaded from the hub"""}  ,						)
						_snake_case			:     str      							=      field(
						    default="""main"""  ,						metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}  ,						)
						_snake_case			:     str      							=      field(default=_UpperCAmelCase  ,						metadata={"""help""": """Name or path of preprocessor config."""}	)
						_snake_case			:     bool      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
						            """with private models)."""
						        )
						    }  ,						)
						_snake_case			:     Optional[int]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """The size (resolution) of each image. If not specified, will use `image_size` of the configuration."""
						        )
						    }  ,						)
						_snake_case			:     Optional[int]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={
						        """help""": (
						            """The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration."""
						        )
						    }  ,						)
						_snake_case			:     Optional[int]      							=      field(
						    default=_UpperCAmelCase  ,						metadata={"""help""": """Stride to use for the encoder."""}  ,						)

class   _A   :


						'''simple docstring'''





						def __init__(	self	:							Any							,      lowerCamelCase	:							Dict=192							,      lowerCamelCase	:							Union[str, Any]=32							,      lowerCamelCase	:							List[str]=4							,      lowerCamelCase	:							Union[str, Any]=0.6	):






							'''simple docstring'''



							__lowercase		       =			input_size
							__lowercase		       =			mask_patch_size
							__lowercase		       =			model_patch_size
							__lowercase		       =			mask_ratio

							if self.input_size % self.mask_patch_size != 0:
								raise ValueError("Input size must be divisible by mask patch size"	)
							if self.mask_patch_size % self.model_patch_size != 0:
								raise ValueError("Mask patch size must be divisible by model patch size"	)

							__lowercase		       =			self.input_size // self.mask_patch_size
							__lowercase		       =			self.mask_patch_size // self.model_patch_size

							__lowercase		       =			self.rand_size**2
							__lowercase		       =			int(np.ceil(self.token_count * self.mask_ratio	)	)



						def __call__(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			np.random.permutation(self.token_count	)[: self.mask_count]
							__lowercase		       =			np.zeros(self.token_count							,      dtype=lowercase__	)
							__lowercase		       =			1

							__lowercase		       =			mask.reshape((self.rand_size, self.rand_size)	)
							__lowercase		       =			mask.repeat(self.scale							,      axis=0	).repeat(self.scale							,      axis=1	)

							return torch.tensor(mask.flatten()	)



def    snake_case_				(    _SCREAMING_SNAKE_CASE   )     ->   Optional[int]:
	__lowercase		       =			torch.stack([example["pixel_values"] for example in examples]   )
	__lowercase		       =			torch.stack([example["mask"] for example in examples]   )
	return {"pixel_values": pixel_values, "bool_masked_pos": mask}



def    snake_case_				(    )     ->   Dict:
	__lowercase		       =			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
	if len(sys.argv   ) == 2 and sys.argv[1].endswith(".json"   ):
		# If we pass only one argument to the script and it's the path to a json file,
		# let's parse it to get our arguments.
		__lowercase		       =			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
	else:
		__lowercase		       =			parser.parse_args_into_dataclasses()

	# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
	# information sent is the one passed as arguments along with your Python/PyTorch versions.
	send_example_telemetry("run_mim"  ,	SCREAMING_SNAKE_CASE__  ,	SCREAMING_SNAKE_CASE__   )

	# Setup logging
	logging.basicConfig(
	    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"  ,	datefmt="%m/%d/%Y %H:%M:%S"  ,	handlers=[logging.StreamHandler(sys.stdout   )]  ,	)

	if training_args.should_log:
		# The default of training_args.log_level is passive, so we set log level at info here to have that default.
		transformers.utils.logging.set_verbosity_info()

	__lowercase		       =			training_args.get_process_log_level()
	logger.setLevel(SCREAMING_SNAKE_CASE__   )
	transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__   )
	transformers.utils.logging.enable_default_handler()
	transformers.utils.logging.enable_explicit_format()

	# Log on each process the small summary:
	logger.warning(
	    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
	    + F"""distributed training: {bool(training_args.local_rank != -1   )}, 16-bits training: {training_args.fpaa}"""   )
	logger.info(F"""Training/evaluation parameters {training_args}"""   )

	# Detecting last checkpoint.
	__lowercase		       =			None
	if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
		__lowercase		       =			get_last_checkpoint(training_args.output_dir   )
		if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
			raise ValueError(
			    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
			    "Use --overwrite_output_dir to overcome."   )
		elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
			logger.info(
			    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
			    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."   )

    # Initialize our dataset.
	__lowercase		       =			load_dataset(
	    data_args.dataset_name  ,	data_args.dataset_config_name  ,	data_files=data_args.data_files  ,	cache_dir=model_args.cache_dir  ,	use_auth_token=True if model_args.use_auth_token else None  ,	)

	# If we don't have a validation split, split off a percentage of train as validation.
	__lowercase		       =			None if """validation""" in ds.keys() else data_args.train_val_split
	if isinstance(data_args.train_val_split  ,	SCREAMING_SNAKE_CASE__   ) and data_args.train_val_split > 0.0:
		__lowercase		       =			ds["""train"""].train_test_split(data_args.train_val_split   )
		__lowercase		       =			split["""train"""]
		__lowercase		       =			split["""test"""]

	# Create config
	# Distributed training:
	# The .from_pretrained methods guarantee that only one local process can concurrently
	# download model & vocab.
	__lowercase		       =			{
	    """cache_dir""": model_args.cache_dir,
	    """revision""": model_args.model_revision,
	    """use_auth_token""": True if model_args.use_auth_token else None,
	}
	if model_args.config_name_or_path:
		__lowercase		       =			AutoConfig.from_pretrained(model_args.config_name_or_path  ,	**SCREAMING_SNAKE_CASE__   )
	elif model_args.model_name_or_path:
		__lowercase		       =			AutoConfig.from_pretrained(model_args.model_name_or_path  ,	**SCREAMING_SNAKE_CASE__   )
	else:
		__lowercase		       =			CONFIG_MAPPING[model_args.model_type]()
		logger.warning("You are instantiating a new config instance from scratch."   )
		if model_args.config_overrides is not None:
			logger.info(F"""Overriding config: {model_args.config_overrides}"""   )
			config.update_from_string(model_args.config_overrides   )
			logger.info(F"""New config: {config}"""   )

    # make sure the decoder_type is "simmim" (only relevant for BEiT)
	if hasattr(SCREAMING_SNAKE_CASE__  ,	"decoder_type"   ):
		__lowercase		       =			"""simmim"""

	# adapt config
	__lowercase		       =			model_args.image_size if model_args.image_size is not None else config.image_size
	__lowercase		       =			model_args.patch_size if model_args.patch_size is not None else config.patch_size
	__lowercase		       =			(
	    model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride
	)

	config.update(
	    {
	        "image_size": model_args.image_size,
	        "patch_size": model_args.patch_size,
	        "encoder_stride": model_args.encoder_stride,
	    }   )

	# create image processor
	if model_args.image_processor_name:
		__lowercase		       =			AutoImageProcessor.from_pretrained(model_args.image_processor_name  ,	**SCREAMING_SNAKE_CASE__   )
	elif model_args.model_name_or_path:
		__lowercase		       =			AutoImageProcessor.from_pretrained(model_args.model_name_or_path  ,	**SCREAMING_SNAKE_CASE__   )
	else:
		__lowercase		       =			{
		    conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items()
		}
		__lowercase		       =			IMAGE_PROCESSOR_TYPES[model_args.model_type]()

	# create model
	if model_args.model_name_or_path:
		__lowercase		       =			AutoModelForMaskedImageModeling.from_pretrained(
		    model_args.model_name_or_path  ,	from_tf=bool(".ckpt" in model_args.model_name_or_path   )  ,	config=SCREAMING_SNAKE_CASE__  ,	cache_dir=model_args.cache_dir  ,	revision=model_args.model_revision  ,	use_auth_token=True if model_args.use_auth_token else None  ,	)
	else:
		logger.info("Training new model from scratch"   )
		__lowercase		       =			AutoModelForMaskedImageModeling.from_config(SCREAMING_SNAKE_CASE__   )

	if training_args.do_train:
		__lowercase		       =			ds["""train"""].column_names
	else:
		__lowercase		       =			ds["""validation"""].column_names

	if data_args.image_column_name is not None:
		__lowercase		       =			data_args.image_column_name
	elif "image" in column_names:
		__lowercase		       =			"""image"""
	elif "img" in column_names:
		__lowercase		       =			"""img"""
	else:
		__lowercase		       =			column_names[0]

	# transformations as done in original SimMIM paper
	# source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py
	__lowercase		       =			Compose(
	    [
	        Lambda(lambda _SCREAMING_SNAKE_CASE   : img.convert("RGB"   ) if img.mode != "RGB" else img   ),
	        RandomResizedCrop(model_args.image_size  ,	scale=(0.6_7, 1.0)  ,	ratio=(3.0 / 4.0, 4.0 / 3.0)   ),
	        RandomHorizontalFlip(),
	        ToTensor(),
	        Normalize(mean=image_processor.image_mean  ,	std=image_processor.image_std   ),
	    ]   )

	# create mask generator
	__lowercase		       =			MaskGenerator(
	    input_size=model_args.image_size  ,	mask_patch_size=data_args.mask_patch_size  ,	model_patch_size=model_args.patch_size  ,	mask_ratio=data_args.mask_ratio  ,	)

	def preprocess_images(_SCREAMING_SNAKE_CASE   ):
		__lowercase		       =			[transforms(SCREAMING_SNAKE_CASE__   ) for image in examples[image_column_name]]
		__lowercase		       =			[mask_generator() for i in range(len(examples[image_column_name]   )   )]

		return examples

	if training_args.do_train:
		if "train" not in ds:
			raise ValueError("--do_train requires a train dataset"   )
		if data_args.max_train_samples is not None:
			__lowercase		       =			ds["""train"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_train_samples   )   )
		# Set the training transforms
		ds["train"].set_transform(SCREAMING_SNAKE_CASE__   )

	if training_args.do_eval:
		if "validation" not in ds:
			raise ValueError("--do_eval requires a validation dataset"   )
		if data_args.max_eval_samples is not None:
			__lowercase		       =			(
			    ds["""validation"""].shuffle(seed=training_args.seed   ).select(range(data_args.max_eval_samples   )   )
			)
		# Set the validation transforms
		ds["validation"].set_transform(SCREAMING_SNAKE_CASE__   )

	# Initialize our trainer
	__lowercase		       =			Trainer(
	    model=SCREAMING_SNAKE_CASE__  ,	args=SCREAMING_SNAKE_CASE__  ,	train_dataset=ds["train"] if training_args.do_train else None  ,	eval_dataset=ds["validation"] if training_args.do_eval else None  ,	tokenizer=SCREAMING_SNAKE_CASE__  ,	data_collator=SCREAMING_SNAKE_CASE__  ,	)

	# Training
	if training_args.do_train:
		__lowercase		       =			None
		if training_args.resume_from_checkpoint is not None:
			__lowercase		       =			training_args.resume_from_checkpoint
		elif last_checkpoint is not None:
			__lowercase		       =			last_checkpoint
		__lowercase		       =			trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__   )
		trainer.save_model()
		trainer.log_metrics("train"  ,	train_result.metrics   )
		trainer.save_metrics("train"  ,	train_result.metrics   )
		trainer.save_state()

	# Evaluation
	if training_args.do_eval:
		__lowercase		       =			trainer.evaluate()
		trainer.log_metrics("eval"  ,	SCREAMING_SNAKE_CASE__   )
		trainer.save_metrics("eval"  ,	SCREAMING_SNAKE_CASE__   )

	# Write model card and (optionally) push to hub
	__lowercase		       =			{
	    """finetuned_from""": model_args.model_name_or_path,
	    """tasks""": """masked-image-modeling""",
	    """dataset""": data_args.dataset_name,
	    """tags""": ["""masked-image-modeling"""],
	}
	if training_args.push_to_hub:
		trainer.push_to_hub(**SCREAMING_SNAKE_CASE__   )
	else:
		trainer.create_model_card(**SCREAMING_SNAKE_CASE__   )


if __name__ == "__main__":
	main()








import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()

class   _A   ( _lowercase  ,						_lowercase  ,						_lowercase  ,						unittest.TestCase	):


						'''simple docstring'''





						_snake_case			:     Dict      							=      StableUnCLIPImgaImgPipeline
						_snake_case			:     List[Any]      							=      TEXT_GUIDED_IMAGE_VARIATION_PARAMS
						_snake_case			:     Optional[Any]      							=      TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
						_snake_case			:     int      							=      frozenset(
						    []	)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
						_snake_case			:     int      							=      frozenset([]	)



						def     _snake_case	(	self	:							Tuple	):






							'''simple docstring'''



							__lowercase		       =			32
							__lowercase		       =			embedder_hidden_size

							# image encoding components

							__lowercase		       =			CLIPImageProcessor(crop_size=32							,      size=32	)

							torch.manual_seed(0	)
							__lowercase		       =			CLIPVisionModelWithProjection(
							    CLIPVisionConfig(
							        hidden_size=lowerCamelCase							,      projection_dim=lowerCamelCase							,      num_hidden_layers=5							,      num_attention_heads=4							,      image_size=32							,      intermediate_size=37							,      patch_size=1							,      )	)

							# regular denoising components

							torch.manual_seed(0	)
							__lowercase		       =			StableUnCLIPImageNormalizer(embedding_dim=lowerCamelCase	)
							__lowercase		       =			DDPMScheduler(beta_schedule="squaredcos_cap_v2"	)

							torch.manual_seed(0	)
							__lowercase		       =			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

							torch.manual_seed(0	)
							__lowercase		       =			CLIPTextModel(
							    CLIPTextConfig(
							        bos_token_id=0							,      eos_token_id=2							,      hidden_size=lowerCamelCase							,      projection_dim=32							,      intermediate_size=37							,      layer_norm_eps=1e-05							,      num_attention_heads=4							,      num_hidden_layers=5							,      pad_token_id=1							,      vocab_size=1_000							,      )	)

							torch.manual_seed(0	)
							__lowercase		       =			UNetaDConditionModel(
							    sample_size=32							,      in_channels=4							,      out_channels=4							,      down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")							,      up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")							,      block_out_channels=(32, 64)							,      attention_head_dim=(2, 4)							,      class_embed_type="projection"							,      projection_class_embeddings_input_dim=embedder_projection_dim * 2							,      cross_attention_dim=lowerCamelCase							,      layers_per_block=1							,      upcast_attention=lowerCamelCase							,      use_linear_projection=lowerCamelCase							,      )

							torch.manual_seed(0	)
							__lowercase		       =			DDIMScheduler(
							    beta_schedule="scaled_linear"							,      beta_start=0.0_0085							,      beta_end=0.012							,      prediction_type="v_prediction"							,      set_alpha_to_one=lowerCamelCase							,      steps_offset=1							,      )

							torch.manual_seed(0	)
							__lowercase		       =			AutoencoderKL()

							__lowercase		       =			{
							    # image encoding components
							    "feature_extractor": feature_extractor,
							    "image_encoder": image_encoder.eval(),
							    # image noising components
							    "image_normalizer": image_normalizer.eval(),
							    "image_noising_scheduler": image_noising_scheduler,
							    # regular denoising components
							    "tokenizer": tokenizer,
							    "text_encoder": text_encoder.eval(),
							    "unet": unet.eval(),
							    "scheduler": scheduler,
							    "vae": vae.eval(),
							}

							return components



						def     _snake_case	(	self	:							List[Any]							,      lowerCamelCase	:							str							,      lowerCamelCase	:							Any=0							,      lowerCamelCase	:							Union[str, Any]=True	):






							'''simple docstring'''



							if str(lowerCamelCase	).startswith("mps"	):
								__lowercase		       =			torch.manual_seed(lowerCamelCase	)
							else:
								__lowercase		       =			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)

							__lowercase		       =			floats_tensor((1, 3, 32, 32)							,      rng=random.Random(lowerCamelCase	)	).to(lowerCamelCase	)

							if pil_image:
								__lowercase		       =			input_image * 0.5 + 0.5
								__lowercase		       =			input_image.clamp(0							,      1	)
								__lowercase		       =			input_image.cpu().permute(0							,      2							,      3							,      1	).float().numpy()
								__lowercase		       =			DiffusionPipeline.numpy_to_pil(lowerCamelCase	)[0]

							return {
							    "prompt": "An anime racoon running a marathon",
							    "image": input_image,
							    "generator": generator,
							    "num_inference_steps": 2,
							    "output_type": "np",
							}



						@skip_mps
						def     _snake_case	(	self	:							Optional[Any]	):






							'''simple docstring'''



							__lowercase		       =			"cpu"  # ensure determinism for the device-dependent torch.Generator
							__lowercase		       =			self.get_dummy_components()
							__lowercase		       =			StableUnCLIPImgaImgPipeline(**lowerCamelCase	)
							__lowercase		       =			sd_pipe.to(lowerCamelCase	)
							sd_pipe.set_progress_bar_config(disable=lowerCamelCase	)

							__lowercase		       =			self.get_dummy_inputs(lowerCamelCase	)
							inputs.update({"image_embeds": None}	)
							__lowercase		       =			sd_pipe(**lowerCamelCase	).images
							__lowercase		       =			image[0, -3:, -3:, -1]

							assert image.shape == (1, 32, 32, 3)
							__lowercase		       =			np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078]	)

							assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-3



						def     _snake_case	(	self	:							Dict	):






							'''simple docstring'''



							__lowercase		       =			torch_device in ["cpu", "mps"]

							self._test_attention_slicing_forward_pass(test_max_difference=lowerCamelCase	)



						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							__lowercase		       =			torch_device in ["cpu", "mps"]

							self._test_inference_batch_single_identical(test_max_difference=lowerCamelCase	)



						@unittest.skipIf(
						    torch_device != "cuda" or not is_xformers_available()							,      reason="XFormers attention is only available with CUDA and `xformers` installed"							,      )
						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowerCamelCase	)

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


						'''simple docstring'''





						def     _snake_case	(	self	:							Union[str, Any]	):






							'''simple docstring'''



							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



						def     _snake_case	(	self	:							Any	):






							'''simple docstring'''



							__lowercase		       =			load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"	)

							__lowercase		       =			load_numpy(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy"	)

							__lowercase		       =			StableUnCLIPImgaImgPipeline.from_pretrained(
							    "fusing/stable-unclip-2-1-l-img2img"							,      torch_dtype=torch.floataa	)
							pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__lowercase		       =			torch.Generator(device="cpu"	).manual_seed(0	)
							__lowercase		       =			pipe(lowerCamelCase							,      "anime turle"							,      generator=lowerCamelCase							,      output_type="np"	)

							__lowercase		       =			output.images[0]

							assert image.shape == (768, 768, 3)

							assert_mean_pixel_difference(lowerCamelCase							,      lowerCamelCase	)



						def     _snake_case	(	self	:							Optional[Any]	):






							'''simple docstring'''



							__lowercase		       =			load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"	)

							__lowercase		       =			load_numpy(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy"	)

							__lowercase		       =			StableUnCLIPImgaImgPipeline.from_pretrained(
							    "fusing/stable-unclip-2-1-h-img2img"							,      torch_dtype=torch.floataa	)
							pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)
							# stable unclip will oom when integration tests are run on a V100,
							# so turn on memory savings
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__lowercase		       =			torch.Generator(device="cpu"	).manual_seed(0	)
							__lowercase		       =			pipe(lowerCamelCase							,      "anime turle"							,      generator=lowerCamelCase							,      output_type="np"	)

							__lowercase		       =			output.images[0]

							assert image.shape == (768, 768, 3)

							assert_mean_pixel_difference(lowerCamelCase							,      lowerCamelCase	)



						def     _snake_case	(	self	:							str	):






							'''simple docstring'''



							__lowercase		       =			load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"	)

							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

							__lowercase		       =			StableUnCLIPImgaImgPipeline.from_pretrained(
							    "fusing/stable-unclip-2-1-h-img2img"							,      torch_dtype=torch.floataa	)
							__lowercase		       =			pipe.to(lowerCamelCase	)
							pipe.set_progress_bar_config(disable=lowerCamelCase	)
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							__lowercase		       =			pipe(
							    lowerCamelCase							,      "anime turtle"							,      num_inference_steps=2							,      output_type="np"							,      )

							__lowercase		       =			torch.cuda.max_memory_allocated()
							# make sure that less than 7 GB is allocated
							assert mem_bytes < 7 * 10**9



