






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



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




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								snake_case_				=							floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]					)

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

								snake_case_				=							self.get_config()

								return config, pixel_values, labels




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								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					)       ->    List[str]:
								snake_case_				=							YolosModel(config=a					)
								model.to(a					)
								model.eval()
								snake_case_				=							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					)       ->    Optional[int]:
								snake_case_				=							YolosForObjectDetection(a					)
								model.to(a					)
								model.eval()

								snake_case_				=							model(pixel_values=a					)
								snake_case_				=							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)					)

								snake_case_				=							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					)       ->    str:
								snake_case_				=							self.prepare_config_and_inputs()
								snake_case_			,		snake_case_			,		snake_case_				=							config_and_inputs
								snake_case_				=							{'pixel_values': pixel_values}
								return config, inputs_dict






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



	'''simple docstring'''




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

	lowerCAmelCase													= False
	lowerCAmelCase													= False
	lowerCAmelCase													= False
	lowerCAmelCase													= False




	def 							_UpperCamelCase			(       self       ,			a       ,			a       ,			a=False					)       ->    int:
								snake_case_				=							super()._prepare_for_class(a       ,			a       ,			return_labels=a					)

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

								return inputs_dict




	def 							_UpperCamelCase			(       self					)       ->    Any:
								snake_case_				=							YolosModelTester(self					)
								snake_case_				=							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					)       ->    int:
								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()

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




	def 							_UpperCamelCase			(       self					)       ->    Any:
								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()

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

															snake_case_				=							['pixel_values']
															self.assertListEqual(arg_names[:1]       ,			a					)




	def 							_UpperCamelCase			(       self					)       ->    List[str]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a					)




	def 							_UpperCamelCase			(       self					)       ->    int:
								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()
								snake_case_				=							True

								# in YOLOS, the seq_len is different
								snake_case_				=							self.model_tester.expected_seq_len
								for model_class in self.all_model_classes:
															snake_case_				=							True
															snake_case_				=							False
															snake_case_				=							True
															snake_case_				=							model_class(a					)
															model.to(a					)
															model.eval()
															with torch.no_grad():
																						snake_case_				=							model(**self._prepare_for_class(a       ,			a					)					)
															snake_case_				=							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"]
															snake_case_				=							True
															snake_case_				=							model_class(a					)
															model.to(a					)
															model.eval()
															with torch.no_grad():
																						snake_case_				=							model(**self._prepare_for_class(a       ,			a					)					)
															snake_case_				=							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]       ,			)
															snake_case_				=							len(a					)

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

															snake_case_				=							1
															self.assertEqual(out_len + added_hidden_states       ,			len(a					)					)

															snake_case_				=							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					)       ->    int:
								def check_hidden_states_output(a       ,			a       ,			a					):
															snake_case_				=							model_class(a					)
															model.to(a					)
															model.eval()

															with torch.no_grad():
																						snake_case_				=							model(**self._prepare_for_class(a       ,			a					)					)

															snake_case_				=							outputs.hidden_states

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

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

								snake_case_			,		snake_case_				=							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
															snake_case_				=							True
															check_hidden_states_output(a       ,			a       ,			a					)

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

															check_hidden_states_output(a       ,			a       ,			a					)




	def 							_UpperCamelCase			(       self					)       ->    Optional[int]:
								snake_case_				=							self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*a					)






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






def 						__UpperCAmelCase			(     ):
							snake_case_				=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
							return image




@require_torch
@require_vision
class  UpperCamelCase_      (			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					)       ->    int:
								snake_case_				=							YolosForObjectDetection.from_pretrained('hustvl/yolos-small'					).to(a					)

								snake_case_				=							self.default_image_processor
								snake_case_				=							prepare_img()
								snake_case_				=							image_processor(images=a       ,			return_tensors='pt'					).to(a					)

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

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

								snake_case_				=							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       ,			)
								snake_case_				=							torch.tensor(
								    [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]]       ,			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
								snake_case_				=							image_processor.post_process_object_detection(
								    a       ,			threshold=0.3       ,			target_sizes=[image.size[::-1]]					)[0]
								snake_case_				=							torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]					).to(a					)
								snake_case_				=							[75, 75, 17, 63, 17]
								snake_case_				=							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 json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_squeezebert import SqueezeBertTokenizer


lowercase  							=					logging.get_logger(__name__)

lowercase  							=					{"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

lowercase  							=					{
    "vocab_file": {
        "squeezebert/squeezebert-uncased": (
            "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/vocab.txt"
        ),
        "squeezebert/squeezebert-mnli": "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/vocab.txt",
        "squeezebert/squeezebert-mnli-headless": (
            "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "squeezebert/squeezebert-uncased": (
            "https://huggingface.co/squeezebert/squeezebert-uncased/resolve/main/tokenizer.json"
        ),
        "squeezebert/squeezebert-mnli": (
            "https://huggingface.co/squeezebert/squeezebert-mnli/resolve/main/tokenizer.json"
        ),
        "squeezebert/squeezebert-mnli-headless": (
            "https://huggingface.co/squeezebert/squeezebert-mnli-headless/resolve/main/tokenizer.json"
        ),
    },
}

lowercase  							=					{
    "squeezebert/squeezebert-uncased": 512,
    "squeezebert/squeezebert-mnli": 512,
    "squeezebert/squeezebert-mnli-headless": 512,
}


lowercase  							=					{
    "squeezebert/squeezebert-uncased": {"do_lower_case": True},
    "squeezebert/squeezebert-mnli": {"do_lower_case": True},
    "squeezebert/squeezebert-mnli-headless": {"do_lower_case": True},
}




class  UpperCamelCase_      (			snake_case_				):



	'''simple docstring'''




	lowerCAmelCase													= VOCAB_FILES_NAMES
	lowerCAmelCase													= PRETRAINED_VOCAB_FILES_MAP
	lowerCAmelCase													= PRETRAINED_INIT_CONFIGURATION
	lowerCAmelCase													= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowerCAmelCase													= SqueezeBertTokenizer




	def __init__(       self       ,			a=None       ,			a=None       ,			a=True       ,			a="[UNK]"       ,			a="[SEP]"       ,			a="[PAD]"       ,			a="[CLS]"       ,			a="[MASK]"       ,			a=True       ,			a=None       ,			**a       ,			)       ->    Tuple:
								super().__init__(
								    a       ,			tokenizer_file=a       ,			do_lower_case=a       ,			unk_token=a       ,			sep_token=a       ,			pad_token=a       ,			cls_token=a       ,			mask_token=a       ,			tokenize_chinese_chars=a       ,			strip_accents=a       ,			**a       ,			)

								snake_case_				=							json.loads(self.backend_tokenizer.normalizer.__getstate__()					)
								if (
								    normalizer_state.get('lowercase'       ,			a					) != do_lower_case
								    or normalizer_state.get('strip_accents'       ,			a					) != strip_accents
								    or normalizer_state.get('handle_chinese_chars'       ,			a					) != tokenize_chinese_chars
								):
															snake_case_				=							getattr(a       ,			normalizer_state.pop('type'					)					)
															snake_case_				=							do_lower_case
															snake_case_				=							strip_accents
															snake_case_				=							tokenize_chinese_chars
															snake_case_				=							normalizer_class(**a					)

								snake_case_				=							do_lower_case




	def 							_UpperCamelCase			(       self       ,			a       ,			a=None					)       ->    Tuple:
								snake_case_				=							[self.cls_token_id] + token_ids_a + [self.sep_token_id]

								if token_ids_a:
															output += token_ids_a + [self.sep_token_id]

								return output




	def 							_UpperCamelCase			(       self       ,			a       ,			a = None					)       ->    List[int]:
								snake_case_				=							[self.sep_token_id]
								snake_case_				=							[self.cls_token_id]
								if token_ids_a is None:
															return len(cls + token_ids_a + sep					) * [0]
								return len(cls + token_ids_a + sep					) * [0] + len(token_ids_a + sep					) * [1]






	def 							_UpperCamelCase			(       self       ,			a       ,			a = None					)       ->    Tuple[str]:
								snake_case_				=							self._tokenizer.model.save(a       ,			name=a					)
								return tuple(a					)





