




"""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 				lowercase_       :



 '''simple docstring'''

 def __init__( self       :       Optional[int]    ,							_UpperCAmelCase       :       Union[str, Any]    ,							_UpperCAmelCase       :       str=13    ,							_UpperCAmelCase       :       str=[30, 30]    ,							_UpperCAmelCase       :       Any=2    ,							_UpperCAmelCase       :       List[Any]=3    ,							_UpperCAmelCase       :       Dict=True    ,							_UpperCAmelCase       :       int=True    ,							_UpperCAmelCase       :       int=32    ,							_UpperCAmelCase       :       Optional[Any]=5    ,							_UpperCAmelCase       :       List[str]=4    ,							_UpperCAmelCase       :       List[Any]=37    ,							_UpperCAmelCase       :       List[str]="gelu"    ,							_UpperCAmelCase       :       int=0.1    ,							_UpperCAmelCase       :       int=0.1    ,							_UpperCAmelCase       :       Optional[int]=10    ,							_UpperCAmelCase       :       Any=0.02    ,							_UpperCAmelCase       :       Tuple=3    ,							_UpperCAmelCase       :       Optional[int]=None    ,							_UpperCAmelCase       :       Any=8    ,							_UpperCAmelCase       :       Union[str, Any]=10    ,							):
       _A					   =   parent
       _A					   =   batch_size
       _A					   =   image_size
       _A					   =   patch_size
       _A					   =   num_channels
       _A					   =   is_training
       _A					   =   use_labels
       _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					   =   type_sequence_label_size
       _A					   =   initializer_range
       _A					   =   num_labels
       _A					   =   scope
       _A					   =   n_targets
       _A					   =   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
       _A					   =   (image_size[1] // patch_size) * (image_size[0] // patch_size)
       _A					   =   num_patches + 1 + self.num_detection_tokens

 def 			lowerCAmelCase_							( self       :       Optional[int]		):
       _A					   =   floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

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

       _A					   =   self.get_config()

       return config, pixel_values, labels

 def 			lowerCAmelCase_							( self       :       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=A__    ,							initializer_range=self.initializer_range    ,							num_detection_tokens=self.num_detection_tokens    ,							num_labels=self.num_labels    ,							)

 def 			lowerCAmelCase_							( self       :       List[Any]    ,							_UpperCAmelCase       :       Tuple    ,							_UpperCAmelCase       :       str    ,							_UpperCAmelCase       :       List[str]		):
       _A					   =   YolosModel(config=A__		)
       model.to(A__		)
       model.eval()
       _A					   =   model(A__		)
       self.parent.assertEqual(
           result.last_hidden_state.shape    ,							(self.batch_size, self.expected_seq_len, self.hidden_size)		)

 def 			lowerCAmelCase_							( self       :       Tuple    ,							_UpperCAmelCase       :       Tuple    ,							_UpperCAmelCase       :       int    ,							_UpperCAmelCase       :       List[str]		):
       _A					   =   YolosForObjectDetection(A__		)
       model.to(A__		)
       model.eval()

       _A					   =   model(pixel_values=A__		)
       _A					   =   model(A__		)

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

       _A					   =   model(pixel_values=A__    ,							labels=A__		)

       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 			lowerCAmelCase_							( self       :       int		):
       _A					   =   self.prepare_config_and_inputs()
       _A					   =   config_and_inputs
       _A					   =   {"""pixel_values""": pixel_values}
       return config, inputs_dict





@require_torch
class 				lowercase_       (     __lowerCAmelCase			,	__lowerCAmelCase			,	unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase    :     Tuple        =	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
 UpperCAmelCase    :     List[str]        =	(
     {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
 )

 UpperCAmelCase    :     str        =	False
 UpperCAmelCase    :     Optional[Any]        =	False
 UpperCAmelCase    :     str        =	False
 UpperCAmelCase    :     Any        =	False

 def 			lowerCAmelCase_							( self       :       List[Any]    ,							_UpperCAmelCase       :       Optional[Any]    ,							_UpperCAmelCase       :       int    ,							_UpperCAmelCase       :       List[str]=False		):
       _A					   =   super()._prepare_for_class(A__    ,							A__    ,							return_labels=A__		)

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

       return inputs_dict

 def 			lowerCAmelCase_							( self       :       List[Any]		):
       _A					   =   YolosModelTester(self		)
       _A					   =   ConfigTester(self    ,							config_class=A__    ,							has_text_modality=A__    ,							hidden_size=37		)

 def 			lowerCAmelCase_							( self       :       Dict		):
       self.config_tester.run_common_tests()

 def 			lowerCAmelCase_							( self       :       List[Any]		):
       # YOLOS does not use inputs_embeds
       pass

 def 			lowerCAmelCase_							( self       :       int		):
       _A					   =   self.model_tester.prepare_config_and_inputs_for_common()

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

 def 			lowerCAmelCase_							( self       :       Dict		):
       _A					   =   self.model_tester.prepare_config_and_inputs_for_common()

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

             _A					   =   ["""pixel_values"""]
             self.assertListEqual(arg_names[:1]    ,							A__		)

 def 			lowerCAmelCase_							( self       :       List[str]		):
       _A					   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A__		)

 def 			lowerCAmelCase_							( self       :       Union[str, Any]		):
       _A					   =   self.model_tester.prepare_config_and_inputs_for_common()
       _A					   =   True

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

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

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

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

             _A					   =   1
             self.assertEqual(out_len + added_hidden_states    ,							len(A__		)		)

             _A					   =   outputs.attentions

             self.assertEqual(len(A__		)    ,							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 			lowerCAmelCase_							( self       :       str		):
       def check_hidden_states_output(_UpperCAmelCase       :       int    ,							_UpperCAmelCase       :       Any    ,							_UpperCAmelCase       :       int		):
             _A					   =   model_class(A__		)
             model.to(A__		)
             model.eval()

             with torch.no_grad():
                   _A					   =   model(**self._prepare_for_class(A__    ,							A__		)		)

             _A					   =   outputs.hidden_states

             _A					   =   getattr(
                 self.model_tester    ,							'expected_num_hidden_layers'    ,							self.model_tester.num_hidden_layers + 1		)
             self.assertEqual(len(A__		)    ,							A__		)

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

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

       _A					   =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             _A					   =   True
             check_hidden_states_output(A__    ,							A__    ,							A__		)

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

             check_hidden_states_output(A__    ,							A__    ,							A__		)

 def 			lowerCAmelCase_							( self       :       str		):
       _A					   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*A__		)



 @slow
 def 			lowerCAmelCase_							( self       :       Tuple		):
       for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A					   =   YolosModel.from_pretrained(A__		)
             self.assertIsNotNone(A__		)






def 						_snake_case     (					)    ->					Optional[int]:






      '''simple docstring'''


      _A					   =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
      return image







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



 '''simple docstring'''

 @cached_property
 def 			lowerCAmelCase_							( self       :       Optional[int]		):
       return AutoImageProcessor.from_pretrained('hustvl/yolos-small'		) if is_vision_available() else None



 @slow
 def 			lowerCAmelCase_							( self       :       List[str]		):
       _A					   =   YolosForObjectDetection.from_pretrained('hustvl/yolos-small'		).to(A__		)

       _A					   =   self.default_image_processor
       _A					   =   prepare_img()
       _A					   =   image_processor(images=A__    ,							return_tensors='pt'		).to(A__		)

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

       # verify outputs
       _A					   =   torch.Size((1, 100, 92)		)
       self.assertEqual(outputs.logits.shape    ,							A__		)

       _A					   =   torch.tensor(
           [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]]    ,							device=A__    ,							)
       _A					   =   torch.tensor(
           [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]    ,							device=A__		)
       self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]    ,							A__    ,							atol=1E-4		)		)
       self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]    ,							A__    ,							atol=1E-4		)		)

       # verify postprocessing
       _A					   =   image_processor.post_process_object_detection(
           A__    ,							threshold=0.3    ,							target_sizes=[image.size[::-1]]		)[0]
       _A					   =   torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]		).to(A__		)
       _A					   =   [75, 75, 17, 63, 17]
       _A					   =   torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]		).to(A__		)

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




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


					'''simple docstring'''






					@property
					def   __A			( self			):
						torch.manual_seed(0			)
						A__							:    int        =		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   __A			( self			):
						torch.manual_seed(0			)
						A__							:    Dict        =		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   __A			( self			):
						torch.manual_seed(0			)
						A__							:    int        =		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=1000    ,       )
						return CLIPTextModel(A__			)






					def   __A			( self			):
						A__							:    int        =		self.dummy_uncond_unet
						A__							:    Optional[int]        =		DDIMScheduler()
						A__							:    List[Any]        =		self.dummy_vq_model

						A__							:    Optional[int]        =		LDMPipeline(unet=A__    ,       vqvae=A__    ,       scheduler=A__			)
						ldm.to(A__			)
						ldm.set_progress_bar_config(disable=A__			)

						A__							:    Tuple        =		torch.manual_seed(0			)
						A__							:    List[Any]        =		ldm(generator=A__    ,       num_inference_steps=2    ,       output_type="""numpy"""			).images

						A__							:    Optional[int]        =		torch.manual_seed(0			)
						A__							:    List[Any]        =		ldm(generator=A__    ,       num_inference_steps=2    ,       output_type="""numpy"""    ,       return_dict=A__			)[0]

						A__							:    str        =		image[0, -3:, -3:, -1]
						A__							:    Tuple        =		image_from_tuple[0, -3:, -3:, -1]

						assert image.shape == (1, 64, 64, 3)
						A__							:    Dict        =		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]			)
						A__							:    List[Any]        =		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				):


					'''simple docstring'''






					def   __A			( self			):
						A__							:    Optional[Any]        =		LDMPipeline.from_pretrained("""CompVis/ldm-celebahq-256"""			)
						ldm.to(A__			)
						ldm.set_progress_bar_config(disable=A__			)

						A__							:    Tuple        =		torch.manual_seed(0			)
						A__							:    List[Any]        =		ldm(generator=A__    ,       num_inference_steps=5    ,       output_type="""numpy"""			).images

						A__							:    int        =		image[0, -3:, -3:, -1]

						assert image.shape == (1, 256, 256, 3)
						A__							:    Any        =		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]			)
						A__							:    int        =		1e-2 if torch_device != """mps""" else 3e-2

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



