



'''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    lowerCamelCase__  :
     """simple docstring"""



     def __init__(self				,			__a				,			__a=13				,			__a=[30, 30]				,			__a=2				,			__a=3				,			__a=True				,			__a=True				,			__a=32				,			__a=5				,			__a=4				,			__a=37				,			__a="gelu"				,			__a=0.1				,			__a=0.1				,			__a=10				,			__a=0.02				,			__a=3				,			__a=None				,			__a=8				,			__a=10				,			):






           '''simple docstring'''



           lowerCamelCase								=		parent
           lowerCamelCase								=		batch_size
           lowerCamelCase								=		image_size
           lowerCamelCase								=		patch_size
           lowerCamelCase								=		num_channels
           lowerCamelCase								=		is_training
           lowerCamelCase								=		use_labels
           lowerCamelCase								=		hidden_size
           lowerCamelCase								=		num_hidden_layers
           lowerCamelCase								=		num_attention_heads
           lowerCamelCase								=		intermediate_size
           lowerCamelCase								=		hidden_act
           lowerCamelCase								=		hidden_dropout_prob
           lowerCamelCase								=		attention_probs_dropout_prob
           lowerCamelCase								=		type_sequence_label_size
           lowerCamelCase								=		initializer_range
           lowerCamelCase								=		num_labels
           lowerCamelCase								=		scope
           lowerCamelCase								=		n_targets
           lowerCamelCase								=		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
           lowerCamelCase								=		(image_size[1] // patch_size) * (image_size[0] // patch_size)
           lowerCamelCase								=		num_patches + 1 + self.num_detection_tokens







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]    )

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

           lowerCamelCase								=		self.get_config()

           return config, pixel_values, labels







     def 						_a      (self    ):






           '''simple docstring'''



           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=snake_case__				,			initializer_range=self.initializer_range				,			num_detection_tokens=self.num_detection_tokens				,			num_labels=self.num_labels				,			)







     def 						_a      (self				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		YolosModel(config=snake_case__    )
           model.to(snake_case__    )
           model.eval()
           lowerCamelCase								=		model(snake_case__    )
           self.parent.assertEqual(
               result.last_hidden_state.shape				,			(self.batch_size, self.expected_seq_len, self.hidden_size)    )







     def 						_a      (self				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		YolosForObjectDetection(snake_case__    )
           model.to(snake_case__    )
           model.eval()

           lowerCamelCase								=		model(pixel_values=snake_case__    )
           lowerCamelCase								=		model(snake_case__    )

           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)    )

           lowerCamelCase								=		model(pixel_values=snake_case__				,			labels=snake_case__    )

           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 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.prepare_config_and_inputs()
           lowerCamelCase			,							lowerCamelCase			,							lowerCamelCase								=		config_and_inputs
           lowerCamelCase								=		{"pixel_values": pixel_values}
           return config, inputs_dict





@require_torch
class    lowerCamelCase__  (						__a       ,    __a       ,    unittest.TestCase):
     """simple docstring"""



     _A       =			(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
     _A       =			(
         {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
     )

     _A       =			False
     _A       =			False
     _A       =			False
     _A       =			False







     def 						_a      (self				,			__a				,			__a				,			__a=False    ):






           '''simple docstring'''



           lowerCamelCase								=		super()._prepare_for_class(snake_case__				,			snake_case__				,			return_labels=snake_case__    )

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

           return inputs_dict







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		YolosModelTester(self    )
           lowerCamelCase								=		ConfigTester(self				,			config_class=snake_case__				,			has_text_modality=snake_case__				,			hidden_size=37    )







     def 						_a      (self    ):






           '''simple docstring'''



           self.config_tester.run_common_tests()







     def 						_a      (self    ):






           '''simple docstring'''



           pass







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase			,							lowerCamelCase								=		self.model_tester.prepare_config_and_inputs_for_common()

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







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase			,							lowerCamelCase								=		self.model_tester.prepare_config_and_inputs_for_common()

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

                 lowerCamelCase								=		["pixel_values"]
                 self.assertListEqual(arg_names[:1]				,			snake_case__    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*snake_case__    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase			,							lowerCamelCase								=		self.model_tester.prepare_config_and_inputs_for_common()
           lowerCamelCase								=		True

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

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

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

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

                 lowerCamelCase								=		1
                 self.assertEqual(out_len + added_hidden_states				,			len(snake_case__    )    )

                 lowerCamelCase								=		outputs.attentions

                 self.assertEqual(len(snake_case__    )				,			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 						_a      (self    ):






           '''simple docstring'''



           def check_hidden_states_output(__a				,			__a				,			__a    ):
                 lowerCamelCase								=		model_class(snake_case__    )
                 model.to(snake_case__    )
                 model.eval()

                 with torch.no_grad():
                       lowerCamelCase								=		model(**self._prepare_for_class(snake_case__				,			snake_case__    )    )

                 lowerCamelCase								=		outputs.hidden_states

                 lowerCamelCase								=		getattr(
                     self.model_tester				,			"expected_num_hidden_layers"				,			self.model_tester.num_hidden_layers + 1    )
                 self.assertEqual(len(snake_case__    )				,			snake_case__    )

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

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

           lowerCamelCase			,							lowerCamelCase								=		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 lowerCamelCase								=		True
                 check_hidden_states_output(snake_case__				,			snake_case__				,			snake_case__    )

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

                 check_hidden_states_output(snake_case__				,			snake_case__				,			snake_case__    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_object_detection(*snake_case__    )







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		YolosModel.from_pretrained(snake_case__    )
                 self.assertIsNotNone(snake_case__    )



def     __lowercase(	):


      """simple docstring"""



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






@require_torch
@require_vision
class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     @cached_property
     def 						_a      (self    ):






           '''simple docstring'''



           return AutoImageProcessor.from_pretrained("hustvl/yolos-small"    ) if is_vision_available() else None







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		YolosForObjectDetection.from_pretrained("hustvl/yolos-small"    ).to(snake_case__    )

           lowerCamelCase								=		self.default_image_processor
           lowerCamelCase								=		prepare_img()
           lowerCamelCase								=		image_processor(images=snake_case__				,			return_tensors="pt"    ).to(snake_case__    )

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

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

           lowerCamelCase								=		torch.tensor(
               [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]				,			device=snake_case__				,			)
           lowerCamelCase								=		torch.tensor(
               [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]				,			device=snake_case__    )
           self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]				,			snake_case__				,			atol=1E-4    )    )
           self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]				,			snake_case__				,			atol=1E-4    )    )

           # verify postprocessing
           lowerCamelCase								=		image_processor.post_process_object_detection(
               snake_case__				,			threshold=0.3				,			target_sizes=[image.size[::-1]]    )[0]
           lowerCamelCase								=		torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]    ).to(snake_case__    )
           lowerCamelCase								=		[75, 75, 17, 63, 17]
           lowerCamelCase								=		torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]    ).to(snake_case__    )

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




import unittest

import numpy as np
import torch

from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()





class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     @property
     def 						_a      (self    ):






           '''simple docstring'''



           torch.manual_seed(0    )
           lowerCamelCase								=		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







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.dummy_uncond_unet
           lowerCamelCase								=		KarrasVeScheduler()

           lowerCamelCase								=		KarrasVePipeline(unet=__a				,			scheduler=__a    )
           pipe.to(__a    )
           pipe.set_progress_bar_config(disable=__a    )

           lowerCamelCase								=		torch.manual_seed(0    )
           lowerCamelCase								=		pipe(num_inference_steps=2				,			generator=__a				,			output_type="numpy"    ).images

           lowerCamelCase								=		torch.manual_seed(0    )
           lowerCamelCase								=		pipe(num_inference_steps=2				,			generator=__a				,			output_type="numpy"				,			return_dict=__a    )[0]

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

           assert image.shape == (1, 32, 32, 3)
           lowerCamelCase								=		np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]    )

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





@slow
@require_torch
class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		"google/ncsnpp-celebahq-256"
           lowerCamelCase								=		UNetaDModel.from_pretrained(__a    )
           lowerCamelCase								=		KarrasVeScheduler()

           lowerCamelCase								=		KarrasVePipeline(unet=__a				,			scheduler=__a    )
           pipe.to(__a    )
           pipe.set_progress_bar_config(disable=__a    )

           lowerCamelCase								=		torch.manual_seed(0    )
           lowerCamelCase								=		pipe(num_inference_steps=20				,			generator=__a				,			output_type="numpy"    ).images

           lowerCamelCase								=		image[0, -3:, -3:, -1]
           assert image.shape == (1, 2_56, 2_56, 3)
           lowerCamelCase								=		np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586]    )

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