




# This model implementation is heavily based on:

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,
    StableDiffusionControlNetInpaintPipeline,
    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 (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
    TEXT_TO_IMAGE_IMAGE_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()

class   UpperCAmelCase    (      A ,       A ,       A ,       unittest.TestCase ):
   __SCREAMING_SNAKE_CASE		:				str      					=       StableDiffusionControlNetInpaintPipeline
   __SCREAMING_SNAKE_CASE		:				Optional[Any]      					=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
   __SCREAMING_SNAKE_CASE		:				str      					=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
   __SCREAMING_SNAKE_CASE		:				Optional[Any]      					=       frozenset({"control_image"} )  # skip `image` and `mask` for now, only test for control_image
   __SCREAMING_SNAKE_CASE		:				List[str]      					=       TEXT_TO_IMAGE_IMAGE_PARAMS






   def 			_a    (						self :							List[str]  )->      List[str]:
     torch.manual_seed(0  )
     _lowercase:			List[str]      =     UNetaDConditionModel(
         block_out_channels=(32, 64)    ,       layers_per_block=2    ,       sample_size=32    ,       in_channels=9    ,       out_channels=4    ,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,       up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,       cross_attention_dim=32    ,       )
     torch.manual_seed(0  )
     _lowercase:			Tuple      =     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  )
     _lowercase:			Union[str, Any]      =     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  )
     _lowercase:			List[str]      =     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  )
     _lowercase:			Union[str, Any]      =     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    ,       )
     _lowercase:			Optional[Any]      =     CLIPTextModel(UpperCamelCase_  )
     _lowercase:			Tuple      =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

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






   def 			_a    (						self :							Optional[Any]    ,       UpperCamelCase_ :							Optional[Any]    ,       UpperCamelCase_ :							int=0  )->      Optional[Any]:
     if str(UpperCamelCase_  ).startswith('mps'  ):
       _lowercase:			Optional[int]      =     torch.manual_seed(UpperCamelCase_  )
     else:
       _lowercase:			Union[str, Any]      =     torch.Generator(device=UpperCamelCase_  ).manual_seed(UpperCamelCase_  )

     _lowercase:			Tuple      =     2
     _lowercase:			List[Any]      =     randn_tensor(
         (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor)    ,       generator=UpperCamelCase_    ,       device=torch.device(UpperCamelCase_  )    ,       )
     _lowercase:			List[Any]      =     floats_tensor((1, 3, 32, 32)    ,       rng=random.Random(UpperCamelCase_  )  ).to(UpperCamelCase_  )
     _lowercase:			List[str]      =     init_image.cpu().permute(0    ,       2    ,       3    ,       1  )[0]

     _lowercase:			Dict      =     Image.fromarray(np.uinta(UpperCamelCase_  )  ).convert('RGB'  ).resize((64, 64)  )
     _lowercase:			Dict      =     Image.fromarray(np.uinta(init_image + 4  )  ).convert('RGB'  ).resize((64, 64)  )

     _lowercase:			Optional[int]      =     {
         'prompt': 'A painting of a squirrel eating a burger',
         'generator': generator,
         'num_inference_steps': 2,
         'guidance_scale': 6.0,
         'output_type': 'numpy',
         'image': image,
         'mask_image': mask_image,
         'control_image': control_image,
     }

     return inputs






   def 			_a    (						self :							List[str]  )->      str:
     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 			_a    (						self :							Union[str, Any]  )->      Tuple:
     self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3  )






   def 			_a    (						self :							Optional[Any]  )->      Tuple:
     self._test_inference_batch_single_identical(expected_max_diff=2E-3  )

class   UpperCAmelCase    (      A ):
   __SCREAMING_SNAKE_CASE		:				Any      					=       StableDiffusionControlNetInpaintPipeline
   __SCREAMING_SNAKE_CASE		:				Tuple      					=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
   __SCREAMING_SNAKE_CASE		:				List[Any]      					=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
   __SCREAMING_SNAKE_CASE		:				Union[str, Any]      					=       frozenset([] )






   def 			_a    (						self :							Dict  )->      List[str]:
     torch.manual_seed(0  )
     _lowercase:			str      =     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  )
     _lowercase:			Dict      =     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  )
     _lowercase:			Optional[int]      =     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  )
     _lowercase:			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    ,       )
     torch.manual_seed(0  )
     _lowercase:			Dict      =     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    ,       )
     _lowercase:			str      =     CLIPTextModel(UpperCamelCase_  )
     _lowercase:			Any      =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

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

class   UpperCAmelCase    (      A ,       A ,       unittest.TestCase ):
   __SCREAMING_SNAKE_CASE		:				int      					=       StableDiffusionControlNetInpaintPipeline
   __SCREAMING_SNAKE_CASE		:				Optional[int]      					=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
   __SCREAMING_SNAKE_CASE		:				Optional[int]      					=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS






   def 			_a    (						self :							Union[str, Any]  )->      Optional[int]:
     torch.manual_seed(0  )
     _lowercase:			Any      =     UNetaDConditionModel(
         block_out_channels=(32, 64)    ,       layers_per_block=2    ,       sample_size=32    ,       in_channels=9    ,       out_channels=4    ,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,       up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,       cross_attention_dim=32    ,       )
     torch.manual_seed(0  )

     def init_weights(UpperCamelCase_ :							Union[str, Any]  ):
       if isinstance(UpperCamelCase_    ,       torch.nn.Convad  ):
         torch.nn.init.normal(m.weight  )
         m.bias.data.fill_(1.0  )

     _lowercase:			int      =     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  )
     _lowercase:			List[str]      =     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  )
     _lowercase:			Optional[Any]      =     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  )
     _lowercase:			List[str]      =     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  )
     _lowercase:			Tuple      =     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    ,       )
     _lowercase:			Dict      =     CLIPTextModel(UpperCamelCase_  )
     _lowercase:			Tuple      =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

     _lowercase:			int      =     MultiControlNetModel([controlneta, controlneta]  )

     _lowercase:			List[str]      =     {
         'unet': unet,
         'controlnet': controlnet,
         'scheduler': scheduler,
         'vae': vae,
         'text_encoder': text_encoder,
         'tokenizer': tokenizer,
         'safety_checker': None,
         'feature_extractor': None,
     }
     return components






   def 			_a    (						self :							Optional[int]    ,       UpperCamelCase_ :							Dict    ,       UpperCamelCase_ :							str=0  )->      List[Any]:
     if str(UpperCamelCase_  ).startswith('mps'  ):
       _lowercase:			str      =     torch.manual_seed(UpperCamelCase_  )
     else:
       _lowercase:			int      =     torch.Generator(device=UpperCamelCase_  ).manual_seed(UpperCamelCase_  )

     _lowercase:			List[str]      =     2

     _lowercase:			List[str]      =     [
         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_  )    ,       ),
     ]
     _lowercase:			int      =     floats_tensor((1, 3, 32, 32)    ,       rng=random.Random(UpperCamelCase_  )  ).to(UpperCamelCase_  )
     _lowercase:			Dict      =     init_image.cpu().permute(0    ,       2    ,       3    ,       1  )[0]

     _lowercase:			Any      =     Image.fromarray(np.uinta(UpperCamelCase_  )  ).convert('RGB'  ).resize((64, 64)  )
     _lowercase:			int      =     Image.fromarray(np.uinta(init_image + 4  )  ).convert('RGB'  ).resize((64, 64)  )

     _lowercase:			str      =     {
         'prompt': 'A painting of a squirrel eating a burger',
         'generator': generator,
         'num_inference_steps': 2,
         'guidance_scale': 6.0,
         'output_type': 'numpy',
         'image': image,
         'mask_image': mask_image,
         'control_image': control_image,
     }

     return inputs






   def 			_a    (						self :							Dict  )->      Optional[Any]:
     _lowercase:			Tuple      =     self.get_dummy_components()
     _lowercase:			int      =     self.pipeline_class(**UpperCamelCase_  )
     pipe.to(UpperCamelCase_  )

     _lowercase:			str      =     10.0
     _lowercase:			List[str]      =     4

     _lowercase:			List[Any]      =     self.get_dummy_inputs(UpperCamelCase_  )
     _lowercase:			str      =     steps
     _lowercase:			Tuple      =     scale
     _lowercase:			List[Any]      =     pipe(**UpperCamelCase_  )[0]

     _lowercase:			List[Any]      =     self.get_dummy_inputs(UpperCamelCase_  )
     _lowercase:			Optional[Any]      =     steps
     _lowercase:			Optional[Any]      =     scale
     _lowercase:			Dict      =     pipe(**UpperCamelCase_    ,       control_guidance_start=0.1    ,       control_guidance_end=0.2  )[0]

     _lowercase:			Union[str, Any]      =     self.get_dummy_inputs(UpperCamelCase_  )
     _lowercase:			List[Any]      =     steps
     _lowercase:			List[str]      =     scale
     _lowercase:			List[Any]      =     pipe(**UpperCamelCase_    ,       control_guidance_start=[0.1, 0.3]    ,       control_guidance_end=[0.2, 0.7]  )[0]

     _lowercase:			int      =     self.get_dummy_inputs(UpperCamelCase_  )
     _lowercase:			List[Any]      =     steps
     _lowercase:			str      =     scale
     _lowercase:			int      =     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 			_a    (						self :							List[str]  )->      str:
     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 			_a    (						self :							List[Any]  )->      List[str]:
     self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3  )






   def 			_a    (						self :							Any  )->      List[str]:
     self._test_inference_batch_single_identical(expected_max_diff=2E-3  )






   def 			_a    (						self :							str  )->      str:
     _lowercase:			List[Any]      =     self.get_dummy_components()
     _lowercase:			Tuple      =     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   UpperCAmelCase    (      unittest.TestCase ):






   def 			_a    (						self :							Union[str, Any]  )->      Optional[Any]:
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()






   def 			_a    (						self :							Any  )->      Tuple:
     _lowercase:			Any      =     ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny'  )

     _lowercase:			int      =     StableDiffusionControlNetInpaintPipeline.from_pretrained(
         'runwayml/stable-diffusion-inpainting'    ,       safety_checker=UpperCamelCase_    ,       controlnet=UpperCamelCase_  )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=UpperCamelCase_  )

     _lowercase:			Union[str, Any]      =     torch.Generator(device='cpu'  ).manual_seed(0  )
     _lowercase:			Dict      =     load_image(
         'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png'  ).resize((5_12, 5_12)  )

     _lowercase:			List[str]      =     load_image(
         'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
         '/stable_diffusion_inpaint/input_bench_mask.png'  ).resize((5_12, 5_12)  )

     _lowercase:			int      =     'pitch black hole'

     _lowercase:			List[Any]      =     load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'  ).resize((5_12, 5_12)  )

     _lowercase:			Tuple      =     pipe(
         UpperCamelCase_    ,       image=UpperCamelCase_    ,       mask_image=UpperCamelCase_    ,       control_image=UpperCamelCase_    ,       generator=UpperCamelCase_    ,       output_type='np'    ,       num_inference_steps=3    ,       )

     _lowercase:			Optional[Any]      =     output.images[0]

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

     _lowercase:			Optional[Any]      =     load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/inpaint.npy'  )

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






   def 			_a    (						self :							int  )->      Union[str, Any]:
     _lowercase:			Optional[Any]      =     ControlNetModel.from_pretrained('lllyasviel/control_v11p_sd15_inpaint'  )

     _lowercase:			List[Any]      =     StableDiffusionControlNetInpaintPipeline.from_pretrained(
         'runwayml/stable-diffusion-v1-5'    ,       safety_checker=UpperCamelCase_    ,       controlnet=UpperCamelCase_  )
     _lowercase:			Optional[int]      =     DDIMScheduler.from_config(pipe.scheduler.config  )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=UpperCamelCase_  )

     _lowercase:			Any      =     torch.Generator(device='cpu'  ).manual_seed(33  )

     _lowercase:			Union[str, Any]      =     load_image(
         'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png'  )
     _lowercase:			Optional[Any]      =     init_image.resize((5_12, 5_12)  )

     _lowercase:			Optional[Any]      =     load_image(
         'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png'  )
     _lowercase:			Tuple      =     mask_image.resize((5_12, 5_12)  )

     _lowercase:			List[Any]      =     'a handsome man with ray-ban sunglasses'

     def make_inpaint_condition(UpperCamelCase_ :							List[str]    ,       UpperCamelCase_ :							Union[str, Any]  ):
       _lowercase:			List[str]      =     np.array(image.convert('RGB'  )  ).astype(np.floataa  ) / 255.0
       _lowercase:			Optional[int]      =     np.array(image_mask.convert('L'  )  ).astype(np.floataa  ) / 255.0

       assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
       _lowercase:			List[Any]      =     -1.0  # set as masked pixel
       _lowercase:			Optional[Any]      =     np.expand_dims(UpperCamelCase_    ,       0  ).transpose(0    ,       3    ,       1    ,       2  )
       _lowercase:			List[str]      =     torch.from_numpy(UpperCamelCase_  )
       return image

     _lowercase:			Any      =     make_inpaint_condition(UpperCamelCase_    ,       UpperCamelCase_  )

     _lowercase:			int      =     pipe(
         UpperCamelCase_    ,       image=UpperCamelCase_    ,       mask_image=UpperCamelCase_    ,       control_image=UpperCamelCase_    ,       guidance_scale=9.0    ,       eta=1.0    ,       generator=UpperCamelCase_    ,       num_inference_steps=20    ,       output_type='np'    ,       )
     _lowercase:			str      =     output.images[0]

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

     _lowercase:			List[Any]      =     load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/boy_ray_ban.npy'  )

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






import argparse
import json
import logging
import os
import sys
from unittest import skip
from unittest.mock import patch

import tensorflow as tf

from transformers.testing_utils import TestCasePlus, get_gpu_count, slow


UpperCAmelCase__    :							Any       		=     [
    os.path.join(os.path.dirname(__file__), dirname)
    for dirname in [
        'text-generation',
        'text-classification',
        'token-classification',
        'language-modeling',
        'multiple-choice',
        'question-answering',
        'summarization',
        'translation',
        'image-classification',
    ]
]
sys.path.extend(SRC_DIRS)


if SRC_DIRS is not None:
   import run_clm
   import run_image_classification
   import run_mlm
   import run_ner
   import run_qa as run_squad
   import run_summarization
   import run_swag
   import run_text_classification
   import run_translation


logging.basicConfig(level=logging.DEBUG)

UpperCAmelCase__    :							Union[str, Any]       		=     logging.getLogger()


def 		_lowerCamelCase					(       )      ->		str:





  """simple docstring"""





  _lowercase:			int      =     argparse.ArgumentParser()
  parser.add_argument('-f'				)
  _lowercase:			Optional[Any]      =     parser.parse_args()
  return args.f


def 		_lowerCamelCase					(       UpperCamelCase				)      ->		Dict:





  """simple docstring"""





  _lowercase:			str      =     {}
  _lowercase:			Union[str, Any]      =     os.path.join(UpperCamelCase       ,  'all_results.json'				)
  if os.path.exists(UpperCamelCase				):
    with open(UpperCamelCase       ,  'r'				) as f:
      _lowercase:			Dict      =     json.load(UpperCamelCase				)
  else:
    raise ValueError(F'can\'t find {path}'				)
  return results


def 		_lowerCamelCase					(       )      ->		Any:





  """simple docstring"""





  return bool(tf.config.list_physical_devices('GPU'				)				)


UpperCAmelCase__    :							List[Any]       		=     logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





class   UpperCAmelCase    (      A ):






   @skip('Skipping until shape inference for to_tf_dataset PR is merged.'  )
   def 			_a    (						self :							Union[str, Any]  )->      Optional[Any]:
     _lowercase:			List[str]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_text_classification.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            '.split()

     if is_cuda_available():
       testargs.append('--fp16'  )

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_text_classification.main()
       # Reset the mixed precision policy so we don't break other tests
       tf.keras.mixed_precision.set_global_policy('float32'  )
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['eval_accuracy']    ,       0.75  )






   def 			_a    (						self :							Optional[Any]  )->      int:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_clm.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --do_train\n            --do_eval\n            --block_size 128\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            '.split()

     if len(tf.config.list_physical_devices('GPU'  )  ) > 1:
       # Skipping because there are not enough batches to train the model + would need a drop_last to work.
       return

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_clm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       1_00  )






   def 			_a    (						self :							Union[str, Any]  )->      Optional[int]:
     _lowercase:			int      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_mlm.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --max_seq_length 64\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --prediction_loss_only\n            --num_train_epochs=1\n            --learning_rate=1e-4\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_mlm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       42  )






   def 			_a    (						self :							int  )->      Any:
     # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
     _lowercase:			List[Any]      =     7 if get_gpu_count() > 1 else 2

     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Optional[int]      =     f'\n            run_ner.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/conll/sample.json\n            --validation_file tests/fixtures/tests_samples/conll/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=2\n            --num_train_epochs={epochs}\n            --seed 7\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_ner.main()
       _lowercase:			Optional[Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.75  )






   def 			_a    (						self :							Tuple  )->      Optional[int]:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_qa.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=10\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_squad.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['f1']    ,       30  )
       self.assertGreaterEqual(result['exact']    ,       30  )






   def 			_a    (						self :							List[str]  )->      Tuple:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Any      =     f'\n            run_swag.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=20\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_swag.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['val_accuracy']    ,       0.8  )






   @slow
   def 			_a    (						self :							Dict  )->      Tuple:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_summarization.py\n            --model_name_or_path t5-small\n            --train_file tests/fixtures/tests_samples/xsum/sample.json\n            --validation_file tests/fixtures/tests_samples/xsum/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=50\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_summarization.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['rouge1']    ,       10  )
       self.assertGreaterEqual(result['rouge2']    ,       2  )
       self.assertGreaterEqual(result['rougeL']    ,       7  )
       self.assertGreaterEqual(result['rougeLsum']    ,       7  )






   @slow
   def 			_a    (						self :							Tuple  )->      str:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_translation.py\n            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=3e-3\n            --num_train_epochs 12\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_translation.main()
       _lowercase:			Optional[int]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['bleu']    ,       30  )






   def 			_a    (						self :							int  )->      List[Any]:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Dict      =     f'\n            run_image_classification.py\n            --dataset_name hf-internal-testing/cats_vs_dogs_sample\n            --model_name_or_path microsoft/resnet-18\n            --do_train\n            --do_eval\n            --learning_rate 1e-4\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --dataloader_num_workers 16\n            --num_train_epochs 2\n            --train_val_split 0.1\n            --seed 42\n            --ignore_mismatched_sizes True\n            '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_image_classification.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.7  )
