
"""simple docstring"""





import collections
from typing import List, Optional, Union

from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
from ..bert.tokenization_bert import BertTokenizer


UpperCamelCase_       :    str						      =			logging.get_logger(__name__)

UpperCamelCase_       :    Union[str, Any]						      =			{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

UpperCamelCase_       :    str						      =			{
    '''vocab_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-ctx_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-ctx_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
UpperCamelCase_       :    Optional[Any]						      =			{
    '''vocab_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-question_encoder-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-question_encoder-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}
UpperCamelCase_       :    Optional[Any]						      =			{
    '''vocab_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt'''
        ),
    },
    '''tokenizer_file''': {
        '''facebook/dpr-reader-single-nq-base''': (
            '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json'''
        ),
        '''facebook/dpr-reader-multiset-base''': (
            '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json'''
        ),
    },
}

UpperCamelCase_       :    int						      =			{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 512,
    '''facebook/dpr-ctx_encoder-multiset-base''': 512,
}
UpperCamelCase_       :    Tuple						      =			{
    '''facebook/dpr-question_encoder-single-nq-base''': 512,
    '''facebook/dpr-question_encoder-multiset-base''': 512,
}
UpperCamelCase_       :    Optional[int]						      =			{
    '''facebook/dpr-reader-single-nq-base''': 512,
    '''facebook/dpr-reader-multiset-base''': 512,
}


UpperCamelCase_       :    Tuple						      =			{
    '''facebook/dpr-ctx_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-ctx_encoder-multiset-base''': {'''do_lower_case''': True},
}
UpperCamelCase_       :    Tuple						      =			{
    '''facebook/dpr-question_encoder-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-question_encoder-multiset-base''': {'''do_lower_case''': True},
}
UpperCamelCase_       :    Optional[int]						      =			{
    '''facebook/dpr-reader-single-nq-base''': {'''do_lower_case''': True},
    '''facebook/dpr-reader-multiset-base''': {'''do_lower_case''': True},
}



class __lowerCAmelCase					(       _lowercase   ):




			"""simple docstring"""







			snake_case						   =					VOCAB_FILES_NAMES
			snake_case						   =					CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
			snake_case						   =					CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			snake_case						   =					CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION





class __lowerCAmelCase					(       _lowercase   ):




			"""simple docstring"""







			snake_case						   =					VOCAB_FILES_NAMES
			snake_case						   =					QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
			snake_case						   =					QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			snake_case						   =					QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION





UpperCamelCase_       :    Optional[int]						      =			collections.namedtuple(
    '''DPRSpanPrediction''', ['''span_score''', '''relevance_score''', '''doc_id''', '''start_index''', '''end_index''', '''text''']
)

UpperCamelCase_       :    List[Any]						      =			collections.namedtuple('''DPRReaderOutput''', ['''start_logits''', '''end_logits''', '''relevance_logits'''])


UpperCamelCase_       :    Optional[Any]						      =			R'''
    Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
    It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
    using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
    with the format:

    ```
    [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
    ```

    Args:
        questions (`str` or `List[str]`):
            The questions to be encoded. You can specify one question for many passages. In this case, the question
            will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
            `titles` or `texts`.
        titles (`str` or `List[str]`):
            The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
        texts (`str` or `List[str]`):
            The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
            Activates and controls padding. Accepts the following values:

            - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
              if provided).
            - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided.
            - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different
              lengths).
        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
            Activates and controls truncation. Accepts the following values:

            - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to
              the maximum acceptable input length for the model if that argument is not provided. This will truncate
              token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
              of pairs) is provided.
            - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the first
              sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
              acceptable input length for the model if that argument is not provided. This will only truncate the
              second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
            - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths
              greater than the model maximum admissible input size).
        max_length (`int`, *optional*):
                Controls the maximum length to use by one of the truncation/padding parameters.

                If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
                is required by one of the truncation/padding parameters. If the model has no specific maximum input
                length (like XLNet) truncation/padding to a maximum length will be deactivated.
        return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `\'tf\'`: Return TensorFlow `tf.constant` objects.
                - `\'pt\'`: Return PyTorch `torch.Tensor` objects.
                - `\'np\'`: Return Numpy `np.ndarray` objects.
        return_attention_mask (`bool`, *optional*):
            Whether or not to return the attention mask. If not set, will return the attention mask according to the
            specific tokenizer\'s default, defined by the `return_outputs` attribute.

            [What are attention masks?](../glossary#attention-mask)

    Returns:
        `Dict[str, List[List[int]]]`: A dictionary with the following keys:

        - `input_ids`: List of token ids to be fed to a model.
        - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
    '''



@add_start_docstrings(_lowercase   )
class __lowerCAmelCase					:




			"""simple docstring"""







			def __call__(					self    :       Dict							, _snake_case    :       int							, _snake_case    :       Optional[str] = None							, _snake_case    :       Optional[str] = None							, _snake_case    :       Union[bool, str] = False							, _snake_case    :       Union[bool, str] = False							, _snake_case    :       Optional[int] = None							, _snake_case    :       Optional[Union[str, TensorType]] = None							, _snake_case    :       Optional[bool] = None							, **_snake_case    :       Tuple							, )   ->			BatchEncoding:







								"""simple docstring"""
								if titles is None and texts is None:
													return super().__call__(
													    _snake_case							, padding=_snake_case							, truncation=_snake_case							, max_length=_snake_case							, return_tensors=_snake_case							, return_attention_mask=_snake_case							, **_snake_case							, )
								elif titles is None or texts is None:
													A_								=    titles if texts is None else texts
													return super().__call__(
													    _snake_case							, _snake_case							, padding=_snake_case							, truncation=_snake_case							, max_length=_snake_case							, return_tensors=_snake_case							, return_attention_mask=_snake_case							, **_snake_case							, )
								A_								=    titles if not isinstance(_snake_case							, _snake_case						) else [titles]
								A_								=    texts if not isinstance(_snake_case							, _snake_case						) else [texts]
								A_								=    len(_snake_case						)
								A_								=    questions if not isinstance(_snake_case							, _snake_case						) else [questions] * n_passages
								if len(_snake_case						) != len(_snake_case						):
													raise ValueError(
													    F'There should be as many titles than texts but got {len(_snake_case						)} titles and {len(_snake_case						)} texts.'						)
								A_								=    super().__call__(_snake_case							, _snake_case							, padding=_snake_case							, truncation=_snake_case						)["input_ids"]
								A_								=    super().__call__(_snake_case							, add_special_tokens=_snake_case							, padding=_snake_case							, truncation=_snake_case						)["input_ids"]
								A_								=    {
								    "input_ids": [
								        (encoded_question_and_title + encoded_text)[:max_length]
								        if max_length is not None and truncation
								        else encoded_question_and_title + encoded_text
								        for encoded_question_and_title, encoded_text in zip(_snake_case							, _snake_case						)
								    ]
								}
								if return_attention_mask is not False:
													A_								=    []
													for input_ids in encoded_inputs["input_ids"]:
																		attention_mask.append([int(input_id != self.pad_token_id						) for input_id in input_ids]						)
													A_								=    attention_mask
								return self.pad(_snake_case							, padding=_snake_case							, max_length=_snake_case							, return_tensors=_snake_case						)




			def   lowerCamelCase__  (					self    :       str							, _snake_case    :       BatchEncoding							, _snake_case    :       DPRReaderOutput							, _snake_case    :       int = 16							, _snake_case    :       int = 64							, _snake_case    :       int = 4							, )   ->			List[DPRSpanPrediction]:







								"""simple docstring"""
								A_								=    reader_input["input_ids"]
								A_			,     A_			,     A_								=    reader_output[:3]
								A_								=    len(_snake_case						)
								A_								=    sorted(range(_snake_case						)							, reverse=_snake_case							, key=relevance_logits.__getitem__						)
								A_								=    []
								for doc_id in sorted_docs:
													A_								=    list(input_ids[doc_id]						)
													# assuming question & title information is at the beginning of the sequence
													A_								=    sequence_ids.index(self.sep_token_id							, 2						) + 1  # second sep id
													if sequence_ids[-1] == self.pad_token_id:
																		A_								=    sequence_ids.index(self.pad_token_id						)
													else:
																		A_								=    len(_snake_case						)

													A_								=    self._get_best_spans(
													    start_logits=start_logits[doc_id][passage_offset:sequence_len]							, end_logits=end_logits[doc_id][passage_offset:sequence_len]							, max_answer_length=_snake_case							, top_spans=_snake_case							, )
													for start_index, end_index in best_spans:
																		start_index += passage_offset
																		end_index += passage_offset
																		nbest_spans_predictions.append(
																		    DPRSpanPrediction(
																		        span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index]							, relevance_score=relevance_logits[doc_id]							, doc_id=_snake_case							, start_index=_snake_case							, end_index=_snake_case							, text=self.decode(sequence_ids[start_index : end_index + 1]						)							, )						)
													if len(_snake_case						) >= num_spans:
																		break
								return nbest_spans_predictions[:num_spans]






			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       List[int]							, _snake_case    :       List[int]							, _snake_case    :       int							, _snake_case    :       int							, )   ->			List[DPRSpanPrediction]:







								"""simple docstring"""
								A_								=    []
								for start_index, start_score in enumerate(_snake_case						):
													for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]						):
																		scores.append(((start_index, start_index + answer_length), start_score + end_score)						)
								A_								=    sorted(_snake_case							, key=lambda _snake_case						: x[1]							, reverse=_snake_case						)
								A_								=    []
								for (start_index, end_index), score in scores:
													if start_index > end_index:
																		raise ValueError(F'Wrong span indices: [{start_index}:{end_index}]'						)
													A_								=    end_index - start_index + 1
													if length > max_answer_length:
																		raise ValueError(F'Span is too long: {length} > {max_answer_length}'						)
													if any(
													    start_index <= prev_start_index <= prev_end_index <= end_index
													    or prev_start_index <= start_index <= end_index <= prev_end_index
													    for (prev_start_index, prev_end_index) in chosen_span_intervals						):
																		continue
													chosen_span_intervals.append((start_index, end_index)						)

													if len(_snake_case						) == top_spans:
																		break
								return chosen_span_intervals





@add_end_docstrings(_lowercase   )
class __lowerCAmelCase					(       _lowercase  ,					_lowercase   ):




			"""simple docstring"""







			snake_case						   =					VOCAB_FILES_NAMES
			snake_case						   =					READER_PRETRAINED_VOCAB_FILES_MAP
			snake_case						   =					READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			snake_case						   =					READER_PRETRAINED_INIT_CONFIGURATION
			snake_case						   =					["input_ids", "attention_mask"]






"""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    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Any=13							, _snake_case    :       Union[str, Any]=[30, 30]							, _snake_case    :       Optional[int]=2							, _snake_case    :       str=3							, _snake_case    :       List[str]=True							, _snake_case    :       Tuple=True							, _snake_case    :       Union[str, Any]=32							, _snake_case    :       List[str]=5							, _snake_case    :       str=4							, _snake_case    :       Tuple=37							, _snake_case    :       Tuple="gelu"							, _snake_case    :       str=0.1							, _snake_case    :       Tuple=0.1							, _snake_case    :       Optional[Any]=10							, _snake_case    :       Dict=0.0_2							, _snake_case    :       int=3							, _snake_case    :       Optional[int]=None							, _snake_case    :       str=8							, _snake_case    :       Dict=10							, )   ->			int:







								"""simple docstring"""
								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    :       Any						)   ->			str:







								"""simple docstring"""
								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=_snake_case						)
																		A_								=    torch.rand(self.n_targets							, 4							, device=_snake_case						)
																		labels.append(_snake_case						)

								A_								=    self.get_config()

								return config, pixel_values, labels




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			str:







								"""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   lowerCamelCase__  (					self    :       Any							, _snake_case    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								A_								=    YolosModel(config=_snake_case						)
								model.to(_snake_case						)
								model.eval()
								A_								=    model(_snake_case						)
								self.parent.assertEqual(
								    result.last_hidden_state.shape							, (self.batch_size, self.expected_seq_len, self.hidden_size)						)




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Tuple							, _snake_case    :       Optional[Any]							, _snake_case    :       Any						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    YolosForObjectDetection(_snake_case						)
								model.to(_snake_case						)
								model.eval()

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

								A_								=    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   lowerCamelCase__  (					self    :       int						)   ->			Union[str, Any]:







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





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




			"""simple docstring"""







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

			snake_case						   =					False
			snake_case						   =					False
			snake_case						   =					False
			snake_case						   =					False




			def   lowerCamelCase__  (					self    :       int							, _snake_case    :       Optional[int]							, _snake_case    :       Any							, _snake_case    :       Dict=False						)   ->			List[Any]:







								"""simple docstring"""
								A_								=    super()._prepare_for_class(_snake_case							, _snake_case							, return_labels=_snake_case						)

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

								return inputs_dict




			def   lowerCamelCase__  (					self    :       Tuple						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    YolosModelTester(self						)
								A_								=    ConfigTester(self							, config_class=_snake_case							, has_text_modality=_snake_case							, hidden_size=37						)




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







								"""simple docstring"""
								self.config_tester.run_common_tests()




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







								"""simple docstring"""
								# YOLOS does not use inputs_embeds
								pass




			def   lowerCamelCase__  (					self    :       Dict						)   ->			List[str]:







								"""simple docstring"""
								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

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




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







								"""simple docstring"""
								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

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




			def   lowerCamelCase__  (					self    :       List[str]						)   ->			Tuple:







								"""simple docstring"""
								A_								=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case						)




			def   lowerCamelCase__  (					self    :       Union[str, Any]						)   ->			List[Any]:







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

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

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

													A_								=    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   lowerCamelCase__  (					self    :       Any						)   ->			List[Any]:







								"""simple docstring"""
								def check_hidden_states_output(_snake_case    :       str							, _snake_case    :       Dict							, _snake_case    :       Dict						):
													A_								=    model_class(_snake_case						)
													model.to(_snake_case						)
													model.eval()

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

													A_								=    outputs.hidden_states

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

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

								A_			,     A_								=    self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													A_								=    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"]
													A_								=    True

													check_hidden_states_output(_snake_case							, _snake_case							, _snake_case						)




			def   lowerCamelCase__  (					self    :       Dict						)   ->			Any:







								"""simple docstring"""
								A_								=    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*_snake_case						)






			@slow
			def   lowerCamelCase__  (					self    :       Optional[Any]						)   ->			Optional[Any]:







								"""simple docstring"""
								for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A_								=    YolosModel.from_pretrained(_snake_case						)
													self.assertIsNotNone(_snake_case						)





def 				A_  ():

					'''simple docstring'''





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




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




			"""simple docstring"""







			@cached_property
			def   lowerCamelCase__  (					self    :       str						)   ->			Any:







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






			@slow
			def   lowerCamelCase__  (					self    :       str						)   ->			Union[str, Any]:







								"""simple docstring"""
								A_								=    YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(_snake_case						)

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

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

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

								A_								=    torch.tensor(
								    [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]							, device=_snake_case							, )
								A_								=    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=_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
								A_								=    image_processor.post_process_object_detection(
								    _snake_case							, threshold=0.3							, target_sizes=[image.size[::-1]]						)[0]
								A_								=    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(_snake_case						)
								A_								=    [75, 75, 17, 63, 17]
								A_								=    torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]						).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						)						)




