



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

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
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       :	Dict            =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')



@dataclass
class  lowerCamelCase__    :




		'''simple docstring'''



		snake_case_			=field(
		    default="""cifar10"""   ,       metadata={"""help""": """Name of a dataset from the datasets package"""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={"""help""": """The column name of the images in the files."""})
		snake_case_			=field(default=lowerCamelCase__   ,       metadata={"""help""": """A folder containing the training data."""})
		snake_case_			=field(default=lowerCamelCase__   ,       metadata={"""help""": """A folder containing the validation data."""})
		snake_case_			=field(
		    default=0.15   ,       metadata={"""help""": """Percent to split off of train for validation."""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={
		        """help""": (
		            """For debugging purposes or quicker training, truncate the number of training examples to this """
		            """value if set."""
		        )
		    }   ,       )
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={
		        """help""": (
		            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
		            """value if set."""
		        )
		    }   ,       )



		def 	lowerCAmelCase__   (self				)  ->    List[str]:

						"""simple docstring"""






						lowerCAmelCase__  :       Any				=  {}
						if self.train_dir is not None:
										lowerCAmelCase__  :       int				=  self.train_dir
						if self.validation_dir is not None:
										lowerCAmelCase__  :       int				=  self.validation_dir
						lowerCAmelCase__  :       Optional[Any]				=  data_files if data_files else None



@dataclass
class  lowerCamelCase__    :




		'''simple docstring'''



		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={
		        """help""": (
		            """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."""
		        )
		    }   ,       )
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       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_			=field(
		    default=lowerCamelCase__   ,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""})
		snake_case_			=field(
		    default="""main"""   ,       metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}   ,       )
		snake_case_			=field(default=lowerCamelCase__   ,       metadata={"""help""": """Name or path of preprocessor config."""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={
		        """help""": (
		            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
		            """with private models)."""
		        )
		    }   ,       )
		snake_case_			=field(
		    default=0.75   ,       metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""})
		snake_case_			=field(
		    default=lowerCamelCase__   ,       metadata={"""help""": """Whether or not to train with normalized pixel values as target."""})



@dataclass
class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_			=field(
		    default=1e-3   ,       metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""})






def 			lowerCAmelCase__	(					lowerCamelCase_	:	List[Any]):





				'''simple docstring'''

				lowerCAmelCase__  :       int				=  torch.stack([example['''pixel_values'''] for example in examples])
				return {"pixel_values": pixel_values}






def 			lowerCAmelCase__	(					):





				'''simple docstring'''

				lowerCAmelCase__  :       Tuple				=  HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments))
				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__  :       Optional[int]				=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
				else:
								lowerCAmelCase__		,	lowerCAmelCase__		,	lowerCAmelCase__  :       Optional[Any]				=  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_mae''' ,lowerCamelCase_ ,lowerCamelCase_)

				# 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()

				lowerCAmelCase__  :       Dict				=  training_args.get_process_log_level()
				logger.setLevel(lowerCamelCase_)
				transformers.utils.logging.set_verbosity(lowerCamelCase_)
				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.
				lowerCAmelCase__  :       Optional[Any]				=  None
				if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
								lowerCAmelCase__  :       List[str]				=  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.
				lowerCAmelCase__  :       Optional[int]				=  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.
				lowerCAmelCase__  :       Optional[int]				=  None if '''validation''' in ds.keys() else data_args.train_val_split
				if isinstance(data_args.train_val_split ,lowerCamelCase_) and data_args.train_val_split > 0.0:
								lowerCAmelCase__  :       str				=  ds['''train'''].train_test_split(data_args.train_val_split)
								lowerCAmelCase__  :       Tuple				=  split['''train''']
								lowerCAmelCase__  :       Optional[int]				=  split['''test''']

				# Load pretrained model and image processor
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.
				lowerCAmelCase__  :       List[str]				=  {
				    '''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__  :       Any				=  ViTMAEConfig.from_pretrained(model_args.config_name ,**lowerCamelCase_)
				elif model_args.model_name_or_path:
								lowerCAmelCase__  :       int				=  ViTMAEConfig.from_pretrained(model_args.model_name_or_path ,**lowerCamelCase_)
				else:
								lowerCAmelCase__  :       int				=  ViTMAEConfig()
								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}""")

    # adapt config
				config.update(
				    {
				        '''mask_ratio''': model_args.mask_ratio,
				        '''norm_pix_loss''': model_args.norm_pix_loss,
				    })

				# create image processor
				if model_args.image_processor_name:
								lowerCAmelCase__  :       str				=  ViTImageProcessor.from_pretrained(model_args.image_processor_name ,**lowerCamelCase_)
				elif model_args.model_name_or_path:
								lowerCAmelCase__  :       Union[str, Any]				=  ViTImageProcessor.from_pretrained(model_args.model_name_or_path ,**lowerCamelCase_)
				else:
								lowerCAmelCase__  :       Tuple				=  ViTImageProcessor()

				# create model
				if model_args.model_name_or_path:
								lowerCAmelCase__  :       Union[str, Any]				=  ViTMAEForPreTraining.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__  :       List[Any]				=  ViTMAEForPreTraining(lowerCamelCase_)

				if training_args.do_train:
								lowerCAmelCase__  :       Tuple				=  ds['''train'''].column_names
				else:
								lowerCAmelCase__  :       Optional[Any]				=  ds['''validation'''].column_names

				if data_args.image_column_name is not None:
								lowerCAmelCase__  :       Union[str, Any]				=  data_args.image_column_name
				elif "image" in column_names:
								lowerCAmelCase__  :       Dict				=  '''image'''
				elif "img" in column_names:
								lowerCAmelCase__  :       str				=  '''img'''
				else:
								lowerCAmelCase__  :       Union[str, Any]				=  column_names[0]

				# transformations as done in original MAE paper
				# source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
				if "shortest_edge" in image_processor.size:
								lowerCAmelCase__  :       List[str]				=  image_processor.size['''shortest_edge''']
				else:
								lowerCAmelCase__  :       int				=  (image_processor.size['''height'''], image_processor.size['''width'''])
				lowerCAmelCase__  :       str				=  Compose(
				    [
				        Lambda(lambda lowerCamelCase_: img.convert('''RGB''') if img.mode != "RGB" else img),
				        RandomResizedCrop(lowerCamelCase_ ,scale=(0.2, 1.0) ,interpolation=InterpolationMode.BICUBIC),
				        RandomHorizontalFlip(),
				        ToTensor(),
				        Normalize(mean=image_processor.image_mean ,std=image_processor.image_std),
				    ])

				def preprocess_images(lowerCamelCase_	:	Optional[Any]):
								lowerCAmelCase__  :       Union[str, Any]				=  [transforms(lowerCamelCase_) for image in 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:
												lowerCAmelCase__  :       List[str]				=  ds['''train'''].shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
								# Set the training transforms
								ds["train"].set_transform(lowerCamelCase_)

				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:
												lowerCAmelCase__  :       List[str]				=  (
												    ds['''validation'''].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
												)
								# Set the validation transforms
								ds["validation"].set_transform(lowerCamelCase_)

				# Compute absolute learning rate
				lowerCAmelCase__  :       List[Any]				=  (
				    training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
				)
				if training_args.base_learning_rate is not None:
								lowerCAmelCase__  :       int				=  training_args.base_learning_rate * total_train_batch_size / 256

				# Initialize our trainer
				lowerCAmelCase__  :       int				=  Trainer(
				    model=lowerCamelCase_ ,args=lowerCamelCase_ ,train_dataset=ds['''train'''] if training_args.do_train else None ,eval_dataset=ds['''validation'''] if training_args.do_eval else None ,tokenizer=lowerCamelCase_ ,data_collator=lowerCamelCase_ ,)

				# Training
				if training_args.do_train:
								lowerCAmelCase__  :       Optional[Any]				=  None
								if training_args.resume_from_checkpoint is not None:
												lowerCAmelCase__  :       Tuple				=  training_args.resume_from_checkpoint
								elif last_checkpoint is not None:
												lowerCAmelCase__  :       Any				=  last_checkpoint
								lowerCAmelCase__  :       str				=  trainer.train(resume_from_checkpoint=lowerCamelCase_)
								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:
								lowerCAmelCase__  :       Tuple				=  trainer.evaluate()
								trainer.log_metrics('''eval''' ,lowerCamelCase_)
								trainer.save_metrics('''eval''' ,lowerCamelCase_)

				# Write model card and (optionally) push to hub
				lowerCAmelCase__  :       Union[str, Any]				=  {
				    '''tasks''': '''masked-auto-encoding''',
				    '''dataset''': data_args.dataset_name,
				    '''tags''': ['''masked-auto-encoding'''],
				}
				if training_args.push_to_hub:
								trainer.push_to_hub(**lowerCamelCase_)
				else:
								trainer.create_model_card(**lowerCamelCase_)






def 			lowerCAmelCase__	(					lowerCamelCase_	:	int):





				'''simple docstring'''

				main()


if __name__ == "__main__":
							main()






import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()



class  lowerCamelCase__    (							lowerCamelCase__   ,       lowerCamelCase__   ,       lowerCamelCase__   ,       unittest.TestCase):




		'''simple docstring'''



		snake_case_			=AltDiffusionPipeline
		snake_case_			=TEXT_TO_IMAGE_PARAMS
		snake_case_			=TEXT_TO_IMAGE_BATCH_PARAMS
		snake_case_			=TEXT_TO_IMAGE_IMAGE_PARAMS
		snake_case_			=TEXT_TO_IMAGE_IMAGE_PARAMS



		def 	lowerCAmelCase__   (self				)  ->    Dict:

						"""simple docstring"""






						torch.manual_seed(0				)
						lowerCAmelCase__  :       int				=  UNetaDConditionModel(
						    block_out_channels=(32, 64)	,layers_per_block=2	,sample_size=32	,in_channels=4	,out_channels=4	,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')	,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')	,cross_attention_dim=32	,)
						lowerCAmelCase__  :       List[str]				=  DDIMScheduler(
						    beta_start=0.0_0085	,beta_end=0.012	,beta_schedule='''scaled_linear'''	,clip_sample=__lowerCamelCase	,set_alpha_to_one=__lowerCamelCase	,)
						torch.manual_seed(0				)
						lowerCAmelCase__  :       Optional[Any]				=  AutoencoderKL(
						    block_out_channels=[32, 64]	,in_channels=3	,out_channels=3	,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']	,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']	,latent_channels=4	,)

						# TODO: address the non-deterministic text encoder (fails for save-load tests)
						# torch.manual_seed(0)
						# text_encoder_config = RobertaSeriesConfig(
						#     hidden_size=32,
						#     project_dim=32,
						#     intermediate_size=37,
						#     layer_norm_eps=1e-05,
						#     num_attention_heads=4,
						#     num_hidden_layers=5,
						#     vocab_size=5002,
						# )
						# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

						torch.manual_seed(0				)
						lowerCAmelCase__  :       Dict				=  CLIPTextConfig(
						    bos_token_id=0	,eos_token_id=2	,hidden_size=32	,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=50_02	,)
						lowerCAmelCase__  :       int				=  CLIPTextModel(__lowerCamelCase				)

						lowerCAmelCase__  :       str				=  XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''				)
						lowerCAmelCase__  :       Union[str, Any]				=  77

						lowerCAmelCase__  :       str				=  {
						    '''unet''': unet,
						    '''scheduler''': scheduler,
						    '''vae''': vae,
						    '''text_encoder''': text_encoder,
						    '''tokenizer''': tokenizer,
						    '''safety_checker''': None,
						    '''feature_extractor''': None,
						}
						return components



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase=0				)  ->    Optional[Any]:

						"""simple docstring"""






						if str(__lowerCamelCase				).startswith('''mps'''				):
										lowerCAmelCase__  :       Tuple				=  torch.manual_seed(__lowerCamelCase				)
						else:
										lowerCAmelCase__  :       Any				=  torch.Generator(device=__lowerCamelCase				).manual_seed(__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  {
						    '''prompt''': '''A painting of a squirrel eating a burger''',
						    '''generator''': generator,
						    '''num_inference_steps''': 2,
						    '''guidance_scale''': 6.0,
						    '''output_type''': '''numpy''',
						}
						return inputs



		def 	lowerCAmelCase__   (self				)  ->    str:

						"""simple docstring"""






						super().test_attention_slicing_forward_pass(expected_max_diff=3e-3				)



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






						super().test_inference_batch_single_identical(expected_max_diff=3e-3				)



		def 	lowerCAmelCase__   (self				)  ->    Tuple:

						"""simple docstring"""






						lowerCAmelCase__  :       List[str]				=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator

						lowerCAmelCase__  :       int				=  self.get_dummy_components()
						torch.manual_seed(0				)
						lowerCAmelCase__  :       str				=  RobertaSeriesConfig(
						    hidden_size=32	,project_dim=32	,intermediate_size=37	,layer_norm_eps=1e-05	,num_attention_heads=4	,num_hidden_layers=5	,vocab_size=50_02	,)
						# TODO: remove after fixing the non-deterministic text encoder
						lowerCAmelCase__  :       Any				=  RobertaSeriesModelWithTransformation(__lowerCamelCase				)
						lowerCAmelCase__  :       List[str]				=  text_encoder

						lowerCAmelCase__  :       List[Any]				=  AltDiffusionPipeline(**__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       List[str]				=  self.get_dummy_inputs(__lowerCamelCase				)
						lowerCAmelCase__  :       str				=  '''A photo of an astronaut'''
						lowerCAmelCase__  :       Any				=  alt_pipe(**__lowerCamelCase				)
						lowerCAmelCase__  :       int				=  output.images
						lowerCAmelCase__  :       List[Any]				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						lowerCAmelCase__  :       Optional[Any]				=  np.array(
						    [0.574_8162, 0.6044_7145, 0.4882_1217, 0.5010_0636, 0.543_1185, 0.4576_3683, 0.4965_7696, 0.4813_2733, 0.4757_3093]				)

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



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

						"""simple docstring"""






						lowerCAmelCase__  :       List[Any]				=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator

						lowerCAmelCase__  :       str				=  self.get_dummy_components()
						lowerCAmelCase__  :       Optional[Any]				=  PNDMScheduler(skip_prk_steps=__lowerCamelCase				)
						torch.manual_seed(0				)
						lowerCAmelCase__  :       int				=  RobertaSeriesConfig(
						    hidden_size=32	,project_dim=32	,intermediate_size=37	,layer_norm_eps=1e-05	,num_attention_heads=4	,num_hidden_layers=5	,vocab_size=50_02	,)
						# TODO: remove after fixing the non-deterministic text encoder
						lowerCAmelCase__  :       Tuple				=  RobertaSeriesModelWithTransformation(__lowerCamelCase				)
						lowerCAmelCase__  :       List[str]				=  text_encoder
						lowerCAmelCase__  :       List[Any]				=  AltDiffusionPipeline(**__lowerCamelCase				)
						lowerCAmelCase__  :       str				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       Union[str, Any]				=  self.get_dummy_inputs(__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[int]				=  alt_pipe(**__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[int]				=  output.images
						lowerCAmelCase__  :       str				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						lowerCAmelCase__  :       Union[str, Any]				=  np.array(
						    [0.5160_5093, 0.570_7241, 0.4736_5507, 0.5057_8886, 0.563_3877, 0.464_2503, 0.518_2081, 0.4876_3484, 0.4908_4237]				)

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



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




		'''simple docstring'''



		def 	lowerCAmelCase__   (self				)  ->    List[Any]:

						"""simple docstring"""






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



		def 	lowerCAmelCase__   (self				)  ->    List[str]:

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''	,safety_checker=__lowerCamelCase				)
						lowerCAmelCase__  :       List[Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       Any				=  '''A painting of a squirrel eating a burger'''
						lowerCAmelCase__  :       List[Any]				=  torch.manual_seed(0				)
						lowerCAmelCase__  :       str				=  alt_pipe([prompt]	,generator=__lowerCamelCase	,guidance_scale=6.0	,num_inference_steps=20	,output_type='''np'''				)

						lowerCAmelCase__  :       str				=  output.images

						lowerCAmelCase__  :       int				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						lowerCAmelCase__  :       Dict				=  np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586]				)

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



		def 	lowerCAmelCase__   (self				)  ->    Any:

						"""simple docstring"""






						lowerCAmelCase__  :       List[Any]				=  DDIMScheduler.from_pretrained('''BAAI/AltDiffusion'''	,subfolder='''scheduler'''				)

						lowerCAmelCase__  :       List[str]				=  AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''	,scheduler=__lowerCamelCase	,safety_checker=__lowerCamelCase				)
						lowerCAmelCase__  :       Union[str, Any]				=  alt_pipe.to(__lowerCamelCase				)
						alt_pipe.set_progress_bar_config(disable=__lowerCamelCase				)

						lowerCAmelCase__  :       List[Any]				=  '''A painting of a squirrel eating a burger'''
						lowerCAmelCase__  :       Optional[Any]				=  torch.manual_seed(0				)

						lowerCAmelCase__  :       List[str]				=  alt_pipe([prompt]	,generator=__lowerCamelCase	,num_inference_steps=2	,output_type='''numpy'''				)
						lowerCAmelCase__  :       List[str]				=  output.images

						lowerCAmelCase__  :       Optional[int]				=  image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						lowerCAmelCase__  :       List[Any]				=  np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323]				)

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

