





import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
    slow,
)
from transformers.utils import is_sentencepiece_available


if is_sentencepiece_available():
    from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json

from ...test_tokenization_common import TokenizerTesterMixin


if is_sentencepiece_available():
    UpperCamelCase_												=	get_tests_dir('fixtures/test_sentencepiece.model')


if is_torch_available():
    from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right

UpperCamelCase_												=	12_80_22
UpperCamelCase_												=	12_80_28

@require_sentencepiece
class     snake_case_		(   a,		unittest.TestCase							):






 '''simple docstring'''





 __UpperCamelCase       =      MaMaaaTokenizer
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False
 __UpperCamelCase       =      True

 def  __UpperCAmelCase						(  self		)	->       List[str]:
    super().setUp()

    UpperCAmelCase__						=["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"]
    UpperCAmelCase__						=dict(zip(A_,		range(len(A_		)		)		)		)
    UpperCAmelCase__						=Path(self.tmpdirname		)
    save_json(A_,		save_dir / VOCAB_FILES_NAMES["vocab_file"]		)
    if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
       copyfile(A_,		save_dir / VOCAB_FILES_NAMES["spm_file"]		)

    UpperCAmelCase__						=MaMaaaTokenizer.from_pretrained(self.tmpdirname		)
    tokenizer.save_pretrained(self.tmpdirname		)

 def  __UpperCAmelCase						(  self,		**A_		)	->       List[str]:
    return MaMaaaTokenizer.from_pretrained(self.tmpdirname,		**A_		)

 def  __UpperCAmelCase						(  self,		A_		)	->       str:
    return (
        "This is a test",
        "This is a test",
    )

 def  __UpperCAmelCase						(  self		)	->       Union[str, Any]:
    UpperCAmelCase__						="</s>"
    UpperCAmelCase__						=0

    self.assertEqual(self.get_tokenizer()._convert_token_to_id(A_		),		A_		)
    self.assertEqual(self.get_tokenizer()._convert_id_to_token(A_		),		A_		)

 def  __UpperCAmelCase						(  self		)	->       Any:
    UpperCAmelCase__						=self.get_tokenizer()
    UpperCAmelCase__						=list(tokenizer.get_vocab().keys()		)

    self.assertEqual(vocab_keys[0],		"</s>"		)
    self.assertEqual(vocab_keys[1],		"<unk>"		)
    self.assertEqual(vocab_keys[-1],		"<s>"		)
    self.assertEqual(len(A_		),		tokenizer.vocab_size + len(tokenizer.get_added_vocab()		)		)

 @unittest.skip("Skip this test while all models are still to be uploaded."		)
 def  __UpperCAmelCase						(  self		)	->       Any:
    pass

 def  __UpperCAmelCase						(  self		)	->       Optional[Any]:
    UpperCAmelCase__						=self.get_tokenizer()

    UpperCAmelCase__						=tokenizer.tokenize("This is a test"		)
    self.assertListEqual(A_,		["▁This", "▁is", "▁a", "▁t", "est"]		)

    self.assertListEqual(
        tokenizer.convert_tokens_to_ids(A_		),		[2, 3, 4, 5, 6],		)

    UpperCAmelCase__						=tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6]		)
    self.assertListEqual(A_,		["▁This", "▁is", "▁a", "▁t", "est"]		)

    UpperCAmelCase__						=tokenizer.convert_tokens_to_string(A_		)
    self.assertEqual(A_,		"This is a test"		)






 @slow
 def  __UpperCAmelCase						(  self		)	->       Tuple:
    # fmt: off
    UpperCAmelCase__						={"input_ids": [[12_8022, 11_0108, 397, 11, 3_8272, 2247, 12_4811, 285, 1_8105, 1586, 207, 7, 3_9534, 4428, 397, 1019, 1_8105, 1586, 207, 7, 4_1337, 1_6786, 241, 7, 2_0214, 17, 12_5690, 1_0398, 7, 4_4378, 5_8069, 6_8342, 7798, 7343, 11, 299, 3_3310, 4, 158, 3_7350, 9_4077, 4569, 299, 3_3310, 90, 4, 5_2840, 290, 4, 3_1270, 112, 299, 682, 4, 5_2840, 3_9953, 1_4079, 193, 5_2519, 9_0894, 1_7894, 12_0697, 11, 4_0445, 551, 17, 1019, 5_2519, 9_0894, 1_7756, 963, 11, 4_0445, 480, 17, 9792, 1120, 5173, 1393, 6240, 1_6786, 241, 12_0996, 28, 1245, 1393, 11_8240, 1_1123, 1019, 9_3612, 2691, 1_0618, 9_8058, 12_0409, 1928, 279, 4, 4_0683, 367, 178, 207, 1019, 103, 10_3121, 506, 6_5296, 5, 2], [12_8022, 2_1217, 367, 117, 12_5450, 128, 719, 7, 7308, 40, 9_3612, 1_2669, 1116, 1_6704, 71, 1_7785, 3699, 1_5592, 35, 144, 9584, 241, 1_1943, 713, 950, 799, 2247, 8_8427, 150, 149, 11_8813, 12_0706, 1019, 10_6906, 8_1518, 28, 1224, 2_2799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [12_8022, 1658, 12_3311, 5155, 5578, 4722, 279, 1_4947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
    # fmt: on

    self.tokenizer_integration_test_util(
        expected_encoding=A_,		model_name="facebook/m2m100_418M",		revision="c168bae485c864188cf9aa0e4108b0b6934dc91e",		)

@require_torch
@require_sentencepiece
@require_tokenizers
class     snake_case_		(   unittest.TestCase							):






 '''simple docstring'''





 __UpperCamelCase       =      'facebook/m2m100_418M'
 __UpperCamelCase       =      [
     'In my opinion, there are two levels of response from the French government.',
     'NSA Affair Emphasizes Complete Lack of Debate on Intelligence',
 ]
 __UpperCamelCase       =      [
     'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.',
     'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement',
 ]

 # fmt: off
 __UpperCamelCase       =      [EN_CODE, 5_9_3, 1_9_4_9, 1_1_5_7_8_1, 4, 7_1_5_8_6, 4_2_3_4, 6_0_6_3_3, 1_2_6_2_3_3, 4_3_2, 1_2_3_8_0_8, 1_5_5_9_2, 1_1_9_7, 1_1_7_1_3_2, 1_2_0_6_1_8, 5, 2]

 @classmethod
 def  __UpperCAmelCase						(  cls		)	->       Union[str, Any]:
    UpperCAmelCase__						=MaMaaaTokenizer.from_pretrained(
        cls.checkpoint_name,		src_lang="en",		tgt_lang="fr"		)
    UpperCAmelCase__						=1
    return cls

 def  __UpperCAmelCase						(  self		)	->       Optional[Any]:
    self.assertEqual(self.tokenizer.get_lang_id("ar"		),		12_8006		)
    self.assertEqual(self.tokenizer.get_lang_id("en"		),		12_8022		)
    self.assertEqual(self.tokenizer.get_lang_id("ro"		),		12_8076		)
    self.assertEqual(self.tokenizer.get_lang_id("mr"		),		12_8063		)

 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=self.tokenizer.get_vocab()
    self.assertEqual(len(A_		),		self.tokenizer.vocab_size		)
    self.assertEqual(vocab["<unk>"],		3		)
    self.assertIn(self.tokenizer.get_lang_token("en"		),		A_		)

 def  __UpperCAmelCase						(  self		)	->       Dict:
    UpperCAmelCase__						="en"
    UpperCAmelCase__						=self.tokenizer.batch_encode_plus(self.src_text		).input_ids[0]
    self.assertListEqual(self.expected_src_tokens,		A_		)

 def  __UpperCAmelCase						(  self		)	->       Optional[Any]:
    self.assertIn(A_,		self.tokenizer.all_special_ids		)
    # fmt: off
    UpperCAmelCase__						=[FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 1_4028, 136, 3286, 9706, 6, 9_0797, 6, 14_4012, 162, 8_8128, 3_0061, 5, 2]
    # fmt: on
    UpperCAmelCase__						=self.tokenizer.decode(A_,		skip_special_tokens=A_		)
    UpperCAmelCase__						=self.tokenizer.decode(generated_ids[1:],		skip_special_tokens=A_		)
    self.assertEqual(A_,		A_		)
    self.assertNotIn(self.tokenizer.eos_token,		A_		)

 def  __UpperCAmelCase						(  self		)	->       Tuple:
    UpperCAmelCase__						=tempfile.mkdtemp()
    UpperCAmelCase__						=self.tokenizer.lang_token_to_id
    self.tokenizer.save_pretrained(A_		)
    UpperCAmelCase__						=MaMaaaTokenizer.from_pretrained(A_		)
    self.assertDictEqual(new_tok.lang_token_to_id,		A_		)

 @require_torch
 def  __UpperCAmelCase						(  self		)	->       Any:
    UpperCAmelCase__						="en"
    UpperCAmelCase__						="fr"

    UpperCAmelCase__						=self.tokenizer(self.src_text,		text_target=self.tgt_text,		padding=A_,		return_tensors="pt"		)

    UpperCAmelCase__						=shift_tokens_right(
        batch["labels"],		self.tokenizer.pad_token_id,		self.tokenizer.eos_token_id		)

    for k in batch:
       UpperCAmelCase__						=batch[k].tolist()
    # batch = {k: v.tolist() for k,v in batch.items()}
    # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
    # batch.decoder_inputs_ids[0][0] ==
    assert batch.input_ids[1][0] == EN_CODE
    assert batch.input_ids[1][-1] == 2
    assert batch.labels[1][0] == FR_CODE
    assert batch.labels[1][-1] == 2
    assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]

 @require_torch
 def  __UpperCAmelCase						(  self		)	->       Any:
    UpperCAmelCase__						="mr"
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id("mr"		)]		)
    self.assertListEqual(self.tokenizer.suffix_tokens,		[self.tokenizer.eos_token_id]		)

    UpperCAmelCase__						="zh"
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id("zh"		)]		)
    self.assertListEqual(self.tokenizer.suffix_tokens,		[self.tokenizer.eos_token_id]		)

 @require_torch
 def  __UpperCAmelCase						(  self		)	->       Optional[int]:
    UpperCAmelCase__						="mr"
    self.tokenizer._switch_to_target_mode()
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id("mr"		)]		)
    self.assertListEqual(self.tokenizer.suffix_tokens,		[self.tokenizer.eos_token_id]		)
    self.tokenizer._switch_to_input_mode()
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id(self.tokenizer.src_lang		)]		)

    UpperCAmelCase__						="zh"
    self.tokenizer._switch_to_target_mode()
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id("zh"		)]		)
    self.assertListEqual(self.tokenizer.suffix_tokens,		[self.tokenizer.eos_token_id]		)
    self.tokenizer._switch_to_input_mode()
    self.assertListEqual(self.tokenizer.prefix_tokens,		[self.tokenizer.get_lang_id(self.tokenizer.src_lang		)]		)






 @require_torch
 def  __UpperCAmelCase						(  self		)	->       Dict:
    UpperCAmelCase__						=self.tokenizer._build_translation_inputs("A test",		return_tensors="pt",		src_lang="en",		tgt_lang="ar"		)

    self.assertEqual(
        nested_simplify(A_		),		{
            # en_XX, A, test, EOS
            "input_ids": [[12_8022, 58, 4183, 2]],
            "attention_mask": [[1, 1, 1, 1]],
            # ar_AR
            "forced_bos_token_id": 12_8006,
        },		)










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






 '''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,		)	->       List[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  __UpperCAmelCase						(  self		)	->       Dict:
    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=A_		)
          UpperCAmelCase__						=torch.rand(self.n_targets,		4,		device=A_		)
          labels.append(A_		)

    UpperCAmelCase__						=self.get_config()

    return config, pixel_values, labels

 def  __UpperCAmelCase						(  self		)	->       Dict:
    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  __UpperCAmelCase						(  self,		A_,		A_,		A_		)	->       Tuple:
    UpperCAmelCase__						=YolosModel(config=A_		)
    model.to(A_		)
    model.eval()
    UpperCAmelCase__						=model(A_		)
    self.parent.assertEqual(
        result.last_hidden_state.shape,		(self.batch_size, self.expected_seq_len, self.hidden_size)		)

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_		)	->       Union[str, Any]:
    UpperCAmelCase__						=YolosForObjectDetection(A_		)
    model.to(A_		)
    model.eval()

    UpperCAmelCase__						=model(pixel_values=A_		)
    UpperCAmelCase__						=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)		)

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

@require_torch
class     snake_case_		(   a,		a,		unittest.TestCase							):






 '''simple docstring'''





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

 __UpperCamelCase       =      False
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False
 __UpperCamelCase       =      False

 def  __UpperCAmelCase						(  self,		A_,		A_,		A_=False		)	->       Dict:
    UpperCAmelCase__						=super()._prepare_for_class(A_,		A_,		return_labels=A_		)

    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=A_,		dtype=torch.long		)
             UpperCAmelCase__						=torch.ones(
                 self.model_tester.n_targets,		4,		device=A_,		dtype=torch.float		)
             labels.append(A_		)
          UpperCAmelCase__						=labels

    return inputs_dict

 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    UpperCAmelCase__						=YolosModelTester(self		)
    UpperCAmelCase__						=ConfigTester(self,		config_class=A_,		has_text_modality=A_,		hidden_size=37		)

 def  __UpperCAmelCase						(  self		)	->       Optional[int]:
    self.config_tester.run_common_tests()

 def  __UpperCAmelCase						(  self		)	->       Union[str, Any]:
    # YOLOS does not use inputs_embeds
    pass

 def  __UpperCAmelCase						(  self		)	->       Any:
    UpperCAmelCase__			,							UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs_for_common()

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

 def  __UpperCAmelCase						(  self		)	->       str:
    UpperCAmelCase__			,							UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       UpperCAmelCase__						=model_class(A_		)
       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],		A_		)

 def  __UpperCAmelCase						(  self		)	->       Optional[int]:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*A_		)

 def  __UpperCAmelCase						(  self		)	->       Dict:
    UpperCAmelCase__			,							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(A_		)
       model.to(A_		)
       model.eval()
       with torch.no_grad():
          UpperCAmelCase__						=model(**self._prepare_for_class(A_,		A_		)		)
       UpperCAmelCase__						=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"]
       UpperCAmelCase__						=True
       UpperCAmelCase__						=model_class(A_		)
       model.to(A_		)
       model.eval()
       with torch.no_grad():
          UpperCAmelCase__						=model(**self._prepare_for_class(A_,		A_		)		)
       UpperCAmelCase__						=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],		)
       UpperCAmelCase__						=len(A_		)

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

       UpperCAmelCase__						=1
       self.assertEqual(out_len + added_hidden_states,		len(A_		)		)

       UpperCAmelCase__						=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  __UpperCAmelCase						(  self		)	->       List[str]:
    def check_hidden_states_output(A_,		A_,		A_		):
       UpperCAmelCase__						=model_class(A_		)
       model.to(A_		)
       model.eval()

       with torch.no_grad():
          UpperCAmelCase__						=model(**self._prepare_for_class(A_,		A_		)		)

       UpperCAmelCase__						=outputs.hidden_states

       UpperCAmelCase__						=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
       UpperCAmelCase__						=self.model_tester.expected_seq_len

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

    UpperCAmelCase__			,							UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       UpperCAmelCase__						=True
       check_hidden_states_output(A_,		A_,		A_		)

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

       check_hidden_states_output(A_,		A_,		A_		)

 def  __UpperCAmelCase						(  self		)	->       Union[str, Any]:
    UpperCAmelCase__						=self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_object_detection(*A_		)






 @slow
 def  __UpperCAmelCase						(  self		)	->       Any:
    for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase__						=YolosModel.from_pretrained(A_		)
       self.assertIsNotNone(A_		)






def 				_UpperCAmelCase			(    ):




   '''simple docstring'''

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




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






 '''simple docstring'''





 @cached_property
 def  __UpperCAmelCase						(  self		)	->       Any:
    return AutoImageProcessor.from_pretrained("hustvl/yolos-small"		) if is_vision_available() else None






 @slow
 def  __UpperCAmelCase						(  self		)	->       List[Any]:
    UpperCAmelCase__						=YolosForObjectDetection.from_pretrained("hustvl/yolos-small"		).to(A_		)

    UpperCAmelCase__						=self.default_image_processor
    UpperCAmelCase__						=prepare_img()
    UpperCAmelCase__						=image_processor(images=A_,		return_tensors="pt"		).to(A_		)

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

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

    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=A_,		)
    UpperCAmelCase__						=torch.tensor(
        [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]],		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
    UpperCAmelCase__						=image_processor.post_process_object_detection(
        A_,		threshold=0.3,		target_sizes=[image.size[::-1]]		)[0]
    UpperCAmelCase__						=torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]		).to(A_		)
    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(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_		)		)



