





import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class 					__lowerCAmelCase       (			_a,     _a,     _a,     unittest.TestCase     ):
			lowerCamelCase_     :     Tuple       			=      StableDiffusionInpaintPipeline
			lowerCamelCase_     :     Tuple       			=      TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
			lowerCamelCase_     :     str       			=      TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
			lowerCamelCase_     :     str       			=      frozenset(
			    []     )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
			lowerCamelCase_     :     Union[str, Any]       			=      frozenset([]     )






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


							'''simple docstring'''



							torch.manual_seed(0    )
							snake_case_						:    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					,							attention_head_dim=(2, 4)					,							use_linear_projection=__magic_name__					,							)
							snake_case_						:    Dict				=  PNDMScheduler(skip_prk_steps=__magic_name__    )
							torch.manual_seed(0    )
							snake_case_						:    int				=  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					,							sample_size=128					,							)
							torch.manual_seed(0    )
							snake_case_						:    int				=  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=1000					,							hidden_act='''gelu'''					,							projection_dim=512					,							)
							snake_case_						:    Any				=  CLIPTextModel(__magic_name__    )
							snake_case_						:    str				=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    )

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






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__=0    )     ->   Optional[Any]:


							'''simple docstring'''



							snake_case_						:    int				=  floats_tensor((1, 3, 32, 32)					,							rng=random.Random(__magic_name__    )    ).to(__magic_name__    )
							snake_case_						:    str				=  image.cpu().permute(0					,							2					,							3					,							1    )[0]
							snake_case_						:    Optional[Any]				=  Image.fromarray(np.uinta(__magic_name__    )    ).convert('''RGB'''    ).resize((64, 64)    )
							snake_case_						:    List[Any]				=  Image.fromarray(np.uinta(image + 4    )    ).convert('''RGB'''    ).resize((64, 64)    )
							if str(__magic_name__    ).startswith('''mps'''    ):
											snake_case_						:    Any				=  torch.manual_seed(__magic_name__    )
							else:
											snake_case_						:    List[str]				=  torch.Generator(device=__magic_name__    ).manual_seed(__magic_name__    )
							snake_case_						:    int				=  {
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''image''': init_image,
							    '''mask_image''': mask_image,
							    '''generator''': generator,
							    '''num_inference_steps''': 2,
							    '''guidance_scale''': 6.0,
							    '''output_type''': '''numpy''',
							}
							return inputs






			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    List[Any]				=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							snake_case_						:    Dict				=  self.get_dummy_components()
							snake_case_						:    Optional[Any]				=  StableDiffusionInpaintPipeline(**__magic_name__    )
							snake_case_						:    List[Any]				=  sd_pipe.to(__magic_name__    )
							sd_pipe.set_progress_bar_config(disable=__magic_name__    )

							snake_case_						:    Tuple				=  self.get_dummy_inputs(__magic_name__    )
							snake_case_						:    Tuple				=  sd_pipe(**__magic_name__    ).images
							snake_case_						:    Any				=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case_						:    Tuple				=  np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476]    )

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






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


							'''simple docstring'''



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




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






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


							'''simple docstring'''



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






			def 			lowerCamelCase  (self    )     ->   Dict:


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/sd2-inpaint/init_image.png'''    )
							snake_case_						:    List[str]				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )
							snake_case_						:    str				=  load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
							    '''/yellow_cat_sitting_on_a_park_bench.npy'''    )

							snake_case_						:    Tuple				=  '''stabilityai/stable-diffusion-2-inpainting'''
							snake_case_						:    Optional[int]				=  StableDiffusionInpaintPipeline.from_pretrained(__magic_name__					,							safety_checker=__magic_name__    )
							pipe.to(__magic_name__    )
							pipe.set_progress_bar_config(disable=__magic_name__    )
							pipe.enable_attention_slicing()

							snake_case_						:    List[Any]				=  '''Face of a yellow cat, high resolution, sitting on a park bench'''

							snake_case_						:    Optional[Any]				=  torch.manual_seed(0    )
							snake_case_						:    List[str]				=  pipe(
							    prompt=__magic_name__					,							image=__magic_name__					,							mask_image=__magic_name__					,							generator=__magic_name__					,							output_type='''np'''					,							)
							snake_case_						:    List[Any]				=  output.images[0]

							assert image.shape == (512, 512, 3)
							assert np.abs(expected_image - image    ).max() < 9e-3






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


							'''simple docstring'''



							snake_case_						:    Optional[Any]				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/sd2-inpaint/init_image.png'''    )
							snake_case_						:    Tuple				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )
							snake_case_						:    Union[str, Any]				=  load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint'''
							    '''/yellow_cat_sitting_on_a_park_bench_fp16.npy'''    )

							snake_case_						:    Optional[Any]				=  '''stabilityai/stable-diffusion-2-inpainting'''
							snake_case_						:    int				=  StableDiffusionInpaintPipeline.from_pretrained(
							    __magic_name__					,							torch_dtype=torch.floataa					,							safety_checker=__magic_name__					,							)
							pipe.to(__magic_name__    )
							pipe.set_progress_bar_config(disable=__magic_name__    )
							pipe.enable_attention_slicing()

							snake_case_						:    Optional[int]				=  '''Face of a yellow cat, high resolution, sitting on a park bench'''

							snake_case_						:    int				=  torch.manual_seed(0    )
							snake_case_						:    Dict				=  pipe(
							    prompt=__magic_name__					,							image=__magic_name__					,							mask_image=__magic_name__					,							generator=__magic_name__					,							output_type='''np'''					,							)
							snake_case_						:    Union[str, Any]				=  output.images[0]

							assert image.shape == (512, 512, 3)
							assert np.abs(expected_image - image    ).max() < 5e-1






			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

							snake_case_						:    Any				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/sd2-inpaint/init_image.png'''    )
							snake_case_						:    List[str]				=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png'''    )

							snake_case_						:    List[str]				=  '''stabilityai/stable-diffusion-2-inpainting'''
							snake_case_						:    Any				=  PNDMScheduler.from_pretrained(__magic_name__					,							subfolder='''scheduler'''    )
							snake_case_						:    Dict				=  StableDiffusionInpaintPipeline.from_pretrained(
							    __magic_name__					,							safety_checker=__magic_name__					,							scheduler=__magic_name__					,							torch_dtype=torch.floataa					,							)
							pipe.to(__magic_name__    )
							pipe.set_progress_bar_config(disable=__magic_name__    )
							pipe.enable_attention_slicing(1    )
							pipe.enable_sequential_cpu_offload()

							snake_case_						:    int				=  '''Face of a yellow cat, high resolution, sitting on a park bench'''

							snake_case_						:    Optional[int]				=  torch.manual_seed(0    )
							snake_case_						:    List[Any]				=  pipe(
							    prompt=__magic_name__					,							image=__magic_name__					,							mask_image=__magic_name__					,							generator=__magic_name__					,							num_inference_steps=2					,							output_type='''np'''					,							)

							snake_case_						:    Union[str, Any]				=  torch.cuda.max_memory_allocated()
							# make sure that less than 2.65 GB is allocated
							assert mem_bytes < 2.65 * 10**9







import unittest
from pathlib import Path
from tempfile import NamedTemporaryFile, TemporaryDirectory

from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline
from transformers.convert_graph_to_onnx import (
    convert,
    ensure_valid_input,
    generate_identified_filename,
    infer_shapes,
    quantize,
)
from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow



class 					__lowerCAmelCase       :






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   Dict:


							'''simple docstring'''



							return None




class 					__lowerCAmelCase       :






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   List[str]:


							'''simple docstring'''



							return None




class 					__lowerCAmelCase       (			unittest.TestCase     ):
			lowerCamelCase_     :     Dict       			=      [
			    # (model_name, model_kwargs)
			    ('''bert-base-cased''', {}),
			    ('''gpt2''', {'''use_cache''': False}),  # We don't support exporting GPT2 past keys anymore
			]






			@require_tf
			@slow
			def 			lowerCamelCase  (self    )     ->   Union[str, Any]:


							'''simple docstring'''



							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
											self._test_export(__magic_name__					,							'''tf'''					,							12					,							**__magic_name__    )






			@require_torch
			@slow
			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
											self._test_export(__magic_name__					,							'''pt'''					,							12					,							**__magic_name__    )






			@require_torch
			@slow
			def 			lowerCamelCase  (self    )     ->   int:


							'''simple docstring'''



							from transformers import BertModel

							snake_case_						:    str				=  ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words''']
							with NamedTemporaryFile(mode='''w+t'''    ) as vocab_file:
											vocab_file.write('''\n'''.join(__magic_name__    )    )
											vocab_file.flush()
											snake_case_						:    Optional[Any]				=  BertTokenizerFast(vocab_file.name    )

							with TemporaryDirectory() as bert_save_dir:
											snake_case_						:    str				=  BertModel(BertConfig(vocab_size=len(__magic_name__    )    )    )
											model.save_pretrained(__magic_name__    )
											self._test_export(__magic_name__					,							'''pt'''					,							12					,							__magic_name__    )






			@require_tf
			@slow
			def 			lowerCamelCase  (self    )     ->   Tuple:


							'''simple docstring'''



							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
											snake_case_						:    Tuple				=  self._test_export(__magic_name__					,							'''tf'''					,							12					,							**__magic_name__    )
											snake_case_						:    List[str]				=  quantize(Path(__magic_name__    )    )

											# Ensure the actual quantized model is not bigger than the original one
											if quantized_path.stat().st_size >= Path(__magic_name__    ).stat().st_size:
															self.fail('''Quantized model is bigger than initial ONNX model'''    )






			@require_torch
			@slow
			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST:
											snake_case_						:    Any				=  self._test_export(__magic_name__					,							'''pt'''					,							12					,							**__magic_name__    )
											snake_case_						:    Any				=  quantize(__magic_name__    )

											# Ensure the actual quantized model is not bigger than the original one
											if quantized_path.stat().st_size >= Path(__magic_name__    ).stat().st_size:
															self.fail('''Quantized model is bigger than initial ONNX model'''    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__=None					,							**__magic_name__    )     ->   Tuple:


							'''simple docstring'''



							try:
											# Compute path
											with TemporaryDirectory() as tempdir:
															snake_case_						:    List[str]				=  Path(__magic_name__    ).joinpath('''model.onnx'''    )

											# Remove folder if exists
											if path.parent.exists():
															path.parent.rmdir()

											# Export
											convert(__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							__magic_name__					,							**__magic_name__    )

											return path
							except Exception as e:
											self.fail(__magic_name__    )






			@require_torch
			@require_tokenizers
			@slow
			def 			lowerCamelCase  (self    )     ->   Optional[Any]:


							'''simple docstring'''



							from transformers import BertModel

							snake_case_						:    Optional[Any]				=  BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random'''    )    )
							snake_case_						:    int				=  BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random'''    )
							self._test_infer_dynamic_axis(__magic_name__					,							__magic_name__					,							'''pt'''    )






			@require_tf
			@require_tokenizers
			@slow
			def 			lowerCamelCase  (self    )     ->   List[str]:


							'''simple docstring'''



							from transformers import TFBertModel

							snake_case_						:    Any				=  TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random'''    )    )
							snake_case_						:    str				=  BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random'''    )
							self._test_infer_dynamic_axis(__magic_name__					,							__magic_name__					,							'''tf'''    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   int:


							'''simple docstring'''



							snake_case_						:    Tuple				=  FeatureExtractionPipeline(__magic_name__					,							__magic_name__    )

							snake_case_						:    Optional[int]				=  ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1''']
							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_						:    Optional[int]				=  infer_shapes(__magic_name__					,							__magic_name__    )

							# Assert all variables are present
							self.assertEqual(len(__magic_name__    )					,							len(__magic_name__    )    )
							self.assertTrue(all(var_name in shapes for var_name in variable_names    )    )
							self.assertSequenceEqual(variable_names[:3]					,							__magic_name__    )
							self.assertSequenceEqual(variable_names[3:]					,							__magic_name__    )

							# Assert inputs are {0: batch, 1: sequence}
							for var_name in ["input_ids", "token_type_ids", "attention_mask"]:
											self.assertDictEqual(shapes[var_name]					,							{0: '''batch''', 1: '''sequence'''}    )

							# Assert outputs are {0: batch, 1: sequence} and {0: batch}
							self.assertDictEqual(shapes['''output_0''']					,							{0: '''batch''', 1: '''sequence'''}    )
							self.assertDictEqual(shapes['''output_1''']					,							{0: '''batch'''}    )






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


							'''simple docstring'''



							snake_case_						:    Tuple				=  ['''input_ids''', '''attention_mask''', '''token_type_ids''']
							snake_case_						:    List[str]				=  {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]}
							snake_case_			,							snake_case_						:    Tuple				=  ensure_valid_input(FuncContiguousArgs()					,							__magic_name__					,							__magic_name__    )

							# Should have exactly the same number of args (all are valid)
							self.assertEqual(len(__magic_name__    )					,							3    )

							# Should have exactly the same input names
							self.assertEqual(set(__magic_name__    )					,							set(__magic_name__    )    )

							# Parameter should be reordered according to their respective place in the function:
							# (input_ids, token_type_ids, attention_mask)
							self.assertEqual(__magic_name__					,							(tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask'''])    )

							# Generated args are interleaved with another args (for instance parameter "past" in GPT2)
							snake_case_			,							snake_case_						:    Dict				=  ensure_valid_input(FuncNonContiguousArgs()					,							__magic_name__					,							__magic_name__    )

							# Should have exactly the one arg (all before the one not provided "some_other_args")
							self.assertEqual(len(__magic_name__    )					,							1    )
							self.assertEqual(len(__magic_name__    )					,							1    )

							# Should have only "input_ids"
							self.assertEqual(inputs_args[0]					,							tokens['''input_ids''']    )
							self.assertEqual(ordered_input_names[0]					,							'''input_ids'''    )






			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    Optional[int]				=  generate_identified_filename(Path('''/home/something/my_fake_model.onnx'''    )					,							'''-test'''    )
							self.assertEqual('''/home/something/my_fake_model-test.onnx'''					,							generated.as_posix()    )
