
"""simple docstring"""



import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    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        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							List[Any]							=					"ssube/stable-diffusion-x4-upscaler-onnx"


				def 				__lowerCamelCase	(					self	:			List[Any]				,     UpperCAmelCase_	:			Any=0  )		->  Any:







											"""simple docstring"""




											_lowerCAmelCase  	=			floats_tensor((1, 3, 128, 128)				,     rng=random.Random(lowercase_  )  )
											_lowerCAmelCase  	=			torch.manual_seed(lowercase_  )
											_lowerCAmelCase  	=			{
											    'prompt': 'A painting of a squirrel eating a burger',
											    'image': image,
											    'generator': generator,
											    'num_inference_steps': 3,
											    'guidance_scale': 7.5,
											    'output_type': 'numpy',
											}
											return inputs


				def 				__lowerCamelCase	(					self	:			str  )		->  List[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,     provider='CPUExecutionProvider'  )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			self.get_dummy_inputs()
											_lowerCAmelCase  	=			pipe(**lowercase_  ).images
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1].flatten()

											# started as 128, should now be 512
											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]  )
											assert np.abs(image_slice - expected_slice  ).max() < 1E-1


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







											"""simple docstring"""




											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,     provider='CPUExecutionProvider'  )
											_lowerCAmelCase  	=			PNDMScheduler.from_config(pipe.scheduler.config				,     skip_prk_steps=lowercase_  )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			self.get_dummy_inputs()
											_lowerCAmelCase  	=			pipe(**lowercase_  ).images
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1]

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]  )
											assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-1


				def 				__lowerCamelCase	(					self	:			Optional[int]  )		->  Any:







											"""simple docstring"""




											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,     provider='CPUExecutionProvider'  )
											_lowerCAmelCase  	=			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			self.get_dummy_inputs()
											_lowerCAmelCase  	=			pipe(**lowercase_  ).images
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1]

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]  )

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


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







											"""simple docstring"""




											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,     provider='CPUExecutionProvider'  )
											_lowerCAmelCase  	=			EulerDiscreteScheduler.from_config(pipe.scheduler.config  )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			self.get_dummy_inputs()
											_lowerCAmelCase  	=			pipe(**lowercase_  ).images
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1]

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]  )
											assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-1







				def 				__lowerCamelCase	(					self	:			Any  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,     provider='CPUExecutionProvider'  )
											_lowerCAmelCase  	=			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config  )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			self.get_dummy_inputs()
											_lowerCAmelCase  	=			pipe(**lowercase_  ).images
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1]

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]  )

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






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






				'''simple docstring'''



				@property
				def 				__lowerCamelCase	(					self	:			Optional[int]  )		->  Optional[int]:







											"""simple docstring"""




											return (
											    "CUDAExecutionProvider",
											    {
											        "gpu_mem_limit": "15000000000",  # 15GB
											        "arena_extend_strategy": "kSameAsRequested",
											    },
											)


				@property
				def 				__lowerCamelCase	(					self	:			int  )		->  int:







											"""simple docstring"""




											_lowerCAmelCase  	=			ort.SessionOptions()
											_lowerCAmelCase  	=			False
											return options


				def 				__lowerCamelCase	(					self	:			Dict  )		->  List[str]:







											"""simple docstring"""




											_lowerCAmelCase  	=			load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/img2img/sketch-mountains-input.jpg'  )
											_lowerCAmelCase  	=			init_image.resize((128, 128)  )
											# using the PNDM scheduler by default
											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(
											    'ssube/stable-diffusion-x4-upscaler-onnx'				,     provider=self.gpu_provider				,     sess_options=self.gpu_options				,     )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			'A fantasy landscape, trending on artstation'

											_lowerCAmelCase  	=			torch.manual_seed(0  )
											_lowerCAmelCase  	=			pipe(
											    prompt=lowercase_				,     image=lowercase_				,     guidance_scale=7.5				,     num_inference_steps=10				,     generator=lowercase_				,     output_type='np'				,     )
											_lowerCAmelCase  	=			output.images
											_lowerCAmelCase  	=			images[0, 255:258, 383:386, -1]

											assert images.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]  )
											# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







				def 				__lowerCamelCase	(					self	:			int  )		->  Union[str, Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/img2img/sketch-mountains-input.jpg'  )
											_lowerCAmelCase  	=			init_image.resize((128, 128)  )
											_lowerCAmelCase  	=			LMSDiscreteScheduler.from_pretrained(
											    'ssube/stable-diffusion-x4-upscaler-onnx'				,     subfolder='scheduler'  )
											_lowerCAmelCase  	=			OnnxStableDiffusionUpscalePipeline.from_pretrained(
											    'ssube/stable-diffusion-x4-upscaler-onnx'				,     scheduler=lowercase_				,     provider=self.gpu_provider				,     sess_options=self.gpu_options				,     )
											pipe.set_progress_bar_config(disable=lowercase_  )

											_lowerCAmelCase  	=			'A fantasy landscape, trending on artstation'

											_lowerCAmelCase  	=			torch.manual_seed(0  )
											_lowerCAmelCase  	=			pipe(
											    prompt=lowercase_				,     image=lowercase_				,     guidance_scale=7.5				,     num_inference_steps=20				,     generator=lowercase_				,     output_type='np'				,     )
											_lowerCAmelCase  	=			output.images
											_lowerCAmelCase  	=			images[0, 255:258, 383:386, -1]

											assert images.shape == (1, 512, 512, 3)
											_lowerCAmelCase  	=			np.array(
											    [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]  )
											# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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








"""simple docstring"""



import unittest

from datasets import load_dataset

from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							str							=					None
				SCREAMING_SNAKE_CASE_:							List[str]							=					BloomTokenizerFast
				SCREAMING_SNAKE_CASE_:							List[str]							=					BloomTokenizerFast
				SCREAMING_SNAKE_CASE_:							Any							=					True
				SCREAMING_SNAKE_CASE_:							List[Any]							=					False
				SCREAMING_SNAKE_CASE_:							Optional[int]							=					"tokenizer_file"
				SCREAMING_SNAKE_CASE_:							str							=					{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"}


				def 				__lowerCamelCase	(					self	:			Tuple  )		->  str:







											"""simple docstring"""




											super().setUp()
											_lowerCAmelCase  	=			BloomTokenizerFast.from_pretrained('bigscience/tokenizer'  )
											tokenizer.save_pretrained(self.tmpdirname  )


				def 				__lowerCamelCase	(					self	:			List[str]				,     **UpperCAmelCase_	:			Any  )		->  Optional[Any]:







											"""simple docstring"""




											kwargs.update(self.special_tokens_map  )
											return BloomTokenizerFast.from_pretrained(self.tmpdirname				,     **UpperCAmelCase_  )


				def 				__lowerCamelCase	(					self	:			List[Any]  )		->  str:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.get_rust_tokenizer()

											_lowerCAmelCase  	=			['The quick brown fox</s>', 'jumps over the lazy dog</s>']
											_lowerCAmelCase  	=			[[2_175, 23_714, 73_173, 144_252, 2], [77, 132_619, 3_478, 368, 109_586, 35_433, 2]]

											_lowerCAmelCase  	=			tokenizer.batch_encode_plus(UpperCAmelCase_  )['input_ids']
											self.assertListEqual(UpperCAmelCase_				,     UpperCAmelCase_  )

											_lowerCAmelCase  	=			tokenizer.batch_decode(UpperCAmelCase_  )
											self.assertListEqual(UpperCAmelCase_				,     UpperCAmelCase_  )


				def 				__lowerCamelCase	(					self	:			Any				,     UpperCAmelCase_	:			List[str]=6  )		->  Any:







											"""simple docstring"""




											for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																		with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""  ):
																									_lowerCAmelCase  	=			self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_				,     **UpperCAmelCase_  )
																									# tokenizer_r.pad_token = None # Hotfixing padding = None
																									# Simple input
																									_lowerCAmelCase  	=			'This is a simple input'
																									_lowerCAmelCase  	=			['This is a simple input 1', 'This is a simple input 2']
																									_lowerCAmelCase  	=			('This is a simple input', 'This is a pair')
																									_lowerCAmelCase  	=			[
																									    ('This is a simple input 1', 'This is a simple input 2'),
																									    ('This is a simple pair 1', 'This is a simple pair 2'),
																									]

																									# Simple input tests
																									try:
																																tokenizer_r.encode(UpperCAmelCase_				,     max_length=UpperCAmelCase_  )
																																tokenizer_r.encode_plus(UpperCAmelCase_				,     max_length=UpperCAmelCase_  )

																																tokenizer_r.batch_encode_plus(UpperCAmelCase_				,     max_length=UpperCAmelCase_  )
																																tokenizer_r.encode(UpperCAmelCase_				,     max_length=UpperCAmelCase_  )
																																tokenizer_r.batch_encode_plus(UpperCAmelCase_				,     max_length=UpperCAmelCase_  )
																									except ValueError:
																																self.fail('Bloom Tokenizer should be able to deal with padding'  )

																									_lowerCAmelCase  	=			None  # Hotfixing padding = None
																									self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'  )

																									# Simple input
																									self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'  )

																									# Simple input
																									self.assertRaises(
																									    UpperCAmelCase_				,     tokenizer_r.batch_encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'				,     )

																									# Pair input
																									self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'  )

																									# Pair input
																									self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'  )

																									# Pair input
																									self.assertRaises(
																									    UpperCAmelCase_				,     tokenizer_r.batch_encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding='max_length'				,     )


				def 				__lowerCamelCase	(					self	:			str  )		->  Any:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.get_rust_tokenizer()
											_lowerCAmelCase  	=			load_dataset('xnli'				,     'all_languages'				,     split='test'				,     streaming=UpperCAmelCase_  )

											_lowerCAmelCase  	=			next(iter(UpperCAmelCase_  )  )['premise']  # pick up one data
											_lowerCAmelCase  	=			list(sample_data.values()  )

											_lowerCAmelCase  	=			list(map(tokenizer.encode				,     UpperCAmelCase_  )  )
											_lowerCAmelCase  	=			[tokenizer.decode(UpperCAmelCase_				,     clean_up_tokenization_spaces=UpperCAmelCase_  ) for x in output_tokens]
											self.assertListEqual(UpperCAmelCase_				,     UpperCAmelCase_  )







				def 				__lowerCamelCase	(					self	:			Tuple  )		->  List[Any]:







											"""simple docstring"""




											self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map  )				,     1  )
											self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()  )[0]  )				,     1  )






