

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     ):
    # TODO: is there an appropriate internal test set?
    __lowerCamelCase						:       int														=     """ssube/stable-diffusion-x4-upscaler-onnx"""





    def       snake_case_				(      self						,   a=0):
         lowercase__    :   List[str]      =       floats_tensor((1, 3, 128, 128)						,   rng=random.Random(a))
         lowercase__    :   Optional[int]      =       torch.manual_seed(a)
         lowercase__    :   Dict      =       {
             '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       snake_case_				(      self):
         lowercase__    :   int      =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,   provider='CPUExecutionProvider')
         pipe.set_progress_bar_config(disable=a)

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

         # started as 128, should now be 512
         assert image.shape == (1, 512, 512, 3)
         lowercase__    :   str      =       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       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,   provider='CPUExecutionProvider')
         lowercase__    :   Any      =       PNDMScheduler.from_config(pipe.scheduler.config						,   skip_prk_steps=a)
         pipe.set_progress_bar_config(disable=a)

         lowercase__    :   Union[str, Any]      =       self.get_dummy_inputs()
         lowercase__    :   Tuple      =       pipe(**a).images
         lowercase__    :   Tuple      =       image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         lowercase__    :   Union[str, Any]      =       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       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,   provider='CPUExecutionProvider')
         lowercase__    :   List[Any]      =       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
         pipe.set_progress_bar_config(disable=a)

         lowercase__    :   Tuple      =       self.get_dummy_inputs()
         lowercase__    :   List[Any]      =       pipe(**a).images
         lowercase__    :   Dict      =       image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         lowercase__    :   List[str]      =       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       snake_case_				(      self):
         lowercase__    :   Union[str, Any]      =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,   provider='CPUExecutionProvider')
         lowercase__    :   Union[str, Any]      =       EulerDiscreteScheduler.from_config(pipe.scheduler.config)
         pipe.set_progress_bar_config(disable=a)

         lowercase__    :   List[Any]      =       self.get_dummy_inputs()
         lowercase__    :   Optional[int]      =       pipe(**a).images
         lowercase__    :   Tuple      =       image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         lowercase__    :   Optional[Any]      =       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       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,   provider='CPUExecutionProvider')
         lowercase__    :   Optional[int]      =       EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
         pipe.set_progress_bar_config(disable=a)

         lowercase__    :   Optional[int]      =       self.get_dummy_inputs()
         lowercase__    :   Optional[int]      =       pipe(**a).images
         lowercase__    :   List[Any]      =       image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         lowercase__    :   Optional[Any]      =       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     ):





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





    @property
    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       ort.SessionOptions()
         lowercase__    :   Optional[int]      =       False
         return options





    def       snake_case_				(      self):
         lowercase__    :   List[Any]      =       load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/img2img/sketch-mountains-input.jpg')
         lowercase__    :   str      =       init_image.resize((128, 128))
         # using the PNDM scheduler by default
         lowercase__    :   List[str]      =       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)

         lowercase__    :   Optional[Any]      =       'A fantasy landscape, trending on artstation'

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

         assert images.shape == (1, 512, 512, 3)
         lowercase__    :   Optional[Any]      =       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       snake_case_				(      self):
         lowercase__    :   Any      =       load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/img2img/sketch-mountains-input.jpg')
         lowercase__    :   Optional[Any]      =       init_image.resize((128, 128))
         lowercase__    :   Dict      =       LMSDiscreteScheduler.from_pretrained(
             'ssube/stable-diffusion-x4-upscaler-onnx'						,   subfolder='scheduler')
         lowercase__    :   Tuple      =       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)

         lowercase__    :   Optional[int]      =       'A fantasy landscape, trending on artstation'

         lowercase__    :   List[Any]      =       torch.manual_seed(0)
         lowercase__    :   Union[str, Any]      =       pipe(
             prompt=a						,   image=a						,   guidance_scale=7.5						,   num_inference_steps=20						,   generator=a						,   output_type='np'						,   )
         lowercase__    :   int      =       output.images
         lowercase__    :   Optional[Any]      =       images[0, 255:258, 383:386, -1]

         assert images.shape == (1, 512, 512, 3)
         lowercase__    :   List[str]      =       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 unittest

from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device

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.models.esm.modeling_esmfold import EsmForProteinFolding


class       SCREAMING_SNAKE_CASE__					:





    def __init__(      self						,   a						,   a=13						,   a=7						,   a=False						,   a=True						,   a=False						,   a=False						,   a=19						,   a=32						,   a=5						,   a=4						,   a=37						,   a="gelu"						,   a=0.1						,   a=0.1						,   a=512						,   a=16						,   a=2						,   a=0.02						,   a=3						,   a=4						,   a=None						,   ):
         lowercase__    :   Optional[Any]      =       parent
         lowercase__    :   Dict      =       batch_size
         lowercase__    :   Union[str, Any]      =       seq_length
         lowercase__    :   Optional[Any]      =       is_training
         lowercase__    :   Tuple      =       use_input_mask
         lowercase__    :   List[str]      =       use_token_type_ids
         lowercase__    :   Optional[Any]      =       use_labels
         lowercase__    :   List[str]      =       vocab_size
         lowercase__    :   Optional[int]      =       hidden_size
         lowercase__    :   List[str]      =       num_hidden_layers
         lowercase__    :   Any      =       num_attention_heads
         lowercase__    :   int      =       intermediate_size
         lowercase__    :   Any      =       hidden_act
         lowercase__    :   Any      =       hidden_dropout_prob
         lowercase__    :   str      =       attention_probs_dropout_prob
         lowercase__    :   List[Any]      =       max_position_embeddings
         lowercase__    :   int      =       type_vocab_size
         lowercase__    :   List[Any]      =       type_sequence_label_size
         lowercase__    :   str      =       initializer_range
         lowercase__    :   List[str]      =       num_labels
         lowercase__    :   Union[str, Any]      =       num_choices
         lowercase__    :   Optional[int]      =       scope





    def       snake_case_				(      self):
         lowercase__    :   List[Any]      =       ids_tensor([self.batch_size, self.seq_length]						,   self.vocab_size)

         lowercase__    :   List[Any]      =       None
         if self.use_input_mask:
              lowercase__    :   Union[str, Any]      =       random_attention_mask([self.batch_size, self.seq_length])

         lowercase__    :   int      =       None
         lowercase__    :   Optional[int]      =       None
         lowercase__    :   Optional[int]      =       None
         if self.use_labels:
              lowercase__    :   Optional[int]      =       ids_tensor([self.batch_size]						,   self.type_sequence_label_size)
              lowercase__    :   str      =       ids_tensor([self.batch_size, self.seq_length]						,   self.num_labels)
              lowercase__    :   str      =       ids_tensor([self.batch_size]						,   self.num_choices)

         lowercase__    :   int      =       self.get_config()

         return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels





    def       snake_case_				(      self):
         lowercase__    :   str      =       EsmConfig(
             vocab_size=33						,   hidden_size=self.hidden_size						,   pad_token_id=1						,   num_hidden_layers=self.num_hidden_layers						,   num_attention_heads=self.num_attention_heads						,   intermediate_size=self.intermediate_size						,   hidden_act=self.hidden_act						,   hidden_dropout_prob=self.hidden_dropout_prob						,   attention_probs_dropout_prob=self.attention_probs_dropout_prob						,   max_position_embeddings=self.max_position_embeddings						,   type_vocab_size=self.type_vocab_size						,   initializer_range=self.initializer_range						,   is_folding_model=a						,   esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False}						,   )
         return config





    def       snake_case_				(      self						,   a						,   a						,   a						,   a						,   a						,   a):
         lowercase__    :   Dict      =       EsmForProteinFolding(config=a).float()
         model.to(a)
         model.eval()
         lowercase__    :   Union[str, Any]      =       model(a						,   attention_mask=a)
         lowercase__    :   Dict      =       model(a)
         lowercase__    :   int      =       model(a)

         self.parent.assertEqual(result.positions.shape						,   (8, self.batch_size, self.seq_length, 14, 3))
         self.parent.assertEqual(result.angles.shape						,   (8, self.batch_size, self.seq_length, 7, 2))





    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       self.prepare_config_and_inputs()
         (
             (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , (
             lowercase__
         )      , 
         )    :   int      =       config_and_inputs
         lowercase__    :   Optional[int]      =       {'input_ids': input_ids, 'attention_mask': input_mask}
         return config, inputs_dict



@require_torch
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       __snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       Dict														=     False

    __lowerCamelCase						:       Dict														=     (EsmForProteinFolding,) if is_torch_available() else ()
    __lowerCamelCase						:       Union[str, Any]														=     ()
    __lowerCamelCase						:       List[Any]														=     {} if is_torch_available() else {}
    __lowerCamelCase						:       Optional[Any]														=     False





    def       snake_case_				(      self):
         lowercase__    :   Tuple      =       EsmFoldModelTester(self)
         lowercase__    :   List[Any]      =       ConfigTester(self						,   config_class=a						,   hidden_size=37)





    def       snake_case_				(      self):
         self.config_tester.run_common_tests()





    def       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a)





    @unittest.skip('Does not support attention outputs')
    def       snake_case_				(      self):
         pass





    @unittest.skip
    def       snake_case_				(      self):
         pass





    @unittest.skip('Esm does not support embedding resizing')
    def       snake_case_				(      self):
         pass





    @unittest.skip('Esm does not support embedding resizing')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support passing input embeds!')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support head pruning.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not output hidden states in the normal way.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMfold does not output hidden states in the normal way.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold only has one output format.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold does not support input chunking.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support torchscript compilation.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('ESMFold doesn\'t support data parallel.')
    def       snake_case_				(      self):
         pass





    @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
    def       snake_case_				(      self):
         pass



@require_torch
class       SCREAMING_SNAKE_CASE__					(__snake_case     ):





    @slow
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       EsmForProteinFolding.from_pretrained('facebook/esmfold_v1').float()
         model.eval()
         lowercase__    :   Optional[Any]      =       torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
         lowercase__    :   Optional[int]      =       model(a)['positions']
         lowercase__    :   Dict      =       torch.tensor([2.5_828, 0.7_993, -10.9_334]						,   dtype=torch.floataa)
         self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0]						,   a						,   atol=1e-4))

