






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				( snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							A_						  =					"ssube/stable-diffusion-x4-upscaler-onnx"

							def       __A (  self:   Union[str, Any]		,     __A:   str=0   )    ->				int:
												_A								= floats_tensor((1, 3, 1_28, 1_28)		,     rng=random.Random(__A   )   )
												_A								= torch.manual_seed(__A   )
												_A								= {
												    '''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       __A (  self:   int   )    ->				Optional[Any]:
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,     provider='''CPUExecutionProvider'''   )
												pipe.set_progress_bar_config(disable=__A   )

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

												# started as 128, should now be 512
												assert image.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]   )
												assert np.abs(image_slice - expected_slice   ).max() < 1e-1

							def       __A (  self:   List[Any]   )    ->				Optional[Any]:
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,     provider='''CPUExecutionProvider'''   )
												_A								= PNDMScheduler.from_config(pipe.scheduler.config		,     skip_prk_steps=__A   )
												pipe.set_progress_bar_config(disable=__A   )

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

												assert image.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964]   )
												assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-1

							def       __A (  self:   Tuple   )    ->				Any:
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,     provider='''CPUExecutionProvider'''   )
												_A								= DPMSolverMultistepScheduler.from_config(pipe.scheduler.config   )
												pipe.set_progress_bar_config(disable=__A   )

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

												assert image.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515]   )

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

							def       __A (  self:   List[Any]   )    ->				Optional[Any]:
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,     provider='''CPUExecutionProvider'''   )
												_A								= EulerDiscreteScheduler.from_config(pipe.scheduler.config   )
												pipe.set_progress_bar_config(disable=__A   )

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

												assert image.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]   )
												assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-1



							def       __A (  self:   List[Any]   )    ->				Dict:
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,     provider='''CPUExecutionProvider'''   )
												_A								= EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config   )
												pipe.set_progress_bar_config(disable=__A   )

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

												assert image.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043]   )

												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       __A (  self:   List[Any]   )    ->				Union[str, Any]:
												return (
												    "CUDAExecutionProvider",
												    {
												        "gpu_mem_limit": "15000000000",  # 15GB
												        "arena_extend_strategy": "kSameAsRequested",
												    },
												)

							@property
							def       __A (  self:   str   )    ->				str:
												_A								= ort.SessionOptions()
												_A								= False
												return options

							def       __A (  self:   List[Any]   )    ->				Optional[int]:
												_A								= load_image(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
												    '''/img2img/sketch-mountains-input.jpg'''   )
												_A								= init_image.resize((1_28, 1_28)   )
												# using the PNDM scheduler by default
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(
												    '''ssube/stable-diffusion-x4-upscaler-onnx'''		,     provider=self.gpu_provider		,     sess_options=self.gpu_options		,     )
												pipe.set_progress_bar_config(disable=__A   )

												_A								= '''A fantasy landscape, trending on artstation'''

												_A								= torch.manual_seed(0   )
												_A								= pipe(
												    prompt=__A		,     image=__A		,     guidance_scale=7.5		,     num_inference_steps=10		,     generator=__A		,     output_type='''np'''		,     )
												_A								= output.images
												_A								= images[0, 2_55:2_58, 3_83:3_86, -1]

												assert images.shape == (1, 5_12, 5_12, 3)
												_A								= np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972]   )
												# 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:   Tuple   )    ->				Tuple:
												_A								= load_image(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
												    '''/img2img/sketch-mountains-input.jpg'''   )
												_A								= init_image.resize((1_28, 1_28)   )
												_A								= LMSDiscreteScheduler.from_pretrained(
												    '''ssube/stable-diffusion-x4-upscaler-onnx'''		,     subfolder='''scheduler'''   )
												_A								= OnnxStableDiffusionUpscalePipeline.from_pretrained(
												    '''ssube/stable-diffusion-x4-upscaler-onnx'''		,     scheduler=__A		,     provider=self.gpu_provider		,     sess_options=self.gpu_options		,     )
												pipe.set_progress_bar_config(disable=__A   )

												_A								= '''A fantasy landscape, trending on artstation'''

												_A								= torch.manual_seed(0   )
												_A								= pipe(
												    prompt=__A		,     image=__A		,     guidance_scale=7.5		,     num_inference_steps=20		,     generator=__A		,     output_type='''np'''		,     )
												_A								= output.images
												_A								= images[0, 2_55:2_58, 3_83:3_86, -1]

												assert images.shape == (1, 5_12, 5_12, 3)
												_A								= np.array(
												    [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566]   )
												# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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











import gc
import unittest

from transformers import CTRLConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CTRLForSequenceClassification,
				    CTRLLMHeadModel,
				    CTRLModel,
				)





class 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

							def __init__(  self:   Tuple		,     __A:   Any		,     __A:   List[Any]=14		,     __A:   Dict=7		,     __A:   List[str]=True		,     __A:   Tuple=True		,     __A:   Union[str, Any]=True		,     __A:   List[Any]=True		,     __A:   Optional[int]=True		,     __A:   Tuple=99		,     __A:   Optional[Any]=32		,     __A:   List[str]=5		,     __A:   Dict=4		,     __A:   str=37		,     __A:   Dict="gelu"		,     __A:   List[str]=0.1		,     __A:   str=0.1		,     __A:   Any=5_12		,     __A:   Union[str, Any]=16		,     __A:   List[Any]=2		,     __A:   Tuple=0.02		,     __A:   Tuple=3		,     __A:   Union[str, Any]=4		,     __A:   Any=None		,     )    ->				Optional[Any]:
												_A								= parent
												_A								= batch_size
												_A								= seq_length
												_A								= is_training
												_A								= use_token_type_ids
												_A								= use_input_mask
												_A								= use_labels
												_A								= use_mc_token_ids
												_A								= vocab_size
												_A								= hidden_size
												_A								= num_hidden_layers
												_A								= num_attention_heads
												_A								= intermediate_size
												_A								= hidden_act
												_A								= hidden_dropout_prob
												_A								= attention_probs_dropout_prob
												_A								= max_position_embeddings
												_A								= type_vocab_size
												_A								= type_sequence_label_size
												_A								= initializer_range
												_A								= num_labels
												_A								= num_choices
												_A								= scope
												_A								= self.vocab_size - 1

							def       __A (  self:   Optional[int]   )    ->				Union[str, Any]:
												_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size   )

												_A								= None
												if self.use_input_mask:
																	_A								= random_attention_mask([self.batch_size, self.seq_length]   )

												_A								= None
												if self.use_token_type_ids:
																	_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.type_vocab_size   )

												_A								= None
												if self.use_mc_token_ids:
																	_A								= ids_tensor([self.batch_size, self.num_choices]		,     self.seq_length   )

												_A								= None
												_A								= None
												_A								= None
												if self.use_labels:
																	_A								= ids_tensor([self.batch_size]		,     self.type_sequence_label_size   )
																	_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.num_labels   )
																	_A								= ids_tensor([self.batch_size]		,     self.num_choices   )

												_A								= self.get_config()

												_A								= ids_tensor([self.num_hidden_layers, self.num_attention_heads]		,     2   )

												return (
												    config,
												    input_ids,
												    input_mask,
												    head_mask,
												    token_type_ids,
												    mc_token_ids,
												    sequence_labels,
												    token_labels,
												    choice_labels,
												)

							def       __A (  self:   Optional[int]   )    ->				List[Any]:
												return CTRLConfig(
												    vocab_size=self.vocab_size		,     n_embd=self.hidden_size		,     n_layer=self.num_hidden_layers		,     n_head=self.num_attention_heads		,     n_positions=self.max_position_embeddings		,     pad_token_id=self.pad_token_id		,     )

							def       __A (  self:   Union[str, Any]		,     __A:   Union[str, Any]		,     __A:   Dict		,     __A:   Optional[int]		,     __A:   List[str]		,     __A:   List[str]		,     *__A:   Optional[int]   )    ->				Optional[Any]:
												_A								= CTRLModel(config=__A   )
												model.to(__A   )
												model.eval()

												model(__A		,     token_type_ids=__A		,     head_mask=__A   )
												model(__A		,     token_type_ids=__A   )
												_A								= model(__A   )
												self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)   )
												self.parent.assertEqual(len(result.past_key_values   )		,     config.n_layer   )

							def       __A (  self:   Optional[Any]		,     __A:   List[str]		,     __A:   Dict		,     __A:   List[Any]		,     __A:   List[Any]		,     __A:   Any		,     *__A:   Any   )    ->				str:
												_A								= CTRLLMHeadModel(__A   )
												model.to(__A   )
												model.eval()

												_A								= model(__A		,     token_type_ids=__A		,     labels=__A   )
												self.parent.assertEqual(result.loss.shape		,     ()   )
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.vocab_size)   )

							def       __A (  self:   Optional[int]   )    ->				Dict:
												_A								= self.prepare_config_and_inputs()

												(
												    (
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,
												)								= config_and_inputs

												_A								= {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

												return config, inputs_dict



							def       __A (  self:   List[str]		,     __A:   Dict		,     __A:   Dict		,     __A:   Tuple		,     __A:   List[Any]		,     *__A:   Optional[int]   )    ->				Any:
												_A								= self.num_labels
												_A								= CTRLForSequenceClassification(__A   )
												model.to(__A   )
												model.eval()
												_A								= ids_tensor([self.batch_size]		,     self.type_sequence_label_size   )
												_A								= model(__A		,     token_type_ids=__A		,     labels=__A   )
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.num_labels)   )





@require_torch
class 						SCREAMING_SNAKE_CASE				( snake_case  ,	snake_case  ,	snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							A_						  =					(CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
							A_						  =					(CTRLLMHeadModel,) if is_torch_available() else ()
							A_						  =					(
							    {
							        "feature-extraction": CTRLModel,
							        "text-classification": CTRLForSequenceClassification,
							        "text-generation": CTRLLMHeadModel,
							        "zero-shot": CTRLForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							A_						  =					True
							A_						  =					False
							A_						  =					False

							def       __A (  self:   Any		,     __A:   List[Any]		,     __A:   int		,     __A:   Optional[Any]		,     __A:   Optional[int]		,     __A:   List[Any]   )    ->				List[str]:
												if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
																	# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
																	# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
																	# config could not be created.
																	return True

												return False

							def       __A (  self:   Any   )    ->				Union[str, Any]:
												_A								= CTRLModelTester(self   )
												_A								= ConfigTester(self		,     config_class=__A		,     n_embd=37   )

							def       __A (  self:   Optional[int]   )    ->				List[Any]:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()

							def       __A (  self:   Dict   )    ->				Any:
												self.config_tester.run_common_tests()

							def       __A (  self:   str   )    ->				Optional[Any]:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*__A   )

							def       __A (  self:   List[str]   )    ->				Any:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*__A   )

							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
							def       __A (  self:   Optional[Any]   )    ->				int:
												pass

							@slow
							def       __A (  self:   Tuple   )    ->				Dict:
												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A								= CTRLModel.from_pretrained(__A   )
																	self.assertIsNotNone(__A   )



							@unittest.skip('''The model doesn\'t support left padding'''   )  # and it's not used enough to be worth fixing :)
							def       __A (  self:   Any   )    ->				Union[str, Any]:
												pass





@require_torch
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

							def       __A (  self:   int   )    ->				Union[str, Any]:
												super().tearDown()
												# clean-up as much as possible GPU memory occupied by PyTorch
												gc.collect()
												torch.cuda.empty_cache()



							@slow
							def       __A (  self:   Any   )    ->				Any:
												_A								= CTRLLMHeadModel.from_pretrained('''ctrl'''   )
												model.to(__A   )
												_A								= torch.tensor(
												    [[1_18_59, 0, 16_11, 8]]		,     dtype=torch.long		,     device=__A   )  # Legal the president is
												_A								= [
												    1_18_59,
												    0,
												    16_11,
												    8,
												    5,
												    1_50,
												    2_64_49,
												    2,
												    19,
												    3_48,
												    4_69,
												    3,
												    25_95,
												    48,
												    2_07_40,
												    24_65_33,
												    24_65_33,
												    19,
												    30,
												    5,
												]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

												_A								= model.generate(__A		,     do_sample=__A   )
												self.assertListEqual(output_ids[0].tolist()		,     __A   )



