
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_fast import BertTokenizerFast
from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer


lowerCamelCase__     :		Optional[int]        = logging.get_logger(__name__)

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

lowerCamelCase__     :		Union[str, Any]        = {
    """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"""
        ),
    },
}
lowerCamelCase__     :		Tuple        = {
    """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"""
        ),
    },
}
lowerCamelCase__     :		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"""
        ),
    },
}

lowerCamelCase__     :		Tuple        = {
    """facebook/dpr-ctx_encoder-single-nq-base""": 5_1_2,
    """facebook/dpr-ctx_encoder-multiset-base""": 5_1_2,
}
lowerCamelCase__     :		Optional[Any]        = {
    """facebook/dpr-question_encoder-single-nq-base""": 5_1_2,
    """facebook/dpr-question_encoder-multiset-base""": 5_1_2,
}
lowerCamelCase__     :		Dict        = {
    """facebook/dpr-reader-single-nq-base""": 5_1_2,
    """facebook/dpr-reader-multiset-base""": 5_1_2,
}


lowerCamelCase__     :		Dict        = {
    """facebook/dpr-ctx_encoder-single-nq-base""": {"""do_lower_case""": True},
    """facebook/dpr-ctx_encoder-multiset-base""": {"""do_lower_case""": True},
}
lowerCamelCase__     :		Any        = {
    """facebook/dpr-question_encoder-single-nq-base""": {"""do_lower_case""": True},
    """facebook/dpr-question_encoder-multiset-base""": {"""do_lower_case""": True},
}
lowerCamelCase__     :		List[str]        = {
    """facebook/dpr-reader-single-nq-base""": {"""do_lower_case""": True},
    """facebook/dpr-reader-multiset-base""": {"""do_lower_case""": True},
}



class    _snake_case (						UpperCAmelCase_				):
 __lowerCAmelCase	:  Optional[int]	   =      VOCAB_FILES_NAMES
 __lowerCAmelCase	:  int	   =      CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
 __lowerCAmelCase	:  List[Any]	   =      CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCAmelCase	:  List[Any]	   =      CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
 __lowerCAmelCase	:  Any	   =      DPRContextEncoderTokenizer



class    _snake_case (						UpperCAmelCase_				):
 __lowerCAmelCase	:  Optional[Any]	   =      VOCAB_FILES_NAMES
 __lowerCAmelCase	:  Any	   =      QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
 __lowerCAmelCase	:  List[Any]	   =      QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCAmelCase	:  Optional[int]	   =      QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
 __lowerCAmelCase	:  List[str]	   =      DPRQuestionEncoderTokenizer

lowerCamelCase__     :		Any        = collections.namedtuple(
    """DPRSpanPrediction""", ["""span_score""", """relevance_score""", """doc_id""", """start_index""", """end_index""", """text"""]
)

lowerCamelCase__     :		int        = collections.namedtuple("""DPRReaderOutput""", ["""start_logits""", """end_logits""", """relevance_logits"""])


lowerCamelCase__     :		Optional[int]        = 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)

    Return:
        `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(UpperCAmelCase_				)
class    _snake_case :


 def __call__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = False       ,	SCREAMING_SNAKE_CASE_ = False       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	SCREAMING_SNAKE_CASE_ = None       ,	**SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




   if titles is None and texts is None:
     return super().__call__(
         SCREAMING_SNAKE_CASE_       ,	padding=SCREAMING_SNAKE_CASE_       ,	truncation=SCREAMING_SNAKE_CASE_       ,	max_length=SCREAMING_SNAKE_CASE_       ,	return_tensors=SCREAMING_SNAKE_CASE_       ,	return_attention_mask=SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_       ,	)
   elif titles is None or texts is None:
     lowercase__	: Union[str, Any]     		=   titles if texts is None else texts
     return super().__call__(
         SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	padding=SCREAMING_SNAKE_CASE_       ,	truncation=SCREAMING_SNAKE_CASE_       ,	max_length=SCREAMING_SNAKE_CASE_       ,	return_tensors=SCREAMING_SNAKE_CASE_       ,	return_attention_mask=SCREAMING_SNAKE_CASE_       ,	**SCREAMING_SNAKE_CASE_       ,	)
   lowercase__	: Optional[int]     		=   titles if not isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_) else [titles]
   lowercase__	: List[Any]     		=   texts if not isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_) else [texts]
   lowercase__	: int     		=   len(SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[int]     		=   questions if not isinstance(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_) else [questions] * n_passages
   assert len(SCREAMING_SNAKE_CASE_) == len(
       SCREAMING_SNAKE_CASE_), f'There should be as many titles than texts but got {len(SCREAMING_SNAKE_CASE_)} titles and {len(SCREAMING_SNAKE_CASE_)} texts.'
   lowercase__	: Dict     		=   super().__call__(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	padding=SCREAMING_SNAKE_CASE_       ,	truncation=SCREAMING_SNAKE_CASE_)["""input_ids"""]
   lowercase__	: Union[str, Any]     		=   super().__call__(SCREAMING_SNAKE_CASE_       ,	add_special_tokens=SCREAMING_SNAKE_CASE_       ,	padding=SCREAMING_SNAKE_CASE_       ,	truncation=SCREAMING_SNAKE_CASE_)["""input_ids"""]
   lowercase__	: Union[str, Any]     		=   {
       """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(SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_)
       ]
   }
   if return_attention_mask is not False:
     lowercase__	: Optional[int]     		=   []
     for input_ids in encoded_inputs["input_ids"]:
       attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
     lowercase__	: List[str]     		=   attention_mask
   return self.pad(SCREAMING_SNAKE_CASE_       ,	padding=SCREAMING_SNAKE_CASE_       ,	max_length=SCREAMING_SNAKE_CASE_       ,	return_tensors=SCREAMING_SNAKE_CASE_)


 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_ = 16       ,	SCREAMING_SNAKE_CASE_ = 64       ,	SCREAMING_SNAKE_CASE_ = 4       ,	):


   '''simple docstring'''




   lowercase__	: Dict     		=   reader_input["""input_ids"""]
   lowercase__		,     lowercase__		,     lowercase__	: str     		=   reader_output[:3]
   lowercase__	: List[Any]     		=   len(SCREAMING_SNAKE_CASE_)
   lowercase__	: Union[str, Any]     		=   sorted(range(SCREAMING_SNAKE_CASE_)       ,	reverse=SCREAMING_SNAKE_CASE_       ,	key=relevance_logits.__getitem__)
   lowercase__	: List[DPRReaderOutput]     		=   []
   for doc_id in sorted_docs:
     lowercase__	: Dict     		=   list(input_ids[doc_id])
     # assuming question & title information is at the beginning of the sequence
     lowercase__	: Optional[Any]     		=   sequence_ids.index(self.sep_token_id       ,	2) + 1  # second sep id
     if sequence_ids[-1] == self.pad_token_id:
       lowercase__	: int     		=   sequence_ids.index(self.pad_token_id)
     else:
       lowercase__	: Optional[int]     		=   len(SCREAMING_SNAKE_CASE_)

     lowercase__	: int     		=   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=SCREAMING_SNAKE_CASE_       ,	top_spans=SCREAMING_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=SCREAMING_SNAKE_CASE_       ,	start_index=SCREAMING_SNAKE_CASE_       ,	end_index=SCREAMING_SNAKE_CASE_       ,	text=self.decode(sequence_ids[start_index : end_index + 1])       ,	))
     if len(SCREAMING_SNAKE_CASE_) >= num_spans:
       break
   return nbest_spans_predictions[:num_spans]



 def   lowercase__  (       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	):


   '''simple docstring'''




   lowercase__	: Tuple     		=   []
   for start_index, start_score in enumerate(SCREAMING_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))
   lowercase__	: Optional[Any]     		=   sorted(SCREAMING_SNAKE_CASE_       ,	key=lambda SCREAMING_SNAKE_CASE_: x[1]       ,	reverse=SCREAMING_SNAKE_CASE_)
   lowercase__	: Tuple     		=   []
   for (start_index, end_index), score in scores:
     assert start_index <= end_index, f'Wrong span indices: [{start_index}:{end_index}]'
     lowercase__	: Dict     		=   end_index - start_index + 1
     assert length <= max_answer_length, 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(SCREAMING_SNAKE_CASE_) == top_spans:
       break
   return chosen_span_intervals



@add_end_docstrings(UpperCAmelCase_				)
class    _snake_case (						UpperCAmelCase_	,    UpperCAmelCase_				):
 __lowerCAmelCase	:  int	   =      VOCAB_FILES_NAMES
 __lowerCAmelCase	:  Optional[Any]	   =      READER_PRETRAINED_VOCAB_FILES_MAP
 __lowerCAmelCase	:  Any	   =      READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __lowerCAmelCase	:  Any	   =      READER_PRETRAINED_INIT_CONFIGURATION
 __lowerCAmelCase	:  Optional[Any]	   =      ['input_ids', 'attention_mask']
 __lowerCAmelCase	:  int	   =      DPRReaderTokenizer













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



