





"""simple docstring"""
import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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 (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()







class       a							(   lowercase__   , lowercase__   , lowercase__   , unittest.TestCase  ):
 snake_case__             =       StableDiffusionControlNetImgaImgPipeline
 snake_case__             =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
 snake_case__             =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 snake_case__             =       IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''}  )
 snake_case__             =       IMAGE_TO_IMAGE_IMAGE_PARAMS



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  torch.manual_seed(0     )
  lowerCAmelCase    				= 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				,       )
  torch.manual_seed(0     )
  lowerCAmelCase    				= ControlNetModel(
      block_out_channels=(32, 64)				,       layers_per_block=2				,       in_channels=4				,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,       cross_attention_dim=32				,       conditioning_embedding_out_channels=(16, 32)				,       )
  torch.manual_seed(0     )
  lowerCAmelCase    				= DDIMScheduler(
      beta_start=0.00_085				,       beta_end=0.012				,       beta_schedule='scaled_linear'				,       clip_sample=UpperCAmelCase__				,       set_alpha_to_one=UpperCAmelCase__				,       )
  torch.manual_seed(0     )
  lowerCAmelCase    				= 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     )
  lowerCAmelCase    				= 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=10_00				,       )
  lowerCAmelCase    				= CLIPTextModel(UpperCAmelCase__     )
  lowerCAmelCase    				= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

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



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(UpperCAmelCase__     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(UpperCAmelCase__     )
  else:
   lowerCAmelCase    				= torch.Generator(device=UpperCAmelCase__     ).manual_seed(UpperCAmelCase__     )

  lowerCAmelCase    				= 2
  lowerCAmelCase    				= randn_tensor(
      (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)				,       generator=UpperCAmelCase__				,       device=torch.device(UpperCAmelCase__     )				,       )
  lowerCAmelCase    				= floats_tensor(control_image.shape				,       rng=random.Random(UpperCAmelCase__     )     ).to(UpperCAmelCase__     )
  lowerCAmelCase    				= image.cpu().permute(0				,       2				,       3				,       1     )[0]
  lowerCAmelCase    				= Image.fromarray(np.uinta(UpperCAmelCase__     )     ).convert('RGB'     ).resize((64, 64)     )
  lowerCAmelCase    				= {
      '''prompt''': '''A painting of a squirrel eating a burger''',
      '''generator''': generator,
      '''num_inference_steps''': 2,
      '''guidance_scale''': 6.0,
      '''output_type''': '''numpy''',
      '''image''': image,
      '''control_image''': control_image,
  }

  return inputs



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3     )



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







  """simple docstring"""






  self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_inference_batch_single_identical(expected_max_diff=2E-3     )







class       a							(   lowercase__   , lowercase__   , unittest.TestCase  ):
 snake_case__             =       StableDiffusionControlNetImgaImgPipeline
 snake_case__             =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
 snake_case__             =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 snake_case__             =       frozenset([]  )  # TO_DO: add image_params once refactored VaeImageProcessor.preprocess



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  torch.manual_seed(0     )
  lowerCAmelCase    				= 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				,       )
  torch.manual_seed(0     )

  def init_weights(_snake_case     ):
   if isinstance(UpperCAmelCase__				,       torch.nn.Convad     ):
    torch.nn.init.normal(m.weight     )
    m.bias.data.fill_(1.0     )

  lowerCAmelCase    				= ControlNetModel(
      block_out_channels=(32, 64)				,       layers_per_block=2				,       in_channels=4				,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,       cross_attention_dim=32				,       conditioning_embedding_out_channels=(16, 32)				,       )
  controlneta.controlnet_down_blocks.apply(UpperCAmelCase__     )

  torch.manual_seed(0     )
  lowerCAmelCase    				= ControlNetModel(
      block_out_channels=(32, 64)				,       layers_per_block=2				,       in_channels=4				,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,       cross_attention_dim=32				,       conditioning_embedding_out_channels=(16, 32)				,       )
  controlneta.controlnet_down_blocks.apply(UpperCAmelCase__     )

  torch.manual_seed(0     )
  lowerCAmelCase    				= DDIMScheduler(
      beta_start=0.00_085				,       beta_end=0.012				,       beta_schedule='scaled_linear'				,       clip_sample=UpperCAmelCase__				,       set_alpha_to_one=UpperCAmelCase__				,       )
  torch.manual_seed(0     )
  lowerCAmelCase    				= 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     )
  lowerCAmelCase    				= 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=10_00				,       )
  lowerCAmelCase    				= CLIPTextModel(UpperCAmelCase__     )
  lowerCAmelCase    				= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     )

  lowerCAmelCase    				= MultiControlNetModel([controlneta, controlneta]     )

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



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(UpperCAmelCase__     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(UpperCAmelCase__     )
  else:
   lowerCAmelCase    				= torch.Generator(device=UpperCAmelCase__     ).manual_seed(UpperCAmelCase__     )

  lowerCAmelCase    				= 2

  lowerCAmelCase    				= [
      randn_tensor(
          (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)				,       generator=UpperCAmelCase__				,       device=torch.device(UpperCAmelCase__     )				,       ),
      randn_tensor(
          (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)				,       generator=UpperCAmelCase__				,       device=torch.device(UpperCAmelCase__     )				,       ),
  ]

  lowerCAmelCase    				= floats_tensor(control_image[0].shape				,       rng=random.Random(UpperCAmelCase__     )     ).to(UpperCAmelCase__     )
  lowerCAmelCase    				= image.cpu().permute(0				,       2				,       3				,       1     )[0]
  lowerCAmelCase    				= Image.fromarray(np.uinta(UpperCAmelCase__     )     ).convert('RGB'     ).resize((64, 64)     )
  lowerCAmelCase    				= {
      '''prompt''': '''A painting of a squirrel eating a burger''',
      '''generator''': generator,
      '''num_inference_steps''': 2,
      '''guidance_scale''': 6.0,
      '''output_type''': '''numpy''',
      '''image''': image,
      '''control_image''': control_image,
  }

  return inputs



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.get_dummy_components()
  lowerCAmelCase    				= self.pipeline_class(**UpperCAmelCase__     )
  pipe.to(UpperCAmelCase__     )

  lowerCAmelCase    				= 10.0
  lowerCAmelCase    				= 4

  lowerCAmelCase    				= self.get_dummy_inputs(UpperCAmelCase__     )
  lowerCAmelCase    				= steps
  lowerCAmelCase    				= scale
  lowerCAmelCase    				= pipe(**UpperCAmelCase__     )[0]

  lowerCAmelCase    				= self.get_dummy_inputs(UpperCAmelCase__     )
  lowerCAmelCase    				= steps
  lowerCAmelCase    				= scale
  lowerCAmelCase    				= pipe(**UpperCAmelCase__				,       control_guidance_start=0.1				,       control_guidance_end=0.2     )[0]

  lowerCAmelCase    				= self.get_dummy_inputs(UpperCAmelCase__     )
  lowerCAmelCase    				= steps
  lowerCAmelCase    				= scale
  lowerCAmelCase    				= pipe(**UpperCAmelCase__				,       control_guidance_start=[0.1, 0.3]				,       control_guidance_end=[0.2, 0.7]     )[0]

  lowerCAmelCase    				= self.get_dummy_inputs(UpperCAmelCase__     )
  lowerCAmelCase    				= steps
  lowerCAmelCase    				= scale
  lowerCAmelCase    				= pipe(**UpperCAmelCase__				,       control_guidance_start=0.4				,       control_guidance_end=[0.5, 0.8]     )[0]

  # make sure that all outputs are different
  assert np.sum(np.abs(output_a - output_a     )     ) > 1E-3
  assert np.sum(np.abs(output_a - output_a     )     ) > 1E-3
  assert np.sum(np.abs(output_a - output_a     )     ) > 1E-3



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3     )



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







  """simple docstring"""






  self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_inference_batch_single_identical(expected_max_diff=2E-3     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= self.get_dummy_components()
  lowerCAmelCase    				= self.pipeline_class(**UpperCAmelCase__     )
  pipe.to(UpperCAmelCase__     )
  pipe.set_progress_bar_config(disable=UpperCAmelCase__     )
  with tempfile.TemporaryDirectory() as tmpdir:
   try:
    # save_pretrained is not implemented for Multi-ControlNet
    pipe.save_pretrained(UpperCAmelCase__     )
   except NotImplementedError:
    pass







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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






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



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  lowerCAmelCase    				= ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny'     )

  lowerCAmelCase    				= StableDiffusionControlNetImgaImgPipeline.from_pretrained(
      'runwayml/stable-diffusion-v1-5'				,       safety_checker=UpperCAmelCase__				,       controlnet=UpperCAmelCase__     )
  pipe.enable_model_cpu_offload()
  pipe.set_progress_bar_config(disable=UpperCAmelCase__     )

  lowerCAmelCase    				= torch.Generator(device='cpu'     ).manual_seed(0     )
  lowerCAmelCase    				= '''evil space-punk bird'''
  lowerCAmelCase    				= load_image(
      'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'     ).resize((5_12, 5_12)     )
  lowerCAmelCase    				= load_image(
      'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png'     ).resize((5_12, 5_12)     )

  lowerCAmelCase    				= pipe(
      UpperCAmelCase__				,       UpperCAmelCase__				,       control_image=UpperCAmelCase__				,       generator=UpperCAmelCase__				,       output_type='np'				,       num_inference_steps=50				,       strength=0.6				,       )

  lowerCAmelCase    				= output.images[0]

  assert image.shape == (5_12, 5_12, 3)

  lowerCAmelCase    				= load_numpy(
      'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy'     )

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








'''simple docstring'''





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

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCamelCase_    						=       logging.getLogger(__name__)






def 				_lowerCAmelCase			(   __magic_name__						:     List[Any]   , __magic_name__						:     str						)				->  Union[str, Any]:
						return (preds == labels).mean()





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    field(
				    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Pretrained config name or path if not the same as model_name'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}      )
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,							)





@dataclass
class 		__SCREAMING_SNAKE_CASE							:
				lowerCamelCase_		       =    field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()      )}      )
				lowerCamelCase_		       =    field(metadata={'help': 'Should contain the data files for the task.'}      )
				lowerCamelCase_		       =    field(
				    default=1_28						,							metadata={
				        'help': (
				            'The maximum total input sequence length after tokenization. Sequences longer '
				            'than this will be truncated, sequences shorter will be padded.'
				        )
				    }						,							)
				lowerCamelCase_		       =    field(
				    default=lowercase__						,							metadata={'help': 'Overwrite the cached training and evaluation sets'}      )






def 				_lowerCAmelCase			(   )				->  int:
						# 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.

						lowercase :							Dict    		=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
						lowercase		,	lowercase		,	lowercase :							List[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 if training_args.local_rank in [-1, 0] else logging.WARN   , )
						logger.warning(
						    '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''   , training_args.local_rank   , training_args.device   , training_args.n_gpu   , bool(training_args.local_rank != -1						)   , 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'''   , __magic_name__						)

						# Set seed
						set_seed(training_args.seed						)

						try:
												lowercase :							Any    		=processors[data_args.task_name]()
												lowercase :							Optional[int]    		=processor.get_labels()
												lowercase :							str    		=len(__magic_name__						)
						except KeyError:
												raise ValueError('''Task not found: %s''' % (data_args.task_name)						)

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

						lowercase :							List[str]    		=AutoConfig.from_pretrained(
						    model_args.config_name if model_args.config_name else model_args.model_name_or_path   , num_labels=__magic_name__   , finetuning_task=data_args.task_name   , cache_dir=model_args.cache_dir   , )
						lowercase :							int    		=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   , )
						lowercase :							Any    		=AutoModelForMultipleChoice.from_pretrained(
						    model_args.model_name_or_path   , from_tf=bool('''.ckpt''' in model_args.model_name_or_path						)   , config=__magic_name__   , cache_dir=model_args.cache_dir   , )

						# Get datasets
						lowercase :							int    		=(
						    MultipleChoiceDataset(
						        data_dir=data_args.data_dir   , tokenizer=__magic_name__   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , mode=Split.train   , )
						    if training_args.do_train
						    else None
						)
						lowercase :							Union[str, Any]    		=(
						    MultipleChoiceDataset(
						        data_dir=data_args.data_dir   , tokenizer=__magic_name__   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , mode=Split.dev   , )
						    if training_args.do_eval
						    else None
						)

						def compute_metrics(__magic_name__						:     EvalPrediction						) -> Dict:
												lowercase :							Dict    		=np.argmax(p.predictions   , axis=1						)
												return {"acc": simple_accuracy(__magic_name__   , p.label_ids						)}

						# Data collator
						lowercase :							List[str]    		=DataCollatorWithPadding(__magic_name__   , pad_to_multiple_of=8						) if training_args.fpaa else None

						# Initialize our Trainer
						lowercase :							Dict    		=Trainer(
						    model=__magic_name__   , args=__magic_name__   , train_dataset=__magic_name__   , eval_dataset=__magic_name__   , compute_metrics=__magic_name__   , data_collator=__magic_name__   , )

						# Training
						if training_args.do_train:
												trainer.train(
												    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path						) else None						)
												trainer.save_model()
												# For convenience, we also re-save the tokenizer to the same directory,
												# so that you can share your model easily on huggingface.co/models =)
												if trainer.is_world_master():
																		tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
						lowercase :							Optional[Any]    		={}
						if training_args.do_eval:
												logger.info('''*** Evaluate ***'''						)

												lowercase :							List[Any]    		=trainer.evaluate()

												lowercase :							Any    		=os.path.join(training_args.output_dir   , '''eval_results.txt'''						)
												if trainer.is_world_master():
																		with open(__magic_name__   , '''w'''						) as writer:
																								logger.info('''***** Eval results *****'''						)
																								for key, value in result.items():
																														logger.info('''  %s = %s'''   , __magic_name__   , __magic_name__						)
																														writer.write('''%s = %s\n''' % (key, value)						)

																								results.update(__magic_name__						)

						return results






def 				_lowerCAmelCase			(   __magic_name__						:     Any						)				->  Optional[Any]:
						# For xla_spawn (TPUs)
						main()


if __name__ == "__main__":
							main()





