
"""simple docstring"""



import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import YolosForObjectDetection, YolosModel
 from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class 		a_						:







    def __init__(			self			:       Tuple     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       int=13     ,					__UpperCamelCase			:       int=[30, 30]     ,					__UpperCamelCase			:       int=2     ,					__UpperCamelCase			:       Tuple=3     ,					__UpperCamelCase			:       Dict=True     ,					__UpperCamelCase			:       List[Any]=True     ,					__UpperCamelCase			:       Tuple=32     ,					__UpperCamelCase			:       Dict=5     ,					__UpperCamelCase			:       Dict=4     ,					__UpperCamelCase			:       List[str]=37     ,					__UpperCamelCase			:       List[str]="gelu"     ,					__UpperCamelCase			:       Dict=0.1     ,					__UpperCamelCase			:       Dict=0.1     ,					__UpperCamelCase			:       Any=10     ,					__UpperCamelCase			:       List[Any]=0.0_2     ,					__UpperCamelCase			:       Dict=3     ,					__UpperCamelCase			:       Optional[Any]=None     ,					__UpperCamelCase			:       List[Any]=8     ,					__UpperCamelCase			:       Union[str, Any]=10     ,					)		->str:
        _UpperCAmelCase          =   parent
        _UpperCAmelCase          =   batch_size
        _UpperCAmelCase          =   image_size
        _UpperCAmelCase          =   patch_size
        _UpperCAmelCase          =   num_channels
        _UpperCAmelCase          =   is_training
        _UpperCAmelCase          =   use_labels
        _UpperCAmelCase          =   hidden_size
        _UpperCAmelCase          =   num_hidden_layers
        _UpperCAmelCase          =   num_attention_heads
        _UpperCAmelCase          =   intermediate_size
        _UpperCAmelCase          =   hidden_act
        _UpperCAmelCase          =   hidden_dropout_prob
        _UpperCAmelCase          =   attention_probs_dropout_prob
        _UpperCAmelCase          =   type_sequence_label_size
        _UpperCAmelCase          =   initializer_range
        _UpperCAmelCase          =   num_labels
        _UpperCAmelCase          =   scope
        _UpperCAmelCase          =   n_targets
        _UpperCAmelCase          =   num_detection_tokens
        # we set the expected sequence length (which is used in several tests)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
        _UpperCAmelCase          =   (image_size[1] // patch_size) * (image_size[0] // patch_size)
        _UpperCAmelCase          =   num_patches + 1 + self.num_detection_tokens







    def      _snake_case					(			self			:       Optional[int]     )		->List[str]:
        _UpperCAmelCase          =   floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )

        _UpperCAmelCase          =   None
        if self.use_labels:
            # labels is a list of Dict (each Dict being the labels for a given example in the batch)
            _UpperCAmelCase          =   []
            for i in range(self.batch_size     ):
                _UpperCAmelCase          =   {}
                _UpperCAmelCase          =   torch.randint(
                    high=self.num_labels     ,					size=(self.n_targets,)     ,					device=UpperCamelCase__     )
                _UpperCAmelCase          =   torch.rand(self.n_targets     ,					4     ,					device=UpperCamelCase__     )
                labels.append(UpperCamelCase__     )

        _UpperCAmelCase          =   self.get_config()

        return config, pixel_values, labels







    def      _snake_case					(			self			:       Optional[int]     )		->Union[str, Any]:
        return YolosConfig(
            image_size=self.image_size     ,					patch_size=self.patch_size     ,					num_channels=self.num_channels     ,					hidden_size=self.hidden_size     ,					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     ,					is_decoder=UpperCamelCase__     ,					initializer_range=self.initializer_range     ,					num_detection_tokens=self.num_detection_tokens     ,					num_labels=self.num_labels     ,					)







    def      _snake_case					(			self			:       Union[str, Any]     ,					__UpperCamelCase			:       List[str]     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       int     )		->Any:
        _UpperCAmelCase          =   YolosModel(config=UpperCamelCase__     )
        model.to(UpperCamelCase__     )
        model.eval()
        _UpperCAmelCase          =   model(UpperCamelCase__     )
        self.parent.assertEqual(
            result.last_hidden_state.shape     ,					(self.batch_size, self.expected_seq_len, self.hidden_size)     )







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       int     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       int     )		->Optional[int]:
        _UpperCAmelCase          =   YolosForObjectDetection(UpperCamelCase__     )
        model.to(UpperCamelCase__     )
        model.eval()

        _UpperCAmelCase          =   model(pixel_values=UpperCamelCase__     )
        _UpperCAmelCase          =   model(UpperCamelCase__     )

        self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_detection_tokens, self.num_labels + 1)     )
        self.parent.assertEqual(result.pred_boxes.shape     ,					(self.batch_size, self.num_detection_tokens, 4)     )

        _UpperCAmelCase          =   model(pixel_values=UpperCamelCase__     ,					labels=UpperCamelCase__     )

        self.parent.assertEqual(result.loss.shape     ,					()     )
        self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.num_detection_tokens, self.num_labels + 1)     )
        self.parent.assertEqual(result.pred_boxes.shape     ,					(self.batch_size, self.num_detection_tokens, 4)     )







    def      _snake_case					(			self			:       Dict     )		->Union[str, Any]:
        _UpperCAmelCase          =   self.prepare_config_and_inputs()
        _UpperCAmelCase          =   config_and_inputs
        _UpperCAmelCase          =   {'''pixel_values''': pixel_values}
        return config, inputs_dict







@require_torch
class 		a_						( SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_     ,						unittest.TestCase	):
    a      :				Dict     =				(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
    a      :				str     =				(
        {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
    )

    a      :				Optional[Any]     =				False
    a      :				Tuple     =				False
    a      :				Optional[Any]     =				False
    a      :				Union[str, Any]     =				False







    def      _snake_case					(			self			:       Optional[Any]     ,					__UpperCamelCase			:       int     ,					__UpperCamelCase			:       Dict     ,					__UpperCamelCase			:       Dict=False     )		->Optional[int]:
        _UpperCAmelCase          =   super()._prepare_for_class(UpperCamelCase__     ,					UpperCamelCase__     ,					return_labels=UpperCamelCase__     )

        if return_labels:
            if model_class.__name__ == "YolosForObjectDetection":
                _UpperCAmelCase          =   []
                for i in range(self.model_tester.batch_size     ):
                    _UpperCAmelCase          =   {}
                    _UpperCAmelCase          =   torch.ones(
                        size=(self.model_tester.n_targets,)     ,					device=UpperCamelCase__     ,					dtype=torch.long     )
                    _UpperCAmelCase          =   torch.ones(
                        self.model_tester.n_targets     ,					4     ,					device=UpperCamelCase__     ,					dtype=torch.float     )
                    labels.append(UpperCamelCase__     )
                _UpperCAmelCase          =   labels

        return inputs_dict







    def      _snake_case					(			self			:       Dict     )		->Tuple:
        _UpperCAmelCase          =   YolosModelTester(self     )
        _UpperCAmelCase          =   ConfigTester(self     ,					config_class=UpperCamelCase__     ,					has_text_modality=UpperCamelCase__     ,					hidden_size=37     )







    def      _snake_case					(			self			:       Optional[Any]     )		->List[Any]:
        self.config_tester.run_common_tests()







    def      _snake_case					(			self			:       Optional[Any]     )		->Tuple:
        # YOLOS does not use inputs_embeds
        pass







    def      _snake_case					(			self			:       Any     )		->Optional[Any]:
        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            self.assertIsInstance(model.get_input_embeddings()     ,					(nn.Module)     )
            _UpperCAmelCase          =   model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(UpperCamelCase__     ,					nn.Linear     )     )







    def      _snake_case					(			self			:       int     )		->Dict:
        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            _UpperCAmelCase          =   inspect.signature(model.forward     )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            _UpperCAmelCase          =   [*signature.parameters.keys()]

            _UpperCAmelCase          =   ['''pixel_values''']
            self.assertListEqual(arg_names[:1]     ,					UpperCamelCase__     )







    def      _snake_case					(			self			:       Tuple     )		->List[str]:
        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCamelCase__     )







    def      _snake_case					(			self			:       Dict     )		->Optional[Any]:
        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCAmelCase          =   True

        # in YOLOS, the seq_len is different
        _UpperCAmelCase          =   self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   False
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            model.to(UpperCamelCase__     )
            model.eval()
            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(UpperCamelCase__     ,					UpperCamelCase__     )     )
            _UpperCAmelCase          =   outputs.attentions
            self.assertEqual(len(UpperCamelCase__     )     ,					self.model_tester.num_hidden_layers     )

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            model.to(UpperCamelCase__     )
            model.eval()
            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(UpperCamelCase__     ,					UpperCamelCase__     )     )
            _UpperCAmelCase          =   outputs.attentions
            self.assertEqual(len(UpperCamelCase__     )     ,					self.model_tester.num_hidden_layers     )

            self.assertListEqual(
                list(attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, seq_len, seq_len]     ,					)
            _UpperCAmelCase          =   len(UpperCamelCase__     )

            # Check attention is always last and order is fine
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   True
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            model.to(UpperCamelCase__     )
            model.eval()
            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(UpperCamelCase__     ,					UpperCamelCase__     )     )

            _UpperCAmelCase          =   1
            self.assertEqual(out_len + added_hidden_states     ,					len(UpperCamelCase__     )     )

            _UpperCAmelCase          =   outputs.attentions

            self.assertEqual(len(UpperCamelCase__     )     ,					self.model_tester.num_hidden_layers     )
            self.assertListEqual(
                list(self_attentions[0].shape[-3:]     )     ,					[self.model_tester.num_attention_heads, seq_len, seq_len]     ,					)







    def      _snake_case					(			self			:       List[str]     )		->str:
        def check_hidden_states_output(__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       Optional[Any]     ,					__UpperCamelCase			:       List[str]     ):
            _UpperCAmelCase          =   model_class(UpperCamelCase__     )
            model.to(UpperCamelCase__     )
            model.eval()

            with torch.no_grad():
                _UpperCAmelCase          =   model(**self._prepare_for_class(UpperCamelCase__     ,					UpperCamelCase__     )     )

            _UpperCAmelCase          =   outputs.hidden_states

            _UpperCAmelCase          =   getattr(
                self.model_tester     ,					"""expected_num_hidden_layers"""     ,					self.model_tester.num_hidden_layers + 1     )
            self.assertEqual(len(UpperCamelCase__     )     ,					UpperCamelCase__     )

            # YOLOS has a different seq_length
            _UpperCAmelCase          =   self.model_tester.expected_seq_len

            self.assertListEqual(
                list(hidden_states[0].shape[-2:]     )     ,					[seq_length, self.model_tester.hidden_size]     ,					)

        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   True
            check_hidden_states_output(UpperCamelCase__     ,					UpperCamelCase__     ,					UpperCamelCase__     )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            _UpperCAmelCase          =   True

            check_hidden_states_output(UpperCamelCase__     ,					UpperCamelCase__     ,					UpperCamelCase__     )







    def      _snake_case					(			self			:       Optional[int]     )		->Tuple:
        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*UpperCamelCase__     )







    @slow
    def      _snake_case					(			self			:       Union[str, Any]     )		->Any:
        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _UpperCAmelCase          =   YolosModel.from_pretrained(UpperCamelCase__     )
            self.assertIsNotNone(UpperCamelCase__     )







def  _UpperCamelCase	(						)    ->  List[str]:





    """simple docstring"""

    _UpperCAmelCase          =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
    return image







@require_torch
@require_vision
class 		a_						( unittest.TestCase	):







    @cached_property
    def      _snake_case					(			self			:       List[str]     )		->str:
        return AutoImageProcessor.from_pretrained("""hustvl/yolos-small"""     ) if is_vision_available() else None







    @slow
    def      _snake_case					(			self			:       Any     )		->List[Any]:
        _UpperCAmelCase          =   YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""     ).to(UpperCamelCase__     )

        _UpperCAmelCase          =   self.default_image_processor
        _UpperCAmelCase          =   prepare_img()
        _UpperCAmelCase          =   image_processor(images=UpperCamelCase__     ,					return_tensors="""pt"""     ).to(UpperCamelCase__     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(inputs.pixel_values     )

        # verify outputs
        _UpperCAmelCase          =   torch.Size((1, 1_00, 92)     )
        self.assertEqual(outputs.logits.shape     ,					UpperCamelCase__     )

        _UpperCAmelCase          =   torch.tensor(
            [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]     ,					device=UpperCamelCase__     ,					)
        _UpperCAmelCase          =   torch.tensor(
            [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]     ,					device=UpperCamelCase__     )
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,					UpperCamelCase__     ,					atol=1e-4     )     )
        self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]     ,					UpperCamelCase__     ,					atol=1e-4     )     )

        # verify postprocessing
        _UpperCAmelCase          =   image_processor.post_process_object_detection(
            UpperCamelCase__     ,					threshold=0.3     ,					target_sizes=[image.size[::-1]]     )[0]
        _UpperCAmelCase          =   torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]     ).to(UpperCamelCase__     )
        _UpperCAmelCase          =   [75, 75, 17, 63, 17]
        _UpperCAmelCase          =   torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]     ).to(UpperCamelCase__     )

        self.assertEqual(len(results["""scores"""]     )     ,					5     )
        self.assertTrue(torch.allclose(results["""scores"""]     ,					UpperCamelCase__     ,					atol=1e-4     )     )
        self.assertSequenceEqual(results["""labels"""].tolist()     ,					UpperCamelCase__     )
        self.assertTrue(torch.allclose(results["""boxes"""][0, :]     ,					UpperCamelCase__     )     )

"""simple docstring"""



import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()




class 		a_						( unittest.TestCase	):







    @property
    def      _snake_case					(			self			:       Dict     )		->int:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   UNetaDModel(
            block_out_channels=(32, 64)     ,					layers_per_block=2     ,					sample_size=32     ,					in_channels=3     ,					out_channels=3     ,					down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")     ,					up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")     ,					)
        return model







    @property
    def      _snake_case					(			self			:       Optional[Any]     )		->str:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   VQModel(
            block_out_channels=[32, 64]     ,					in_channels=3     ,					out_channels=3     ,					down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]     ,					up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]     ,					latent_channels=3     ,					)
        return model







    @property
    def      _snake_case					(			self			:       List[Any]     )		->Optional[int]:






        '''simple docstring'''






        torch.manual_seed(0     )
        _UpperCAmelCase          =   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=10_00     ,					)
        return CLIPTextModel(__UpperCamelCase     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   self.dummy_uncond_unet
        _UpperCAmelCase          =   DDIMScheduler()
        _UpperCAmelCase          =   self.dummy_vq_model

        _UpperCAmelCase          =   LDMPipeline(unet=__UpperCamelCase     ,					vqvae=__UpperCamelCase     ,					scheduler=__UpperCamelCase     )
        ldm.to(__UpperCamelCase     )
        ldm.set_progress_bar_config(disable=__UpperCamelCase     )

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=2     ,					output_type="""numpy"""     ).images

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=2     ,					output_type="""numpy"""     ,					return_dict=__UpperCamelCase     )[0]

        _UpperCAmelCase          =   image[0, -3:, -3:, -1]
        _UpperCAmelCase          =   image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        _UpperCAmelCase          =   np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2]     )
        _UpperCAmelCase          =   1e-2 if torch_device != """mps""" else 3e-2

        assert np.abs(image_slice.flatten() - expected_slice     ).max() < tolerance
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < tolerance







@slow
@require_torch
class 		a_						( unittest.TestCase	):







    def      _snake_case					(			self			:       List[Any]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256"""     )
        ldm.to(__UpperCamelCase     )
        ldm.set_progress_bar_config(disable=__UpperCamelCase     )

        _UpperCAmelCase          =   torch.manual_seed(0     )
        _UpperCAmelCase          =   ldm(generator=__UpperCamelCase     ,					num_inference_steps=5     ,					output_type="""numpy"""     ).images

        _UpperCAmelCase          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 2_56, 2_56, 3)
        _UpperCAmelCase          =   np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7]     )
        _UpperCAmelCase          =   1e-2 if torch_device != """mps""" else 3e-2

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