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

from datasets import Dataset, load_dataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_FOR_MASKED_LM_MAPPING,
    AutoConfig,
    AutoModelForMaskedLM,
    AutoTokenizer,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


_A     =  logging.getLogger(__name__)
_A     =  list(MODEL_FOR_MASKED_LM_MAPPING.keys())
_A     =  tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)





@dataclass
class 			_lowerCAmelCase      :
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={
				        '''help''': (
				            '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.'''
				        )
				    }      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(UpperCamelCase__ )}      ,   )
				_lowercase    	=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'''
				        )
				    }      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}      ,   )
				_lowercase    	=field(
				    default='''main'''      ,   metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={
				        '''help''': (
				            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
				            '''with private models).'''
				        )
				    }      ,   )




				def   __a		(      self  )       ->   Tuple:
							if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None):
										raise ValueError(
										    "--config_overrides can't be used in combination with --config_name or --model_name_or_path"  )





@dataclass
class 			_lowerCAmelCase      :
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} )
				_lowercase    	=field(default=UpperCamelCase__      ,   metadata={'''help''': '''The input training data file (a text file).'''} )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''}      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''}      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )
				_lowercase    	=field(
				    default=5      ,   metadata={
				        '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split'''
				    }      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={
				        '''help''': (
				            '''The maximum total input sequence length after tokenization. Sequences longer '''
				            '''than this will be truncated. Default to the max input length of the model.'''
				        )
				    }      ,   )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={'''help''': '''The number of processes to use for the preprocessing.'''}      ,   )
				_lowercase    	=field(
				    default=0.15      ,   metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} )
				_lowercase    	=field(
				    default=UpperCamelCase__      ,   metadata={
				        '''help''': (
				            '''Whether to pad all samples to `max_seq_length`. '''
				            '''If False, will pad the samples dynamically when batching to the maximum length in the batch.'''
				        )
				    }      ,   )




				def   __a		(      self  )       ->   Dict:
							if self.train_file is not None:
										lowerCAmelCase_      			=			self.train_file.split("."  )[-1]
										assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file."
							if self.validation_file is not None:
										lowerCAmelCase_      			=			self.validation_file.split("."  )[-1]
										assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file."






def      lowerCamelCase__       (       __lowerCAmelCase						:						Optional[Any]					,							__lowerCAmelCase						:						str       ):




			"""simple docstring"""


			with open(__lowerCAmelCase					,							"r"					,							encoding="utf-8"       ) as f:
						lowerCAmelCase_      			=			[json.loads(__lowerCAmelCase       ) for line in f.read().splitlines() if (len(__lowerCAmelCase       ) > 0 and not line.isspace())]
			assert len(__lowerCAmelCase       ) == len(__lowerCAmelCase       )

			lowerCAmelCase_      			=			{c: dataset[c] for c in dataset.column_names}
			lowerCAmelCase_      			=			refs
			return Dataset.from_dict(__lowerCAmelCase       )






def      lowerCamelCase__       (       ):




			"""simple docstring"""


			lowerCAmelCase_      			=			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.
						lowerCAmelCase_			,						lowerCAmelCase_			,						lowerCAmelCase_      			=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
			else:
						lowerCAmelCase_			,						lowerCAmelCase_			,						lowerCAmelCase_      			=			parser.parse_args_into_dataclasses()

			# Detecting last checkpoint.
			lowerCAmelCase_      			=			None
			if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
						lowerCAmelCase_      			=			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:
									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."       )

    # 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       )]					,							)
			logger.setLevel(logging.INFO if is_main_process(training_args.local_rank       ) else logging.WARN       )

			# 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}"""       )
			# Set the verbosity to info of the Transformers logger (on main process only):
			if is_main_process(training_args.local_rank       ):
						transformers.utils.logging.set_verbosity_info()
						transformers.utils.logging.enable_default_handler()
						transformers.utils.logging.enable_explicit_format()
			logger.info("Training/evaluation parameters %s"					,							__lowerCAmelCase       )

			# Set seed before initializing model.
			set_seed(training_args.seed       )

			# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
			# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
			# (the dataset will be downloaded automatically from the datasets Hub).
			#
			# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
			# 'text' is found. You can easily tweak this behavior (see below).
			#
			# In distributed training, the load_dataset function guarantee that only one local process can concurrently
			# download the dataset.
			if data_args.dataset_name is not None:
						# Downloading and loading a dataset from the hub.
						lowerCAmelCase_      			=			load_dataset(data_args.dataset_name					,							data_args.dataset_config_name       )
						if "validation" not in datasets.keys():
									lowerCAmelCase_      			=			load_dataset(
									    data_args.dataset_name					,							data_args.dataset_config_name					,							split=F"""train[:{data_args.validation_split_percentage}%]"""					,							)
									lowerCAmelCase_      			=			load_dataset(
									    data_args.dataset_name					,							data_args.dataset_config_name					,							split=F"""train[{data_args.validation_split_percentage}%:]"""					,							)
			else:
						lowerCAmelCase_      			=			{}
						if data_args.train_file is not None:
									lowerCAmelCase_      			=			data_args.train_file
						if data_args.validation_file is not None:
									lowerCAmelCase_      			=			data_args.validation_file
						lowerCAmelCase_      			=			data_args.train_file.split("."       )[-1]
						if extension == "txt":
									lowerCAmelCase_      			=			"text"
						lowerCAmelCase_      			=			load_dataset(__lowerCAmelCase					,							data_files=__lowerCAmelCase       )
			# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
			# https://huggingface.co/docs/datasets/loading_datasets.html.

			# Load pretrained model and tokenizer
			#
			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.
			lowerCAmelCase_      			=			{
			    "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:
						lowerCAmelCase_      			=			AutoConfig.from_pretrained(model_args.config_name					,							**__lowerCAmelCase       )
			elif model_args.model_name_or_path:
						lowerCAmelCase_      			=			AutoConfig.from_pretrained(model_args.model_name_or_path					,							**__lowerCAmelCase       )
			else:
						lowerCAmelCase_      			=			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}"""       )

			lowerCAmelCase_      			=			{
			    "cache_dir": model_args.cache_dir,
			    "use_fast": model_args.use_fast_tokenizer,
			    "revision": model_args.model_revision,
			    "use_auth_token": True if model_args.use_auth_token else None,
			}
			if model_args.tokenizer_name:
						lowerCAmelCase_      			=			AutoTokenizer.from_pretrained(model_args.tokenizer_name					,							**__lowerCAmelCase       )
			elif model_args.model_name_or_path:
						lowerCAmelCase_      			=			AutoTokenizer.from_pretrained(model_args.model_name_or_path					,							**__lowerCAmelCase       )
			else:
						raise ValueError(
						    "You are instantiating a new tokenizer from scratch. This is not supported by this script."
						    "You can do it from another script, save it, and load it from here, using --tokenizer_name."       )

			if model_args.model_name_or_path:
						lowerCAmelCase_      			=			AutoModelForMaskedLM.from_pretrained(
						    model_args.model_name_or_path					,							from_tf=bool(".ckpt" in model_args.model_name_or_path       )					,							config=__lowerCAmelCase					,							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"       )
						lowerCAmelCase_      			=			AutoModelForMaskedLM.from_config(__lowerCAmelCase       )

			model.resize_token_embeddings(len(__lowerCAmelCase       )       )

			# Preprocessing the datasets.
			# First we tokenize all the texts.
			if training_args.do_train:
						lowerCAmelCase_      			=			datasets["train"].column_names
			else:
						lowerCAmelCase_      			=			datasets["validation"].column_names
			lowerCAmelCase_      			=			"text" if "text" in column_names else column_names[0]

			lowerCAmelCase_      			=			"max_length" if data_args.pad_to_max_length else False

			def tokenize_function(__lowerCAmelCase						:						str       ):
						# Remove empty lines
						lowerCAmelCase_      			=			[line for line in examples["text"] if len(__lowerCAmelCase       ) > 0 and not line.isspace()]
						return tokenizer(examples["text"]					,							padding=__lowerCAmelCase					,							truncation=__lowerCAmelCase					,							max_length=data_args.max_seq_length       )

			lowerCAmelCase_      			=			datasets.map(
			    __lowerCAmelCase					,							batched=__lowerCAmelCase					,							num_proc=data_args.preprocessing_num_workers					,							remove_columns=[text_column_name]					,							load_from_cache_file=not data_args.overwrite_cache					,							)

			# Add the chinese references if provided
			if data_args.train_ref_file is not None:
						lowerCAmelCase_      			=			add_chinese_references(tokenized_datasets["train"]					,							data_args.train_ref_file       )
			if data_args.validation_ref_file is not None:
						lowerCAmelCase_      			=			add_chinese_references(
						    tokenized_datasets["validation"]					,							data_args.validation_ref_file       )
			# If we have ref files, need to avoid it removed by trainer
			lowerCAmelCase_      			=			data_args.train_ref_file or data_args.validation_ref_file
			if has_ref:
						lowerCAmelCase_      			=			False

			# Data collator
			# This one will take care of randomly masking the tokens.
			lowerCAmelCase_      			=			DataCollatorForWholeWordMask(tokenizer=__lowerCAmelCase					,							mlm_probability=data_args.mlm_probability       )

			# Initialize our Trainer
			lowerCAmelCase_      			=			Trainer(
			    model=__lowerCAmelCase					,							args=__lowerCAmelCase					,							train_dataset=tokenized_datasets["train"] if training_args.do_train else None					,							eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None					,							tokenizer=__lowerCAmelCase					,							data_collator=__lowerCAmelCase					,							)

			# Training
			if training_args.do_train:
						if last_checkpoint is not None:
									lowerCAmelCase_      			=			last_checkpoint
						elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path       ):
									lowerCAmelCase_      			=			model_args.model_name_or_path
						else:
									lowerCAmelCase_      			=			None
						lowerCAmelCase_      			=			trainer.train(resume_from_checkpoint=__lowerCAmelCase       )
						trainer.save_model()  # Saves the tokenizer too for easy upload

						lowerCAmelCase_      			=			os.path.join(training_args.output_dir					,							"train_results.txt"       )
						if trainer.is_world_process_zero():
									with open(__lowerCAmelCase					,							"w"       ) as writer:
												logger.info("***** Train results *****"       )
												for key, value in sorted(train_result.metrics.items()       ):
															logger.info(F"""  {key} = {value}"""       )
															writer.write(F"""{key} = {value}\n"""       )

            # Need to save the state, since Trainer.save_model saves only the tokenizer with the model
									trainer.state.save_to_json(os.path.join(training_args.output_dir					,							"trainer_state.json"       )       )

    # Evaluation
			lowerCAmelCase_      			=			{}
			if training_args.do_eval:
						logger.info("*** Evaluate ***"       )

						lowerCAmelCase_      			=			trainer.evaluate()

						lowerCAmelCase_      			=			math.exp(eval_output["eval_loss"]       )
						lowerCAmelCase_      			=			perplexity

						lowerCAmelCase_      			=			os.path.join(training_args.output_dir					,							"eval_results_mlm_wwm.txt"       )
						if trainer.is_world_process_zero():
									with open(__lowerCAmelCase					,							"w"       ) as writer:
												logger.info("***** Eval results *****"       )
												for key, value in sorted(results.items()       ):
															logger.info(F"""  {key} = {value}"""       )
															writer.write(F"""{key} = {value}\n"""       )

			return results






def      lowerCamelCase__       (       __lowerCAmelCase						:						List[Any]       ):




			"""simple docstring"""


			main()


if __name__ == "__main__":
							main()





import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()





class 			_lowerCAmelCase      (			__a      ,   __a      ,   __a      ,   unittest.TestCase ):
				_lowercase    	=StableUnCLIPPipeline
				_lowercase    	=TEXT_TO_IMAGE_PARAMS
				_lowercase    	=TEXT_TO_IMAGE_BATCH_PARAMS
				_lowercase    	=TEXT_TO_IMAGE_IMAGE_PARAMS
				_lowercase    	=TEXT_TO_IMAGE_IMAGE_PARAMS

				# TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
				_lowercase    	=False




				def   __a		(      self  )       ->   Dict:
							lowerCAmelCase_      			=			32
							lowerCAmelCase_      			=			embedder_hidden_size

							# prior components

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

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			CLIPTextModelWithProjection(
							    CLIPTextConfig(
							        bos_token_id=0       ,       eos_token_id=2       ,       hidden_size=_UpperCamelCase       ,       projection_dim=_UpperCamelCase       ,       intermediate_size=37       ,       layer_norm_eps=1e-0_5       ,       num_attention_heads=4       ,       num_hidden_layers=5       ,       pad_token_id=1       ,       vocab_size=1_000       ,       )  )

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			PriorTransformer(
							    num_attention_heads=2       ,       attention_head_dim=12       ,       embedding_dim=_UpperCamelCase       ,       num_layers=1       ,       )

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			DDPMScheduler(
							    variance_type="fixed_small_log"       ,       prediction_type="sample"       ,       num_train_timesteps=1_000       ,       clip_sample=_UpperCamelCase       ,       clip_sample_range=5.0       ,       beta_schedule="squaredcos_cap_v2"       ,       )

							# regular denoising components

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			StableUnCLIPImageNormalizer(embedding_dim=_UpperCamelCase  )
							lowerCAmelCase_      			=			DDPMScheduler(beta_schedule="squaredcos_cap_v2"  )

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

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

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			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=_UpperCamelCase       ,       layers_per_block=1       ,       upcast_attention=_UpperCamelCase       ,       use_linear_projection=_UpperCamelCase       ,       )

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			DDIMScheduler(
							    beta_schedule="scaled_linear"       ,       beta_start=0.00085       ,       beta_end=0.012       ,       prediction_type="v_prediction"       ,       set_alpha_to_one=_UpperCamelCase       ,       steps_offset=1       ,       )

							torch.manual_seed(0  )
							lowerCAmelCase_      			=			AutoencoderKL()

							lowerCAmelCase_      			=			{
							    # prior components
							    "prior_tokenizer": prior_tokenizer,
							    "prior_text_encoder": prior_text_encoder,
							    "prior": prior,
							    "prior_scheduler": prior_scheduler,
							    # image noising components
							    "image_normalizer": image_normalizer,
							    "image_noising_scheduler": image_noising_scheduler,
							    # regular denoising components
							    "tokenizer": tokenizer,
							    "text_encoder": text_encoder,
							    "unet": unet,
							    "scheduler": scheduler,
							    "vae": vae,
							}

							return components




				def   __a		(      self       ,       _UpperCamelCase       ,       _UpperCamelCase=0  )       ->   Tuple:
							if str(_UpperCamelCase  ).startswith("mps"  ):
										lowerCAmelCase_      			=			torch.manual_seed(_UpperCamelCase  )
							else:
										lowerCAmelCase_      			=			torch.Generator(device=_UpperCamelCase  ).manual_seed(_UpperCamelCase  )
							lowerCAmelCase_      			=			{
							    "prompt": "A painting of a squirrel eating a burger",
							    "generator": generator,
							    "num_inference_steps": 2,
							    "prior_num_inference_steps": 2,
							    "output_type": "numpy",
							}
							return inputs




				def   __a		(      self  )       ->   List[Any]:
							lowerCAmelCase_      			=			torch_device == "cpu"

							self._test_attention_slicing_forward_pass(test_max_difference=_UpperCamelCase  )




				def   __a		(      self  )       ->   str:
							lowerCAmelCase_      			=			torch_device in ["cpu", "mps"]

							self._test_inference_batch_single_identical(test_max_difference=_UpperCamelCase  )





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




				def   __a		(      self  )       ->   List[str]:
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()




				def   __a		(      self  )       ->   Optional[int]:
							lowerCAmelCase_      			=			load_numpy(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy"  )

							lowerCAmelCase_      			=			StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"       ,       torch_dtype=torch.floataa  )
							pipe.to(_UpperCamelCase  )
							pipe.set_progress_bar_config(disable=_UpperCamelCase  )
							# 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()

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

							lowerCAmelCase_      			=			output.images[0]

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

							assert_mean_pixel_difference(_UpperCamelCase       ,       _UpperCamelCase  )




				def   __a		(      self  )       ->   Optional[Any]:
							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

							lowerCAmelCase_      			=			StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"       ,       torch_dtype=torch.floataa  )
							lowerCAmelCase_      			=			pipe.to(_UpperCamelCase  )
							pipe.set_progress_bar_config(disable=_UpperCamelCase  )
							pipe.enable_attention_slicing()
							pipe.enable_sequential_cpu_offload()

							lowerCAmelCase_      			=			pipe(
							    "anime turtle"       ,       prior_num_inference_steps=2       ,       num_inference_steps=2       ,       output_type="np"       ,       )

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



