




'''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_							:	int	     =		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_							:	int	     =		{
    '''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_							:	int	     =		{
    '''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_							:	Dict	     =		{
    '''facebook/dpr-ctx_encoder-single-nq-base''': 5_1_2,
    '''facebook/dpr-ctx_encoder-multiset-base''': 5_1_2,
}
UpperCAmelCase_							:	List[Any]	     =		{
    '''facebook/dpr-question_encoder-single-nq-base''': 5_1_2,
    '''facebook/dpr-question_encoder-multiset-base''': 5_1_2,
}
UpperCAmelCase_							:	str	     =		{
    '''facebook/dpr-reader-single-nq-base''': 5_1_2,
    '''facebook/dpr-reader-multiset-base''': 5_1_2,
}


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





class      lowerCAmelCase (			__UpperCamelCase):
       __lowercase	:   List[Any]										=      VOCAB_FILES_NAMES
       __lowercase	:   Optional[int]										=      CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       __lowercase	:   List[str]										=      CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __lowercase	:   List[str]										=      CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION





class      lowerCAmelCase (			__UpperCamelCase):
       __lowercase	:   Dict										=      VOCAB_FILES_NAMES
       __lowercase	:   Any										=      QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
       __lowercase	:   Dict										=      QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __lowercase	:   Optional[int]										=      QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION





UpperCAmelCase_							:	List[str]	     =		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_							:	List[str]	     =		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(__UpperCamelCase)
class      lowerCAmelCase :


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



            '''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:
                 __snake_case            =	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     ,	)
            __snake_case            =	titles if not isinstance(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	) else [titles]
            __snake_case            =	texts if not isinstance(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	) else [texts]
            __snake_case            =	len(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	questions if not isinstance(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	) else [questions] * n_passages
            if len(__SCREAMING_SNAKE_CASE	) != len(__SCREAMING_SNAKE_CASE	):
                 raise ValueError(
                     F'''There should be as many titles than texts but got {len(__SCREAMING_SNAKE_CASE	)} titles and {len(__SCREAMING_SNAKE_CASE	)} texts.'''	)
            __snake_case            =	super().__call__(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	padding=__SCREAMING_SNAKE_CASE     ,	truncation=__SCREAMING_SNAKE_CASE	)['''input_ids''']
            __snake_case            =	super().__call__(__SCREAMING_SNAKE_CASE     ,	add_special_tokens=__SCREAMING_SNAKE_CASE     ,	padding=__SCREAMING_SNAKE_CASE     ,	truncation=__SCREAMING_SNAKE_CASE	)['''input_ids''']
            __snake_case            =	{
                '''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:
                 __snake_case            =	[]
                 for input_ids in encoded_inputs["input_ids"]:
                      attention_mask.append([int(input_id != self.pad_token_id	) for input_id in input_ids]	)
                 __snake_case            =	attention_mask
            return self.pad(__SCREAMING_SNAKE_CASE     ,	padding=__SCREAMING_SNAKE_CASE     ,	max_length=__SCREAMING_SNAKE_CASE     ,	return_tensors=__SCREAMING_SNAKE_CASE	)


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE = 16     ,	__SCREAMING_SNAKE_CASE = 64     ,	__SCREAMING_SNAKE_CASE = 4     ,	)   ->	Optional[Any]:



            '''simple docstring'''




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

                 __snake_case            =	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    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	)   ->	Union[str, Any]:



            '''simple docstring'''




            __snake_case            =	[]
            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)	)
            __snake_case            =	sorted(__SCREAMING_SNAKE_CASE     ,	key=lambda __SCREAMING_SNAKE_CASE	: x[1]     ,	reverse=__SCREAMING_SNAKE_CASE	)
            __snake_case            =	[]
            for (start_index, end_index), score in scores:
                 if start_index > end_index:
                      raise ValueError(F'''Wrong span indices: [{start_index}:{end_index}]'''	)
                 __snake_case            =	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(__SCREAMING_SNAKE_CASE	) == top_spans:
                      break
            return chosen_span_intervals





@add_end_docstrings(__UpperCamelCase)
class      lowerCAmelCase (			__UpperCamelCase					, __UpperCamelCase):
       __lowercase	:   Any										=      VOCAB_FILES_NAMES
       __lowercase	:   Any										=      READER_PRETRAINED_VOCAB_FILES_MAP
       __lowercase	:   Tuple										=      READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __lowercase	:   Optional[int]										=      READER_PRETRAINED_INIT_CONFIGURATION
       __lowercase	:   Any										=      ['input_ids', 'attention_mask']








import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import (
         TFEfficientFormerForImageClassification,
         TFEfficientFormerForImageClassificationWithTeacher,
         TFEfficientFormerModel,
     )
     from transformers.models.efficientformer.modeling_tf_efficientformer import (
         TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
     )


if is_vision_available():
     from PIL import Image

     from transformers import EfficientFormerImageProcessor




class        _SCREAMING_SNAKE_CASE	:
      def __init__(      self		,						lowerCamelCase		,						lowerCamelCase = 13		,						lowerCamelCase = 64		,						lowerCamelCase = 2		,						lowerCamelCase = 3		,						lowerCamelCase = 3		,						lowerCamelCase = True		,						lowerCamelCase = True		,						lowerCamelCase = 1_28		,						lowerCamelCase=[16, 32, 64, 1_28]		,						lowerCamelCase = 7		,						lowerCamelCase = 4		,						lowerCamelCase = 37		,						lowerCamelCase = "gelu"		,						lowerCamelCase = 0.1		,						lowerCamelCase = 0.1		,						lowerCamelCase = 10		,						lowerCamelCase = 0.0_2		,						lowerCamelCase = 2		,						lowerCamelCase = 1		,						lowerCamelCase = 1_28		,						lowerCamelCase = [2, 2, 2, 2]		,						lowerCamelCase = 2		,						lowerCamelCase = 2		,						):
          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__    =					encoder_stride
          snake_case__    =					num_attention_outputs
          snake_case__    =					embed_dim
          snake_case__    =					embed_dim + 1
          snake_case__    =					resolution
          snake_case__    =					depths
          snake_case__    =					hidden_sizes
          snake_case__    =					dim
          snake_case__    =					mlp_expansion_ratio
      def A_      (      self			):
          snake_case__    =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

          snake_case__    =					None
          if self.use_labels:
              snake_case__    =					ids_tensor([self.batch_size]		,						self.type_sequence_label_size			)

          snake_case__    =					self.get_config()

          return config, pixel_values, labels
      def A_      (      self			):
          return EfficientFormerConfig(
              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=lowerCamelCase		,						initializer_range=self.initializer_range		,						encoder_stride=self.encoder_stride		,						resolution=self.resolution		,						depths=self.depths		,						hidden_sizes=self.hidden_sizes		,						dim=self.dim		,						mlp_expansion_ratio=self.mlp_expansion_ratio		,						)
      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			):
          snake_case__    =					TFEfficientFormerModel(config=lowerCamelCase			)
          snake_case__    =					model(lowerCamelCase		,						training=lowerCamelCase			)
          self.parent.assertEqual(result.last_hidden_state.shape		,						(self.batch_size, self.seq_length, self.hidden_size)			)
      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			):
          snake_case__    =					self.type_sequence_label_size
          snake_case__    =					TFEfficientFormerForImageClassification(lowerCamelCase			)
          snake_case__    =					model(lowerCamelCase		,						labels=lowerCamelCase		,						training=lowerCamelCase			)
          self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.type_sequence_label_size)			)

          # test greyscale images
          snake_case__    =					1
          snake_case__    =					TFEfficientFormerForImageClassification(lowerCamelCase			)

          snake_case__    =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
          snake_case__    =					model(lowerCamelCase		,						labels=lowerCamelCase			)
          self.parent.assertEqual(result.logits.shape		,						(self.batch_size, self.type_sequence_label_size)			)



      def A_      (      self			):
          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_tf
class        _SCREAMING_SNAKE_CASE	(   __UpperCamelCase							,       __UpperCamelCase							,       unittest.TestCase			):
      _A    :		str     						=  (
          (
              TFEfficientFormerModel,
              TFEfficientFormerForImageClassificationWithTeacher,
              TFEfficientFormerForImageClassification,
          )
          if is_tf_available()
          else ()
      )
      _A    :		List[str]     						=  (
          {
              'feature-extraction': TFEfficientFormerModel,
              'image-classification': (
                  TFEfficientFormerForImageClassification,
                  TFEfficientFormerForImageClassificationWithTeacher,
              ),
          }
          if is_tf_available()
          else {}
      )

      _A    :		Optional[Any]     						=  False

      _A    :		List[Any]     						=  False
      _A    :		Tuple     						=  False
      _A    :		List[Any]     						=  False
      _A    :		Any     						=  False
      def A_      (      self			):
          snake_case__    =					TFEfficientFormerModelTester(self			)
          snake_case__    =					ConfigTester(
              self		,						config_class=lowerCamelCase		,						has_text_modality=lowerCamelCase		,						hidden_size=37			)
      def A_      (      self			):
          self.config_tester.run_common_tests()
      @unittest.skip(reason="EfficientFormer does not use inputs_embeds"			)
      def A_      (      self			):
          pass
      @unittest.skip(reason="EfficientFormer does not support input and output embeddings"			)
      def A_      (      self			):
          pass
      def A_      (      self			):
          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(lowerCamelCase			)
              snake_case__    =					inspect.signature(model.call			)
              # 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]		,						lowerCamelCase			)
      def A_      (      self			):
          def check_hidden_states_output(lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			):
              snake_case__    =					model_class(lowerCamelCase			)

              snake_case__    =					model(**self._prepare_for_class(lowerCamelCase		,						lowerCamelCase			)		,						training=lowerCamelCase			)
              snake_case__    =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              snake_case__    =					getattr(
                  self.model_tester		,						"expected_num_hidden_layers"		,						self.model_tester.num_hidden_layers + 1			)
              self.assertEqual(len(lowerCamelCase			)		,						lowerCamelCase			)

              if hasattr(self.model_tester		,						"encoder_seq_length"			):
                  snake_case__    =					self.model_tester.encoder_seq_length
                  if hasattr(self.model_tester		,						"chunk_length"			) and self.model_tester.chunk_length > 1:
                      snake_case__    =					seq_length * self.model_tester.chunk_length
              else:
                  snake_case__    =					self.model_tester.seq_length

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

              if config.is_encoder_decoder:
                  snake_case__    =					outputs.decoder_hidden_states

                  self.asseretIsInstance(lowerCamelCase		,						(list, tuple)			)
                  self.assertEqual(len(lowerCamelCase			)		,						lowerCamelCase			)
                  snake_case__    =					getattr(self.model_tester		,						"seq_length"		,						lowerCamelCase			)
                  snake_case__    =					getattr(self.model_tester		,						"decoder_seq_length"		,						lowerCamelCase			)

                  self.assertListEqual(
                      list(hidden_states[-1].shape[-2:]			)		,						[decoder_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(lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			)

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

              check_hidden_states_output(lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase			)
      def A_      (      self		,						lowerCamelCase		,						lowerCamelCase		,						lowerCamelCase=False			):
          snake_case__    =					super()._prepare_for_class(lowerCamelCase		,						lowerCamelCase		,						return_labels=lowerCamelCase			)

          if return_labels:
              if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
                  del inputs_dict["labels"]

          return inputs_dict
      def A_      (      self			):
          snake_case__    =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase			)
      @unittest.skip(reason="EfficientFormer does not implement masked image modeling yet"			)
      def A_      (      self			):
          snake_case__    =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase			)
      def A_      (      self			):
          snake_case__    =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase			)
      @slow
      def A_      (      self			):
          for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              snake_case__    =					TFEfficientFormerModel.from_pretrained(lowerCamelCase			)
              self.assertIsNotNone(lowerCamelCase			)
      def A_      (      self			):
          snake_case__    ,       snake_case__    =					self.model_tester.prepare_config_and_inputs_for_common()
          snake_case__    =					True

          snake_case__    =					getattr(self.model_tester		,						"seq_length"		,						lowerCamelCase			)
          snake_case__    =					getattr(self.model_tester		,						"encoder_seq_length"		,						lowerCamelCase			)
          snake_case__    =					getattr(self.model_tester		,						"key_length"		,						lowerCamelCase			)
          snake_case__    =					getattr(self.model_tester		,						"chunk_length"		,						lowerCamelCase			)

          if chunk_length is not None and hasattr(self.model_tester		,						"num_hashes"			):
              snake_case__    =					encoder_seq_length * self.model_tester.num_hashes

          for model_class in self.all_model_classes:
              snake_case__    =					True
              snake_case__    =					False
              snake_case__    =					True
              snake_case__    =					model_class(lowerCamelCase			)

              snake_case__    =					model(**self._prepare_for_class(lowerCamelCase		,						lowerCamelCase			)		,						training=lowerCamelCase			)
              snake_case__    =					outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
              self.assertEqual(len(lowerCamelCase			)		,						self.model_tester.num_attention_outputs			)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              snake_case__    =					True
              snake_case__    =					model_class(lowerCamelCase			)
              snake_case__    =					model(**self._prepare_for_class(lowerCamelCase		,						lowerCamelCase			)		,						training=lowerCamelCase			)

              snake_case__    =					outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
              self.assertEqual(len(lowerCamelCase			)		,						self.model_tester.num_attention_outputs			)

              if chunk_length is not None:
                  self.assertListEqual(
                      list(attentions[0].shape[-4:]			)		,						[self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]		,						)
              else:
                  self.assertListEqual(
                      list(attentions[0].shape[-3:]			)		,						[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]		,						)



      def A_      (      self			):
          # We use a simplified version of this test for EfficientFormer because it requires training=False
          # and Keras refuses to let us force that during functional construction
          snake_case__    ,       snake_case__    =					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              # Prepare our model
              snake_case__    =					model_class(lowerCamelCase			)
              # These are maximally general inputs for the model, with multiple None dimensions
              # Hopefully this will catch any conditionals that fail for flexible shapes
              snake_case__    =					{
                  key: tf.keras.Input(shape=val.shape[1:]		,						dtype=val.dtype		,						name=lowerCamelCase			)
                  for key, val in model.input_signature.items()
                  if key in model.dummy_inputs
              }
              snake_case__    =					model(lowerCamelCase			)
              self.assertTrue(outputs_dict is not None			)





def 						SCREAMING_SNAKE_CASE__     (   ):
    snake_case__    =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
    return image





@require_tf
@require_vision
class        _SCREAMING_SNAKE_CASE	(   unittest.TestCase			):
      @cached_property
      def A_      (      self			):
          return (
              EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300"			)
              if is_vision_available()
              else None
          )
      @slow
      def A_      (      self			):
          snake_case__    =					TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300"			)
          snake_case__    =					self.default_image_processor
          snake_case__    =					prepare_img()
          snake_case__    =					image_processor(images=lowerCamelCase		,						return_tensors="tf"			)
          # forward pass
          snake_case__    =					model(**lowerCamelCase		,						training=lowerCamelCase			)
          # verify the logits
          snake_case__    =					tf.TensorShape((1, 10_00)			)
          self.assertEqual(outputs.logits.shape		,						lowerCamelCase			)
          snake_case__    =					tf.constant([-0.0_5_5_5, 0.4_8_2_5, -0.0_8_5_2]			)
          self.assertTrue(np.allclose(outputs.logits[0, :3]		,						lowerCamelCase		,						atol=1e-4			)			)



      @slow
      def A_      (      self			):
          snake_case__    =					TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
              "snap-research/efficientformer-l1-300"			)
          snake_case__    =					self.default_image_processor
          snake_case__    =					prepare_img()
          snake_case__    =					image_processor(images=lowerCamelCase		,						return_tensors="tf"			)
          # forward pass
          snake_case__    =					model(**lowerCamelCase		,						training=lowerCamelCase			)
          # verify the logits
          snake_case__    =					tf.TensorShape((1, 10_00)			)
          self.assertEqual(outputs.logits.shape		,						lowerCamelCase			)
          snake_case__    =					tf.constant([-0.1_3_1_2, 0.4_3_5_3, -1.0_4_9_9]			)
          self.assertTrue(np.allclose(outputs.logits[0, :3]		,						lowerCamelCase		,						atol=1e-4			)			)



