


'''simple docstring'''



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

import datasets
import numpy as np
import tensorflow as tf

from transformers import (
    AutoConfig,
    AutoTokenizer,
    EvalPrediction,
    HfArgumentParser,
    PreTrainedTokenizer,
    TFAutoModelForSequenceClassification,
    TFTrainer,
    TFTrainingArguments,
)
from transformers.utils import logging as hf_logging


hf_logging.set_verbosity_info()
hf_logging.enable_default_handler()
hf_logging.enable_explicit_format()



def      UpperCAmelCase__   (      UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							str ,       UpperCAmelCase_       :							PreTrainedTokenizer ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							Optional[int] = None ,       )	->						Tuple:
     __lowerCamelCase  :      Any														=						{}

     if train_file is not None:
          __lowerCamelCase  :      int														=						[train_file]
     if eval_file is not None:
          __lowerCamelCase  :      Any														=						[eval_file]
     if test_file is not None:
          __lowerCamelCase  :      Any														=						[test_file]

     __lowerCamelCase  :      Any														=						datasets.load_dataset('csv' ,       data_files=UpperCAmelCase_				)
     __lowerCamelCase  :      Dict														=						list(ds[list(files.keys()				)[0]].features.keys()				)
     __lowerCamelCase  :      Union[str, Any]														=						features_name.pop(UpperCAmelCase_				)
     __lowerCamelCase  :      Optional[Any]														=						list(set(ds[list(files.keys()				)[0]][label_name]				)				)
     __lowerCamelCase  :      Union[str, Any]														=						{label: i for i, label in enumerate(UpperCAmelCase_				)}
     __lowerCamelCase  :      Optional[Any]														=						tokenizer.model_input_names
     __lowerCamelCase  :      Optional[int]														=						{}

     if len(UpperCAmelCase_				) == 1:
          for k in files.keys():
               __lowerCamelCase  :      str														=						ds[k].map(
                   lambda UpperCAmelCase_				: tokenizer.batch_encode_plus(
                       example[features_name[0]] ,       truncation=UpperCAmelCase_ ,       max_length=UpperCAmelCase_ ,       padding='max_length'				) ,       batched=UpperCAmelCase_ ,       )
     elif len(UpperCAmelCase_				) == 2:
          for k in files.keys():
               __lowerCamelCase  :      Union[str, Any]														=						ds[k].map(
                   lambda UpperCAmelCase_				: tokenizer.batch_encode_plus(
                       (example[features_name[0]], example[features_name[1]]) ,       truncation=UpperCAmelCase_ ,       max_length=UpperCAmelCase_ ,       padding='max_length' ,       ) ,       batched=UpperCAmelCase_ ,       )

     def gen_train():
          for ex in transformed_ds[datasets.Split.TRAIN]:
               __lowerCamelCase  :      Any														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      Dict														=						labelaid[ex[label_name]]
               yield (d, label)

     def gen_val():
          for ex in transformed_ds[datasets.Split.VALIDATION]:
               __lowerCamelCase  :      List[Any]														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      int														=						labelaid[ex[label_name]]
               yield (d, label)

     def gen_test():
          for ex in transformed_ds[datasets.Split.TEST]:
               __lowerCamelCase  :      Optional[int]														=						{k: v for k, v in ex.items() if k in input_names}
               __lowerCamelCase  :      List[str]														=						labelaid[ex[label_name]]
               yield (d, label)

     __lowerCamelCase  :      List[Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.TRAIN in transformed_ds
         else None
     )

     if train_ds is not None:
          __lowerCamelCase  :      Optional[Any]														=						train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN]				)				)				)

     __lowerCamelCase  :      Union[str, Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.VALIDATION in transformed_ds
         else None
     )

     if val_ds is not None:
          __lowerCamelCase  :      Optional[int]														=						val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION]				)				)				)

     __lowerCamelCase  :      List[Any]														=						(
         tf.data.Dataset.from_generator(
             UpperCAmelCase_ ,       ({k: tf.intaa for k in input_names}, tf.intaa) ,       ({k: tf.TensorShape([None]				) for k in input_names}, tf.TensorShape([]				)) ,       )
         if datasets.Split.TEST in transformed_ds
         else None
     )

     if test_ds is not None:
          __lowerCamelCase  :      List[str]														=						test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST]				)				)				)

     return train_ds, val_ds, test_ds, labelaid


A__						:   int				=    logging.getLogger(__name__)





@dataclass
class   UpperCAmelCase_    :





    """simple docstring"""






    lowerCamelCase    :   int					=     field(metadata={'help': 'Which column contains the label'}    )
    lowerCamelCase    :   str					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the training file'}    )
    lowerCamelCase    :   Optional[str]					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the development file'}    )
    lowerCamelCase    :   Optional[str]					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'The path of the test file'}    )
    lowerCamelCase    :   int					=     field(
        default=1_2_8   ,						metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }   ,						)
    lowerCamelCase    :   bool					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Overwrite the cached training and evaluation sets'}    )







@dataclass
class   UpperCAmelCase_    :





    """simple docstring"""






    lowerCamelCase    :   str					=     field(
        metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}    )
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Pretrained config name or path if not the same as model_name'}    )
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}    )
    lowerCamelCase    :   bool					=     field(default=_UpperCAmelCase   ,						metadata={'help': 'Set this flag to use fast tokenization.'}    )
    # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
    # or just modify its tokenizer_config.json.
    lowerCamelCase    :   Optional[str]					=     field(
        default=_UpperCAmelCase   ,						metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}   ,						)







def      UpperCAmelCase__   (      )	->						str:
     # See all possible arguments in src/transformers/training_args.py
     # or by passing the --help flag to this script.
     # We now keep distinct sets of args, for a cleaner separation of concerns.
     __lowerCamelCase  :      int														=						HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments)				)
     __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      Optional[Any]														=						parser.parse_args_into_dataclasses()

     if (
         os.path.exists(training_args.output_dir				)
         and os.listdir(training_args.output_dir				)
         and training_args.do_train
         and not training_args.overwrite_output_dir
     ):
          raise ValueError(
              F'Output directory ({training_args.output_dir}) already exists and is not empty. Use'
              ' --overwrite_output_dir to overcome.'				)

     # Setup logging
     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,       datefmt='%m/%d/%Y %H:%M:%S' ,       level=logging.INFO ,       )
     logger.info(
         F'n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1				)}, '
         F'16-bits training: {training_args.fpaa}'				)
     logger.info(F'Training/evaluation parameters {training_args}'				)

     # Load pretrained model and tokenizer
     #
     # Distributed training:
     # The .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.

     __lowerCamelCase  :      Optional[Any]														=						AutoTokenizer.from_pretrained(
         model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path ,       cache_dir=model_args.cache_dir ,       )

     __lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase							,			__lowerCamelCase  :      int														=						get_tfds(
         train_file=data_args.train_file ,       eval_file=data_args.dev_file ,       test_file=data_args.test_file ,       tokenizer=UpperCAmelCase_ ,       label_column_id=data_args.label_column_id ,       max_seq_length=data_args.max_seq_length ,       )

     __lowerCamelCase  :      Any														=						AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path ,       num_labels=len(UpperCAmelCase_				) ,       labelaid=UpperCAmelCase_ ,       idalabel={id: label for label, id in labelaid.items()} ,       finetuning_task='text-classification' ,       cache_dir=model_args.cache_dir ,       )

     with training_args.strategy.scope():
          __lowerCamelCase  :      Optional[int]														=						TFAutoModelForSequenceClassification.from_pretrained(
              model_args.model_name_or_path ,       from_pt=bool('.bin' in model_args.model_name_or_path				) ,       config=UpperCAmelCase_ ,       cache_dir=model_args.cache_dir ,       )

     def compute_metrics(UpperCAmelCase_       :							EvalPrediction				) -> Dict:
          __lowerCamelCase  :      Any														=						np.argmax(p.predictions ,       axis=1				)

          return {"acc": (preds == p.label_ids).mean()}

     # Initialize our Trainer
     __lowerCamelCase  :      int														=						TFTrainer(
         model=UpperCAmelCase_ ,       args=UpperCAmelCase_ ,       train_dataset=UpperCAmelCase_ ,       eval_dataset=UpperCAmelCase_ ,       compute_metrics=UpperCAmelCase_ ,       )

     # Training
     if training_args.do_train:
          trainer.train()
          trainer.save_model()
          tokenizer.save_pretrained(training_args.output_dir				)

     # Evaluation
     __lowerCamelCase  :      Optional[Any]														=						{}
     if training_args.do_eval:
          logger.info('*** Evaluate ***'				)
          __lowerCamelCase  :      List[str]														=						trainer.evaluate()
          __lowerCamelCase  :      Optional[Any]														=						os.path.join(training_args.output_dir ,       'eval_results.txt'				)

          with open(UpperCAmelCase_ ,       'w'				) as writer:
               logger.info('***** Eval results *****'				)

               for key, value in result.items():
                    logger.info(F'  {key} = {value}'				)
                    writer.write(F'{key} = {value}\n'				)

               results.update(UpperCAmelCase_				)

     return results


if __name__ == "__main__":
      main()











import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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


enable_full_determinism()







class 				_a				(   unittest.TestCase					):

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

			@property
			def      __snake_case       (self					)       ->   int:
						UpperCAmelCase_:		str							      =     1
						UpperCAmelCase_:		Optional[int]							      =     3
						UpperCAmelCase_:		Optional[Any]							      =     (32, 32)

						UpperCAmelCase_:		int							      =     floats_tensor((batch_size, num_channels) + sizes,   rng=random.Random(0					)					).to(SCREAMING_SNAKE_CASE_					)
						return image

			@property
			def      __snake_case       (self					)       ->   str:
						torch.manual_seed(0					)
						UpperCAmelCase_:		Optional[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,   )
						return model

			@property
			def      __snake_case       (self					)       ->   Optional[int]:
						torch.manual_seed(0					)
						UpperCAmelCase_:		Union[str, 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,   )
						return model

			@property
			def      __snake_case       (self					)       ->   Tuple:
						torch.manual_seed(0					)
						UpperCAmelCase_:		List[Any]							      =     RobertaSeriesConfig(
						    hidden_size=32,   project_dim=32,   intermediate_size=37,   layer_norm_eps=1E-05,   num_attention_heads=4,   num_hidden_layers=5,   pad_token_id=1,   vocab_size=5006,   )
						return RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE_					)

			@property
			def      __snake_case       (self					)       ->   Union[str, Any]:
						def extract(*SCREAMING_SNAKE_CASE_,   **SCREAMING_SNAKE_CASE_					):







									class 				_a				:

												def __init__(self					)       ->   Tuple:
															UpperCAmelCase_:		Any							      =     torch.ones([0]					)

												def      __snake_case       (self,   SCREAMING_SNAKE_CASE_					)       ->   List[Any]:
															self.pixel_values.to(SCREAMING_SNAKE_CASE_					)
															return self






									return Out()

						return extract

			def      __snake_case       (self					)       ->   int:
						UpperCAmelCase_:		List[str]							      =     """cpu"""  # ensure determinism for the device-dependent torch.Generator
						UpperCAmelCase_:		Union[str, Any]							      =     self.dummy_cond_unet
						UpperCAmelCase_:		Any							      =     PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		List[Any]							      =     self.dummy_vae
						UpperCAmelCase_:		int							      =     self.dummy_text_encoder
						UpperCAmelCase_:		int							      =     XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""					)
						UpperCAmelCase_:		Tuple							      =     77

						UpperCAmelCase_:		Tuple							      =     self.dummy_image.to(SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		str							      =     init_image / 2 + 0.5

						# make sure here that pndm scheduler skips prk
						UpperCAmelCase_:		List[Any]							      =     AltDiffusionImgaImgPipeline(
						    unet=SCREAMING_SNAKE_CASE_,   scheduler=SCREAMING_SNAKE_CASE_,   vae=SCREAMING_SNAKE_CASE_,   text_encoder=SCREAMING_SNAKE_CASE_,   tokenizer=SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   feature_extractor=self.dummy_extractor,   )
						UpperCAmelCase_:		Dict							      =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,   do_normalize=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe.to(SCREAMING_SNAKE_CASE_					)
						alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		str							      =     """A painting of a squirrel eating a burger"""
						UpperCAmelCase_:		List[str]							      =     torch.Generator(device=SCREAMING_SNAKE_CASE_					).manual_seed(0					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   guidance_scale=6.0,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   )

						UpperCAmelCase_:		List[str]							      =     output.images

						UpperCAmelCase_:		Optional[Any]							      =     torch.Generator(device=SCREAMING_SNAKE_CASE_					).manual_seed(0					)
						UpperCAmelCase_:		Any							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   guidance_scale=6.0,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   return_dict=SCREAMING_SNAKE_CASE_,   )[0]

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

						assert image.shape == (1, 32, 32, 3)
						UpperCAmelCase_:		Tuple							      =     np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]					)

						assert np.abs(image_slice.flatten() - expected_slice					).max() < 5E-3
						assert np.abs(image_from_tuple_slice.flatten() - expected_slice					).max() < 5E-3

			@unittest.skipIf(torch_device != """cuda""",   """This test requires a GPU"""					)
			def      __snake_case       (self					)       ->   str:
						UpperCAmelCase_:		List[Any]							      =     self.dummy_cond_unet
						UpperCAmelCase_:		List[Any]							      =     PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Any							      =     self.dummy_vae
						UpperCAmelCase_:		Optional[Any]							      =     self.dummy_text_encoder
						UpperCAmelCase_:		Dict							      =     XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""					)
						UpperCAmelCase_:		Union[str, Any]							      =     77

						UpperCAmelCase_:		Tuple							      =     self.dummy_image.to(SCREAMING_SNAKE_CASE_					)

						# put models in fp16
						UpperCAmelCase_:		Optional[Any]							      =     unet.half()
						UpperCAmelCase_:		Any							      =     vae.half()
						UpperCAmelCase_:		str							      =     bert.half()

						# make sure here that pndm scheduler skips prk
						UpperCAmelCase_:		Optional[int]							      =     AltDiffusionImgaImgPipeline(
						    unet=SCREAMING_SNAKE_CASE_,   scheduler=SCREAMING_SNAKE_CASE_,   vae=SCREAMING_SNAKE_CASE_,   text_encoder=SCREAMING_SNAKE_CASE_,   tokenizer=SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   feature_extractor=self.dummy_extractor,   )
						UpperCAmelCase_:		Optional[Any]							      =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor,   do_normalize=SCREAMING_SNAKE_CASE_					)
						UpperCAmelCase_:		Any							      =     alt_pipe.to(SCREAMING_SNAKE_CASE_					)
						alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)

						UpperCAmelCase_:		Any							      =     """A painting of a squirrel eating a burger"""
						UpperCAmelCase_:		Optional[Any]							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		Optional[int]							      =     alt_pipe(
						    [prompt],   generator=SCREAMING_SNAKE_CASE_,   num_inference_steps=2,   output_type="""np""",   image=SCREAMING_SNAKE_CASE_,   ).images

						assert image.shape == (1, 32, 32, 3)

			@unittest.skipIf(torch_device != """cuda""",   """This test requires a GPU"""					)
			def      __snake_case       (self					)       ->   Tuple:
						UpperCAmelCase_:		Optional[Any]							      =     load_image(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/img2img/sketch-mountains-input.jpg"""					)
						# resize to resolution that is divisible by 8 but not 16 or 32
						UpperCAmelCase_:		List[Any]							      =     init_image.resize((760, 504)					)

						UpperCAmelCase_:		Tuple							      =     """BAAI/AltDiffusion"""
						UpperCAmelCase_:		Tuple							      =     AltDiffusionImgaImgPipeline.from_pretrained(
						    SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   )
						pipe.to(SCREAMING_SNAKE_CASE_					)
						pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)
						pipe.enable_attention_slicing()

						UpperCAmelCase_:		Tuple							      =     """A fantasy landscape, trending on artstation"""

						UpperCAmelCase_:		Optional[int]							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		int							      =     pipe(
						    prompt=SCREAMING_SNAKE_CASE_,   image=SCREAMING_SNAKE_CASE_,   strength=0.7_5,   guidance_scale=7.5,   generator=SCREAMING_SNAKE_CASE_,   output_type="""np""",   )
						UpperCAmelCase_:		Dict							      =     output.images[0]

						UpperCAmelCase_:		Tuple							      =     image[255:258, 383:386, -1]

						assert image.shape == (504, 760, 3)
						UpperCAmelCase_:		str							      =     np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]					)

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







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

			def      __snake_case       (self					)       ->   int:
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()

			def      __snake_case       (self					)       ->   Union[str, Any]:
						UpperCAmelCase_:		Optional[Any]							      =     load_image(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
						    """/img2img/sketch-mountains-input.jpg"""					)
						UpperCAmelCase_:		Optional[Any]							      =     init_image.resize((768, 512)					)
						UpperCAmelCase_:		Union[str, Any]							      =     load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""					)

						UpperCAmelCase_:		List[str]							      =     """BAAI/AltDiffusion"""
						UpperCAmelCase_:		int							      =     AltDiffusionImgaImgPipeline.from_pretrained(
						    SCREAMING_SNAKE_CASE_,   safety_checker=SCREAMING_SNAKE_CASE_,   )
						pipe.to(SCREAMING_SNAKE_CASE_					)
						pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_					)
						pipe.enable_attention_slicing()

						UpperCAmelCase_:		Dict							      =     """A fantasy landscape, trending on artstation"""

						UpperCAmelCase_:		int							      =     torch.manual_seed(0					)
						UpperCAmelCase_:		int							      =     pipe(
						    prompt=SCREAMING_SNAKE_CASE_,   image=SCREAMING_SNAKE_CASE_,   strength=0.7_5,   guidance_scale=7.5,   generator=SCREAMING_SNAKE_CASE_,   output_type="""np""",   )
						UpperCAmelCase_:		Dict							      =     output.images[0]

						assert image.shape == (512, 768, 3)
						# img2img is flaky across GPUs even in fp32, so using MAE here
						assert np.abs(expected_image - image					).max() < 1E-2






