



import argparse
import glob
import logging
import os
import sys
import time
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple

import numpy as np
import pytorch_lightning as pl
import torch
from callbacks import SeqaSeqLoggingCallback, get_checkpoint_callback, get_early_stopping_callback
from torch import nn
from torch.utils.data import DataLoader

from transformers import MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import (
    ROUGE_KEYS,
    LegacySeqaSeqDataset,
    SeqaSeqDataset,
    assert_all_frozen,
    calculate_bleu,
    calculate_rouge,
    check_output_dir,
    flatten_list,
    freeze_embeds,
    freeze_params,
    get_git_info,
    label_smoothed_nll_loss,
    lmap,
    pickle_save,
    save_git_info,
    save_json,
    use_task_specific_params,
)


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import BaseTransformer, add_generic_args, generic_train  # noqa


lowerCAmelCase__		:					int							=logging.getLogger(__name__)

class        UpperCAmelCase_  (       __SCREAMING_SNAKE_CASE	):

						'''simple docstring'''




						UpperCamelCase__      :			Any      =  '''summarization'''
						UpperCamelCase__      :			Dict      =  ['''loss''']
						UpperCamelCase__      :			List[str]      =  ROUGE_KEYS
						UpperCamelCase__      :			List[str]      =  '''rouge2'''






						def __init__(   self				,							_A				,							**_A		):







													'''simple docstring'''

													if hparams.sortish_sampler and hparams.gpus > 1:
																				__SCREAMING_SNAKE_CASE									= False
													elif hparams.max_tokens_per_batch is not None:
																				if hparams.gpus > 1:
																											raise NotImplementedError('Dynamic Batch size does not work for multi-gpu training'		)
																				if hparams.sortish_sampler:
																											raise ValueError('--sortish_sampler and --max_tokens_per_batch may not be used simultaneously'		)

													super().__init__(UpperCamelCase__				,							num_labels=UpperCamelCase__				,							mode=self.mode				,							**UpperCamelCase__		)
													use_task_specific_params(self.model				,							'summarization'		)
													save_git_info(self.hparams.output_dir		)
													__SCREAMING_SNAKE_CASE									= Path(self.output_dir		) / '''metrics.json'''
													__SCREAMING_SNAKE_CASE									= Path(self.output_dir		) / '''hparams.pkl'''
													pickle_save(self.hparams				,							self.hparams_save_path		)
													__SCREAMING_SNAKE_CASE									= 0
													__SCREAMING_SNAKE_CASE									= defaultdict(UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= self.config.model_type
													__SCREAMING_SNAKE_CASE									= self.config.tgt_vocab_size if self.model_type == '''fsmt''' else self.config.vocab_size

													__SCREAMING_SNAKE_CASE									= {
													    "data_dir": self.hparams.data_dir,
													    "max_source_length": self.hparams.max_source_length,
													    "prefix": self.model.config.prefix or "",
													}
													__SCREAMING_SNAKE_CASE									= {
													    '''train''': self.hparams.n_train,
													    '''val''': self.hparams.n_val,
													    '''test''': self.hparams.n_test,
													}
													__SCREAMING_SNAKE_CASE									= {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}

													__SCREAMING_SNAKE_CASE									= {
													    '''train''': self.hparams.max_target_length,
													    '''val''': self.hparams.val_max_target_length,
													    '''test''': self.hparams.test_max_target_length,
													}
													assert self.target_lens["train"] <= self.target_lens["val"], f"""target_lens: {self.target_lens}"""
													assert self.target_lens["train"] <= self.target_lens["test"], f"""target_lens: {self.target_lens}"""
													if self.hparams.freeze_embeds:
																				freeze_embeds(self.model		)
													if self.hparams.freeze_encoder:
																				freeze_params(self.model.get_encoder()		)
																				assert_all_frozen(self.model.get_encoder()		)

													__SCREAMING_SNAKE_CASE									= get_git_info()['''repo_sha''']
													__SCREAMING_SNAKE_CASE									= hparams.num_workers
													__SCREAMING_SNAKE_CASE									= None  # default to config
													if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer				,							UpperCamelCase__		):
																				__SCREAMING_SNAKE_CASE									= self.tokenizer.lang_code_to_id[hparams.tgt_lang]
																				__SCREAMING_SNAKE_CASE									= self.decoder_start_token_id
													__SCREAMING_SNAKE_CASE									= (
													    SeqaSeqDataset if hasattr(self.tokenizer				,							'prepare_seq2seq_batch'		) else LegacySeqaSeqDataset
													)
													__SCREAMING_SNAKE_CASE									= False
													__SCREAMING_SNAKE_CASE									= self.model.config.num_beams if self.hparams.eval_beams is None else self.hparams.eval_beams
													if self.hparams.eval_max_gen_length is not None:
																				__SCREAMING_SNAKE_CASE									= self.hparams.eval_max_gen_length
													else:
																				__SCREAMING_SNAKE_CASE									= self.model.config.max_length
													__SCREAMING_SNAKE_CASE									= self.default_val_metric if self.hparams.val_metric is None else self.hparams.val_metric






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= {
													    k: self.tokenizer.batch_decode(v.tolist()		) if '''mask''' not in k else v.shape for k, v in batch.items()
													}
													save_json(UpperCamelCase__				,							Path(self.output_dir		) / 'text_batch.json'		)
													save_json({k: v.tolist() for k, v in batch.items()}				,							Path(self.output_dir		) / 'tok_batch.json'		)

													__SCREAMING_SNAKE_CASE									= True
													return readable_batch






						def 	_A     (   self				,							_A				,							**_A		):







													'''simple docstring'''

													return self.model(UpperCamelCase__				,							**UpperCamelCase__		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.tokenizer.batch_decode(
													    UpperCamelCase__				,							skip_special_tokens=UpperCamelCase__				,							clean_up_tokenization_spaces=UpperCamelCase__		)
													return lmap(str.strip				,							UpperCamelCase__		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.tokenizer.pad_token_id
													__SCREAMING_SNAKE_CASE									= batch['''input_ids'''], batch['''attention_mask''']
													__SCREAMING_SNAKE_CASE									= batch['''labels''']
													if isinstance(self.model				,							UpperCamelCase__		):
																				__SCREAMING_SNAKE_CASE									= self.model._shift_right(UpperCamelCase__		)
													else:
																				__SCREAMING_SNAKE_CASE									= shift_tokens_right(UpperCamelCase__				,							UpperCamelCase__		)
													if not self.already_saved_batch:  # This would be slightly better if it only happened on rank zero
																				__SCREAMING_SNAKE_CASE									= decoder_input_ids
																				self.save_readable_batch(UpperCamelCase__		)

													__SCREAMING_SNAKE_CASE									= self(UpperCamelCase__				,							attention_mask=UpperCamelCase__				,							decoder_input_ids=UpperCamelCase__				,							use_cache=UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= outputs['''logits''']
													if self.hparams.label_smoothing == 0:
																				# Same behavior as modeling_bart.py, besides ignoring pad_token_id
																				__SCREAMING_SNAKE_CASE									= nn.CrossEntropyLoss(ignore_index=UpperCamelCase__		)

																				assert lm_logits.shape[-1] == self.vocab_size
																				__SCREAMING_SNAKE_CASE									= ce_loss_fct(lm_logits.view(-1				,							lm_logits.shape[-1]		)				,							tgt_ids.view(-1		)		)
													else:
																				__SCREAMING_SNAKE_CASE									= nn.functional.log_softmax(UpperCamelCase__				,							dim=-1		)
																				__SCREAMING_SNAKE_CASE									= label_smoothed_nll_loss(
																				    UpperCamelCase__				,							UpperCamelCase__				,							self.hparams.label_smoothing				,							ignore_index=UpperCamelCase__		)
													return (loss,)






						@property
						def 	_A     (   self		):







													'''simple docstring'''

													return self.tokenizer.pad_token_id






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self._step(UpperCamelCase__		)

													__SCREAMING_SNAKE_CASE									= dict(zip(self.loss_names				,							UpperCamelCase__		)		)
													# tokens per batch
													__SCREAMING_SNAKE_CASE									= batch['''input_ids'''].ne(self.pad		).sum() + batch['''labels'''].ne(self.pad		).sum()
													__SCREAMING_SNAKE_CASE									= batch['''input_ids'''].shape[0]
													__SCREAMING_SNAKE_CASE									= batch['''input_ids'''].eq(self.pad		).sum()
													__SCREAMING_SNAKE_CASE									= batch['''input_ids'''].eq(self.pad		).float().mean()
													# TODO(SS): make a wandb summary metric for this
													return {"loss": loss_tensors[0], "log": logs}






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													return self._generative_step(UpperCamelCase__		)






						def 	_A     (   self				,							_A				,							_A="val"		):







													'''simple docstring'''

													self.step_count += 1
													__SCREAMING_SNAKE_CASE									= {k: torch.stack([x[k] for x in outputs]		).mean() for k in self.loss_names}
													__SCREAMING_SNAKE_CASE									= losses['''loss''']
													__SCREAMING_SNAKE_CASE									= {
													    k: np.array([x[k] for x in outputs]		).mean() for k in self.metric_names + ['''gen_time''', '''gen_len''']
													}
													__SCREAMING_SNAKE_CASE									= (
													    generative_metrics[self.val_metric] if self.val_metric in generative_metrics else losses[self.val_metric]
													)
													__SCREAMING_SNAKE_CASE									= torch.tensor(UpperCamelCase__		).type_as(UpperCamelCase__		)
													generative_metrics.update({k: v.item() for k, v in losses.items()}		)
													losses.update(UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= {f"""{prefix}_avg_{k}""": x for k, x in losses.items()}
													__SCREAMING_SNAKE_CASE									= self.step_count
													self.metrics[prefix].append(UpperCamelCase__		)  # callback writes this to self.metrics_save_path
													__SCREAMING_SNAKE_CASE									= flatten_list([x['preds'] for x in outputs]		)
													return {
													    "log": all_metrics,
													    "preds": preds,
													    f"""{prefix}_loss""": loss,
													    f"""{prefix}_{self.val_metric}""": metric_tensor,
													}






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													return calculate_rouge(UpperCamelCase__				,							UpperCamelCase__		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= time.time()

													# parser.add_argument('--eval_max_gen_length', type=int, default=None, help='never generate more than n tokens')
													__SCREAMING_SNAKE_CASE									= self.model.generate(
													    batch['input_ids']				,							attention_mask=batch['attention_mask']				,							use_cache=UpperCamelCase__				,							decoder_start_token_id=self.decoder_start_token_id				,							num_beams=self.eval_beams				,							max_length=self.eval_max_length				,							)
													__SCREAMING_SNAKE_CASE									= (time.time() - ta) / batch['''input_ids'''].shape[0]
													__SCREAMING_SNAKE_CASE									= self.ids_to_clean_text(UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= self.ids_to_clean_text(batch['labels']		)
													__SCREAMING_SNAKE_CASE									= self._step(UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= dict(zip(self.loss_names				,							UpperCamelCase__		)		)
													__SCREAMING_SNAKE_CASE									= self.calc_generative_metrics(UpperCamelCase__				,							UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= np.mean(lmap(UpperCamelCase__				,							UpperCamelCase__		)		)
													base_metrics.update(gen_time=UpperCamelCase__				,							gen_len=UpperCamelCase__				,							preds=UpperCamelCase__				,							target=UpperCamelCase__				,							**UpperCamelCase__		)
													return base_metrics






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													return self._generative_step(UpperCamelCase__		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													return self.validation_epoch_end(UpperCamelCase__				,							prefix='test'		)






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.n_obs[type_path]
													__SCREAMING_SNAKE_CASE									= self.target_lens[type_path]
													__SCREAMING_SNAKE_CASE									= self.dataset_class(
													    self.tokenizer				,							type_path=UpperCamelCase__				,							n_obs=UpperCamelCase__				,							max_target_length=UpperCamelCase__				,							**self.dataset_kwargs				,							)
													return dataset






						def 	_A     (   self				,							_A				,							_A				,							_A = False		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.get_dataset(UpperCamelCase__		)

													if self.hparams.sortish_sampler and type_path != "test" and type_path != "val":
																				__SCREAMING_SNAKE_CASE									= dataset.make_sortish_sampler(UpperCamelCase__				,							distributed=self.hparams.gpus > 1		)
																				return DataLoader(
																				    UpperCamelCase__				,							batch_size=UpperCamelCase__				,							collate_fn=dataset.collate_fn				,							shuffle=UpperCamelCase__				,							num_workers=self.num_workers				,							sampler=UpperCamelCase__				,							)

													elif self.hparams.max_tokens_per_batch is not None and type_path != "test" and type_path != "val":
																				__SCREAMING_SNAKE_CASE									= dataset.make_dynamic_sampler(
																				    self.hparams.max_tokens_per_batch				,							distributed=self.hparams.gpus > 1		)
																				return DataLoader(
																				    UpperCamelCase__				,							batch_sampler=UpperCamelCase__				,							collate_fn=dataset.collate_fn				,							num_workers=self.num_workers				,							)
													else:
																				return DataLoader(
																				    UpperCamelCase__				,							batch_size=UpperCamelCase__				,							collate_fn=dataset.collate_fn				,							shuffle=UpperCamelCase__				,							num_workers=self.num_workers				,							sampler=UpperCamelCase__				,							)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.get_dataloader('train'				,							batch_size=self.hparams.train_batch_size				,							shuffle=UpperCamelCase__		)
													return dataloader






						def 	_A     (   self		):







													'''simple docstring'''

													return self.get_dataloader('val'				,							batch_size=self.hparams.eval_batch_size		)






						def 	_A     (   self		):







													'''simple docstring'''

													return self.get_dataloader('test'				,							batch_size=self.hparams.eval_batch_size		)






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

													BaseTransformer.add_model_specific_args(UpperCamelCase__				,							UpperCamelCase__		)
													add_generic_args(UpperCamelCase__				,							UpperCamelCase__		)
													parser.add_argument(
													    '--max_source_length'				,							default=1_024				,							type=UpperCamelCase__				,							help=(
													        'The maximum total input sequence length after tokenization. Sequences longer '
													        'than this will be truncated, sequences shorter will be padded.'
													    )				,							)
													parser.add_argument(
													    '--max_target_length'				,							default=56				,							type=UpperCamelCase__				,							help=(
													        'The maximum total input sequence length after tokenization. Sequences longer '
													        'than this will be truncated, sequences shorter will be padded.'
													    )				,							)
													parser.add_argument(
													    '--val_max_target_length'				,							default=142				,							type=UpperCamelCase__				,							help=(
													        'The maximum total input sequence length after tokenization. Sequences longer '
													        'than this will be truncated, sequences shorter will be padded.'
													    )				,							)
													parser.add_argument(
													    '--test_max_target_length'				,							default=142				,							type=UpperCamelCase__				,							help=(
													        'The maximum total input sequence length after tokenization. Sequences longer '
													        'than this will be truncated, sequences shorter will be padded.'
													    )				,							)
													parser.add_argument('--freeze_encoder'				,							action='store_true'		)
													parser.add_argument('--freeze_embeds'				,							action='store_true'		)
													parser.add_argument('--sortish_sampler'				,							action='store_true'				,							default=UpperCamelCase__		)
													parser.add_argument('--overwrite_output_dir'				,							action='store_true'				,							default=UpperCamelCase__		)
													parser.add_argument('--max_tokens_per_batch'				,							type=UpperCamelCase__				,							default=UpperCamelCase__		)
													parser.add_argument('--logger_name'				,							type=UpperCamelCase__				,							choices=['default', 'wandb', 'wandb_shared']				,							default='default'		)
													parser.add_argument('--n_train'				,							type=UpperCamelCase__				,							default=-1				,							required=UpperCamelCase__				,							help='# examples. -1 means use all.'		)
													parser.add_argument('--n_val'				,							type=UpperCamelCase__				,							default=500				,							required=UpperCamelCase__				,							help='# examples. -1 means use all.'		)
													parser.add_argument('--n_test'				,							type=UpperCamelCase__				,							default=-1				,							required=UpperCamelCase__				,							help='# examples. -1 means use all.'		)
													parser.add_argument(
													    '--task'				,							type=UpperCamelCase__				,							default='summarization'				,							required=UpperCamelCase__				,							help='# examples. -1 means use all.'		)
													parser.add_argument('--label_smoothing'				,							type=UpperCamelCase__				,							default=0.0				,							required=UpperCamelCase__		)
													parser.add_argument('--src_lang'				,							type=UpperCamelCase__				,							default=''				,							required=UpperCamelCase__		)
													parser.add_argument('--tgt_lang'				,							type=UpperCamelCase__				,							default=''				,							required=UpperCamelCase__		)
													parser.add_argument('--eval_beams'				,							type=UpperCamelCase__				,							default=UpperCamelCase__				,							required=UpperCamelCase__		)
													parser.add_argument(
													    '--val_metric'				,							type=UpperCamelCase__				,							default=UpperCamelCase__				,							required=UpperCamelCase__				,							choices=['bleu', 'rouge2', 'loss', None]		)
													parser.add_argument('--eval_max_gen_length'				,							type=UpperCamelCase__				,							default=UpperCamelCase__				,							help='never generate more than n tokens'		)
													parser.add_argument('--save_top_k'				,							type=UpperCamelCase__				,							default=1				,							required=UpperCamelCase__				,							help='How many checkpoints to save'		)
													parser.add_argument(
													    '--early_stopping_patience'				,							type=UpperCamelCase__				,							default=-1				,							required=UpperCamelCase__				,							help=(
													        '-1 means never early stop. early_stopping_patience is measured in validation checks, not epochs. So'
													        ' val_check_interval will effect it.'
													    )				,							)
													return parser







class        UpperCAmelCase_  (       __SCREAMING_SNAKE_CASE	):

						'''simple docstring'''




						UpperCamelCase__      :			str      =  '''translation'''
						UpperCamelCase__      :			List[Any]      =  ['''loss''']
						UpperCamelCase__      :			List[str]      =  ['''bleu''']
						UpperCamelCase__      :			List[Any]      =  '''bleu'''






						def __init__(   self				,							_A				,							**_A		):







													'''simple docstring'''

													super().__init__(UpperCamelCase__				,							**UpperCamelCase__		)
													__SCREAMING_SNAKE_CASE									= hparams.src_lang
													__SCREAMING_SNAKE_CASE									= hparams.tgt_lang






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													return calculate_bleu(UpperCamelCase__				,							UpperCamelCase__		)







def      __lowercase       (			a__							,       a__=None       )    ->			SummarizationModule:
							Path(args.output_dir       ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__       )
							check_output_dir(SCREAMING_SNAKE_CASE__							,       expected_items=3       )

							if model is None:
														if "summarization" in args.task:
																					__SCREAMING_SNAKE_CASE									= SummarizationModule(SCREAMING_SNAKE_CASE__       )
														else:
																					__SCREAMING_SNAKE_CASE									= TranslationModule(SCREAMING_SNAKE_CASE__       )
							__SCREAMING_SNAKE_CASE									= Path(args.data_dir       ).name
							if (
							    args.logger_name == "default"
							    or args.fast_dev_run
							    or str(args.output_dir       ).startswith('/tmp'       )
							    or str(args.output_dir       ).startswith('/var'       )
							):
														__SCREAMING_SNAKE_CASE									= True  # don't pollute wandb logs unnecessarily
							elif args.logger_name == "wandb":
														from pytorch_lightning.loggers import WandbLogger

														__SCREAMING_SNAKE_CASE									= os.environ.get('WANDB_PROJECT'							,       SCREAMING_SNAKE_CASE__       )
														__SCREAMING_SNAKE_CASE									= WandbLogger(name=model.output_dir.name							,       project=SCREAMING_SNAKE_CASE__       )

							elif args.logger_name == "wandb_shared":
														from pytorch_lightning.loggers import WandbLogger

														__SCREAMING_SNAKE_CASE									= WandbLogger(name=model.output_dir.name							,       project=f"""hf_{dataset}"""       )

							if args.early_stopping_patience >= 0:
														__SCREAMING_SNAKE_CASE									= get_early_stopping_callback(model.val_metric							,       args.early_stopping_patience       )
							else:
														__SCREAMING_SNAKE_CASE									= False

							__SCREAMING_SNAKE_CASE									= args.val_metric == '''loss'''
							__SCREAMING_SNAKE_CASE									= generic_train(
							    SCREAMING_SNAKE_CASE__							,       SCREAMING_SNAKE_CASE__							,       logging_callback=SeqaSeqLoggingCallback()							,       checkpoint_callback=get_checkpoint_callback(
							        args.output_dir							,       model.val_metric							,       args.save_top_k							,       SCREAMING_SNAKE_CASE__       )							,       early_stopping_callback=SCREAMING_SNAKE_CASE__							,       logger=SCREAMING_SNAKE_CASE__							,       )
							pickle_save(model.hparams							,       model.output_dir / 'hparams.pkl'       )
							if not args.do_predict:
														return model

							__SCREAMING_SNAKE_CASE									= ''''''
							__SCREAMING_SNAKE_CASE									= sorted(glob.glob(os.path.join(args.output_dir							,       '*.ckpt'       )							,       recursive=SCREAMING_SNAKE_CASE__       )       )
							if checkpoints:
														__SCREAMING_SNAKE_CASE									= checkpoints[-1]
														__SCREAMING_SNAKE_CASE									= checkpoints[-1]
							trainer.logger.log_hyperparams(model.hparams       )

							# test() without a model tests using the best checkpoint automatically
							trainer.test()
							return model


if __name__ == "__main__":
			lowerCAmelCase__		:					Tuple							=argparse.ArgumentParser()
			lowerCAmelCase__		:					str							=pl.Trainer.add_argparse_args(parser)
			lowerCAmelCase__		:					Union[str, Any]							=SummarizationModule.add_model_specific_args(parser, os.getcwd())

			lowerCAmelCase__		:					List[Any]							=parser.parse_args()

			main(args)











import gc
import random
import unittest

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

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
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, skip_mps

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


enable_full_determinism()

class        UpperCAmelCase_  (       UpperCamelCase_   ,   UpperCamelCase_   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			List[str]      =  CycleDiffusionPipeline
						UpperCamelCase__      :			int      =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
						    '''negative_prompt''',
						    '''height''',
						    '''width''',
						    '''negative_prompt_embeds''',
						}
						UpperCamelCase__      :			Union[str, Any]      =  PipelineTesterMixin.required_optional_params - {'''latents'''}
						UpperCamelCase__      :			List[str]      =  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''}	)
						UpperCamelCase__      :			Optional[int]      =  IMAGE_TO_IMAGE_IMAGE_PARAMS
						UpperCamelCase__      :			str      =  IMAGE_TO_IMAGE_IMAGE_PARAMS






						def 	_A     (   self		):







													'''simple docstring'''

													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= 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				,							)
													__SCREAMING_SNAKE_CASE									= DDIMScheduler(
													    beta_start=0.0_0_0_8_5				,							beta_end=0.0_1_2				,							beta_schedule='scaled_linear'				,							num_train_timesteps=1_000				,							clip_sample=_A				,							set_alpha_to_one=_A				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= 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				,							)
													torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= CLIPTextConfig(
													    bos_token_id=0				,							eos_token_id=2				,							hidden_size=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				,							)
													__SCREAMING_SNAKE_CASE									= CLIPTextModel(_A		)
													__SCREAMING_SNAKE_CASE									= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

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






						def 	_A     (   self				,							_A				,							_A=0		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= floats_tensor((1, 3, 32, 32)				,							rng=random.Random(_A		)		).to(_A		)
													__SCREAMING_SNAKE_CASE									= image / 2 + 0.5
													if str(_A		).startswith('mps'		):
																				__SCREAMING_SNAKE_CASE									= torch.manual_seed(_A		)
													else:
																				__SCREAMING_SNAKE_CASE									= torch.Generator(device=_A		).manual_seed(_A		)
													__SCREAMING_SNAKE_CASE									= {
													    'prompt': 'An astronaut riding an elephant',
													    'source_prompt': 'An astronaut riding a horse',
													    'image': image,
													    'generator': generator,
													    'num_inference_steps': 2,
													    'eta': 0.1,
													    'strength': 0.8,
													    'guidance_scale': 3,
													    'source_guidance_scale': 1,
													    'output_type': 'numpy',
													}
													return inputs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 'cpu'  # ensure determinism for the device-dependent torch.Generator

													__SCREAMING_SNAKE_CASE									= self.get_dummy_components()
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline(**_A		)
													__SCREAMING_SNAKE_CASE									= pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_dummy_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		)
													__SCREAMING_SNAKE_CASE									= output.images

													__SCREAMING_SNAKE_CASE									= images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.4_4_5_9, 0.4_9_4_3, 0.4_5_4_4, 0.6_6_4_3, 0.5_4_7_4, 0.4_3_2_7, 0.5_7_0_1, 0.5_9_5_9, 0.5_1_7_9]		)

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






						@unittest.skipIf(torch_device != 'cuda'				,							'This test requires a GPU'		)
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.get_dummy_components()
													for name, module in components.items():
																				if hasattr(_A				,							'half'		):
																											__SCREAMING_SNAKE_CASE									= module.half()
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline(**_A		)
													__SCREAMING_SNAKE_CASE									= pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)

													__SCREAMING_SNAKE_CASE									= self.get_dummy_inputs(_A		)
													__SCREAMING_SNAKE_CASE									= pipe(**_A		)
													__SCREAMING_SNAKE_CASE									= output.images

													__SCREAMING_SNAKE_CASE									= images[0, -3:, -3:, -1]

													assert images.shape == (1, 32, 32, 3)
													__SCREAMING_SNAKE_CASE									= np.array([0.3_5_0_6, 0.4_5_4_3, 0.4_4_6, 0.4_5_7_5, 0.5_1_9_5, 0.4_1_5_5, 0.5_2_7_3, 0.5_1_8, 0.4_1_1_6]		)

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






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_save_load_local()






						@unittest.skip('non-deterministic pipeline'		)
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_inference_batch_single_identical()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_dict_tuple_outputs_equivalent()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_save_load_optional_components()






						@skip_mps
						def 	_A     (   self		):







													'''simple docstring'''

													return super().test_attention_slicing_forward_pass()







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

						'''simple docstring'''




						def 	_A     (   self		):







													'''simple docstring'''

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






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/cycle-diffusion/black_colored_car.png'		)
													__SCREAMING_SNAKE_CASE									= load_numpy(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'		)
													__SCREAMING_SNAKE_CASE									= init_image.resize((512, 512)		)

													__SCREAMING_SNAKE_CASE									= 'CompVis/stable-diffusion-v1-4'
													__SCREAMING_SNAKE_CASE									= DDIMScheduler.from_pretrained(_A				,							subfolder='scheduler'		)
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline.from_pretrained(
													    _A				,							scheduler=_A				,							safety_checker=_A				,							torch_dtype=torch.floataa				,							revision='fp16'		)

													pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)
													pipe.enable_attention_slicing()

													__SCREAMING_SNAKE_CASE									= 'A black colored car'
													__SCREAMING_SNAKE_CASE									= 'A blue colored car'

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= pipe(
													    prompt=_A				,							source_prompt=_A				,							image=_A				,							num_inference_steps=100				,							eta=0.1				,							strength=0.8_5				,							guidance_scale=3				,							source_guidance_scale=1				,							generator=_A				,							output_type='np'				,							)
													__SCREAMING_SNAKE_CASE									= output.images

													# the values aren't exactly equal, but the images look the same visually
													assert np.abs(image - expected_image		).max() < 5e-1






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/cycle-diffusion/black_colored_car.png'		)
													__SCREAMING_SNAKE_CASE									= load_numpy(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'		)
													__SCREAMING_SNAKE_CASE									= init_image.resize((512, 512)		)

													__SCREAMING_SNAKE_CASE									= 'CompVis/stable-diffusion-v1-4'
													__SCREAMING_SNAKE_CASE									= DDIMScheduler.from_pretrained(_A				,							subfolder='scheduler'		)
													__SCREAMING_SNAKE_CASE									= CycleDiffusionPipeline.from_pretrained(_A				,							scheduler=_A				,							safety_checker=_A		)

													pipe.to(_A		)
													pipe.set_progress_bar_config(disable=_A		)
													pipe.enable_attention_slicing()

													__SCREAMING_SNAKE_CASE									= 'A black colored car'
													__SCREAMING_SNAKE_CASE									= 'A blue colored car'

													__SCREAMING_SNAKE_CASE									= torch.manual_seed(0		)
													__SCREAMING_SNAKE_CASE									= pipe(
													    prompt=_A				,							source_prompt=_A				,							image=_A				,							num_inference_steps=100				,							eta=0.1				,							strength=0.8_5				,							guidance_scale=3				,							source_guidance_scale=1				,							generator=_A				,							output_type='np'				,							)
													__SCREAMING_SNAKE_CASE									= output.images

													assert np.abs(image - expected_image		).max() < 2e-2






