




import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
  import onnxruntime as ort







class 						lowercase							(   UpperCamelCase__,unittest.TestCase		):
     _a							 =						"hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"

     def 					a__	(  self		,     _a=0				)						->							Optional[Any]:
           _A							:     Tuple			=						floats_tensor((1, 3, 128, 128)		,     rng=random.Random(_a				)				)
           _A							:     Optional[Any]			=						np.random.RandomState(_a				)
           _A							:     Optional[Any]			=						{
               """prompt""": """A painting of a squirrel eating a burger""",
               """image""": image,
               """generator""": generator,
               """num_inference_steps""": 3,
               """strength""": 0.75,
               """guidance_scale""": 7.5,
               """output_type""": """numpy""",
           }
           return inputs

     def 					a__	(  self				)						->							int:
           _A							:     int			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     Any			=						self.get_dummy_inputs()
           _A							:     List[str]			=						pipe(**_a				).images
           _A							:     Optional[Any]			=						image[0, -3:, -3:, -1].flatten()

           assert image.shape == (1, 128, 128, 3)
           _A							:     List[Any]			=						np.array([0.69643, 0.58484, 0.50314, 0.58760, 0.55368, 0.59643, 0.51529, 0.41217, 0.49087]				)
           assert np.abs(image_slice - expected_slice				).max() < 1e-1

     def 					a__	(  self				)						->							Dict:
           _A							:     List[Any]			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           _A							:     List[Any]			=						PNDMScheduler.from_config(pipe.scheduler.config		,     skip_prk_steps=_a				)
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     List[Any]			=						self.get_dummy_inputs()
           _A							:     Union[str, Any]			=						pipe(**_a				).images
           _A							:     Optional[int]			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 128, 128, 3)
           _A							:     Dict			=						np.array([0.61737, 0.54642, 0.53183, 0.54465, 0.52742, 0.60525, 0.49969, 0.40655, 0.48154]				)

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

     def 					a__	(  self				)						->							List[Any]:
           _A							:     Dict			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           _A							:     Tuple			=						LMSDiscreteScheduler.from_config(pipe.scheduler.config				)
           pipe.set_progress_bar_config(disable=_a				)

           # warmup pass to apply optimizations
           _A							:     List[Any]			=						pipe(**self.get_dummy_inputs()				)

           _A							:     Tuple			=						self.get_dummy_inputs()
           _A							:     List[str]			=						pipe(**_a				).images
           _A							:     Optional[Any]			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 128, 128, 3)
           _A							:     Dict			=						np.array([0.52761, 0.59977, 0.49033, 0.49619, 0.54282, 0.50311, 0.47600, 0.40918, 0.45203]				)

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

     def 					a__	(  self				)						->							Union[str, Any]:
           _A							:     str			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           _A							:     Any			=						EulerDiscreteScheduler.from_config(pipe.scheduler.config				)
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     int			=						self.get_dummy_inputs()
           _A							:     Tuple			=						pipe(**_a				).images
           _A							:     Any			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 128, 128, 3)
           _A							:     Any			=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304]				)

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

     def 					a__	(  self				)						->							List[Any]:
           _A							:     int			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           _A							:     Union[str, Any]			=						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config				)
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     Optional[Any]			=						self.get_dummy_inputs()
           _A							:     Tuple			=						pipe(**_a				).images
           _A							:     Any			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 128, 128, 3)
           _A							:     str			=						np.array([0.52911, 0.60004, 0.49229, 0.49805, 0.54502, 0.50680, 0.47777, 0.41028, 0.45304]				)

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



     def 					a__	(  self				)						->							List[str]:
           _A							:     Union[str, Any]			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint		,     provider="""CPUExecutionProvider"""				)
           _A							:     str			=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config				)
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     Union[str, Any]			=						self.get_dummy_inputs()
           _A							:     List[str]			=						pipe(**_a				).images
           _A							:     str			=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 128, 128, 3)
           _A							:     Optional[int]			=						np.array([0.65331, 0.58277, 0.48204, 0.56059, 0.53665, 0.56235, 0.50969, 0.40009, 0.46552]				)

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







@nightly
@require_onnxruntime
@require_torch_gpu
class 						lowercase							(   unittest.TestCase		):

     @property
     def 					a__	(  self				)						->							str:
           return (
               "CUDAExecutionProvider",
               {
                   "gpu_mem_limit": "15000000000",  # 15GB
                   "arena_extend_strategy": "kSameAsRequested",
               },
           )

     @property
     def 					a__	(  self				)						->							Optional[int]:
           _A							:     Union[str, Any]			=						ort.SessionOptions()
           _A							:     List[str]			=						False
           return options

     def 					a__	(  self				)						->							Tuple:
           _A							:     str			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/img2img/sketch-mountains-input.jpg"""				)
           _A							:     Optional[Any]			=						init_image.resize((768, 512)				)
           # using the PNDM scheduler by default
           _A							:     List[str]			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
               """CompVis/stable-diffusion-v1-4"""		,     revision="""onnx"""		,     safety_checker=_a		,     feature_extractor=_a		,     provider=self.gpu_provider		,     sess_options=self.gpu_options		,     )
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     str			=						"""A fantasy landscape, trending on artstation"""

           _A							:     List[str]			=						np.random.RandomState(0				)
           _A							:     Dict			=						pipe(
               prompt=_a		,     image=_a		,     strength=0.75		,     guidance_scale=7.5		,     num_inference_steps=10		,     generator=_a		,     output_type="""np"""		,     )
           _A							:     Optional[Any]			=						output.images
           _A							:     Optional[Any]			=						images[0, 255:258, 383:386, -1]

           assert images.shape == (1, 512, 768, 3)
           _A							:     Optional[int]			=						np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019]				)
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



     def 					a__	(  self				)						->							Optional[Any]:
           _A							:     Any			=						load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/img2img/sketch-mountains-input.jpg"""				)
           _A							:     Union[str, Any]			=						init_image.resize((768, 512)				)
           _A							:     Any			=						LMSDiscreteScheduler.from_pretrained(
               """runwayml/stable-diffusion-v1-5"""		,     subfolder="""scheduler"""		,     revision="""onnx"""				)
           _A							:     int			=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
               """runwayml/stable-diffusion-v1-5"""		,     revision="""onnx"""		,     scheduler=_a		,     safety_checker=_a		,     feature_extractor=_a		,     provider=self.gpu_provider		,     sess_options=self.gpu_options		,     )
           pipe.set_progress_bar_config(disable=_a				)

           _A							:     str			=						"""A fantasy landscape, trending on artstation"""

           _A							:     int			=						np.random.RandomState(0				)
           _A							:     Optional[Any]			=						pipe(
               prompt=_a		,     image=_a		,     strength=0.75		,     guidance_scale=7.5		,     num_inference_steps=20		,     generator=_a		,     output_type="""np"""		,     )
           _A							:     Tuple			=						output.images
           _A							:     List[Any]			=						images[0, 255:258, 383:386, -1]

           assert images.shape == (1, 512, 768, 3)
           _A							:     List[Any]			=						np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431]				)
           # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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




import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_lxmert import LxmertTokenizer


lowerCAmelCase_       	=	{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

lowerCAmelCase_       	=	{
    '''vocab_file''': {
        '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt''',
    },
    '''tokenizer_file''': {
        '''unc-nlp/lxmert-base-uncased''': (
            '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json'''
        ),
    },
}

lowerCAmelCase_       	=	{
    '''unc-nlp/lxmert-base-uncased''': 5_12,
}

lowerCAmelCase_       	=	{
    '''unc-nlp/lxmert-base-uncased''': {'''do_lower_case''': True},
}





class 	snake_case_   (		__A					):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE     :   Optional[Any]									=				VOCAB_FILES_NAMES
			SCREAMING_SNAKE_CASE     :   Any									=				PRETRAINED_VOCAB_FILES_MAP
			SCREAMING_SNAKE_CASE     :   List[Any]									=				PRETRAINED_INIT_CONFIGURATION
			SCREAMING_SNAKE_CASE     :   Optional[int]									=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			SCREAMING_SNAKE_CASE     :   Any									=				LxmertTokenizer







			def __init__(     self :				Union[str, Any]							,   _UpperCamelCase :				int=None							,   _UpperCamelCase :				Optional[Any]=None							,   _UpperCamelCase :				Dict=True							,   _UpperCamelCase :				Any="[UNK]"							,   _UpperCamelCase :				Tuple="[SEP]"							,   _UpperCamelCase :				List[Any]="[PAD]"							,   _UpperCamelCase :				Union[str, Any]="[CLS]"							,   _UpperCamelCase :				str="[MASK]"							,   _UpperCamelCase :				List[str]=True							,   _UpperCamelCase :				List[str]=None							,   **_UpperCamelCase :				List[str]							,   )      ->Any:
									super().__init__(
									    _UpperCamelCase							,   tokenizer_file=_UpperCamelCase							,   do_lower_case=_UpperCamelCase							,   unk_token=_UpperCamelCase							,   sep_token=_UpperCamelCase							,   pad_token=_UpperCamelCase							,   cls_token=_UpperCamelCase							,   mask_token=_UpperCamelCase							,   tokenize_chinese_chars=_UpperCamelCase							,   strip_accents=_UpperCamelCase							,   **_UpperCamelCase							,   )

									snake_case_   =	json.loads(self.backend_tokenizer.normalizer.__getstate__()							)
									if (
									    normalizer_state.get('''lowercase'''							,   _UpperCamelCase							) != do_lower_case
									    or normalizer_state.get('''strip_accents'''							,   _UpperCamelCase							) != strip_accents
									    or normalizer_state.get('''handle_chinese_chars'''							,   _UpperCamelCase							) != tokenize_chinese_chars
									):
															snake_case_   =	getattr(_UpperCamelCase							,   normalizer_state.pop('''type'''							)							)
															snake_case_   =	do_lower_case
															snake_case_   =	strip_accents
															snake_case_   =	tokenize_chinese_chars
															snake_case_   =	normalizer_class(**_UpperCamelCase							)

									snake_case_   =	do_lower_case







			def 				snake_case__(     self :				Optional[int]							,   _UpperCamelCase :				List[Any]							,   _UpperCamelCase :				List[str]=None							)      ->List[Any]:
									snake_case_   =	[self.cls_token_id] + token_ids_a + [self.sep_token_id]

									if token_ids_a:
															output += token_ids_a + [self.sep_token_id]

									return output







			def 				snake_case__(     self :				int							,   _UpperCamelCase :				List[int]							,   _UpperCamelCase :				Optional[List[int]] = None							)      ->List[int]:
									snake_case_   =	[self.sep_token_id]
									snake_case_   =	[self.cls_token_id]
									if token_ids_a is None:
															return len(cls + token_ids_a + sep							) * [0]
									return len(cls + token_ids_a + sep							) * [0] + len(token_ids_a + sep							) * [1]







			def 				snake_case__(     self :				Any							,   _UpperCamelCase :				str							,   _UpperCamelCase :				Optional[str] = None							)      ->Tuple[str]:
									snake_case_   =	self._tokenizer.model.save(_UpperCamelCase							,   name=_UpperCamelCase							)
									return tuple(_UpperCamelCase							)