





'''simple docstring'''





from typing import Dict, Optional

import numpy as np

import datasets


UpperCAmelCase_  							=				'\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n'

UpperCAmelCase_  							=				'\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric("mean_iou")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), \'per_category_accuracy\': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n'

UpperCAmelCase_  							=				'\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}'




def 	lowerCAmelCase_					(						__UpperCAmelCase:    List[str]	,     __UpperCAmelCase:    List[str]	,     __UpperCAmelCase:    int	,     __UpperCAmelCase:    str	,     __UpperCAmelCase:    Optional[Any] = None	,     __UpperCAmelCase:    Optional[int] = False	,     )   ->			Union[str, Any]:
    if label_map is not None:
        for old_id, new_id in label_map.items():
            UpperCamelCase__							:       Optional[Any]      =   new_id

    # turn into Numpy arrays
    UpperCamelCase__							:       str      =   np.array(lowerCamelCase_   )
    UpperCamelCase__							:       Dict      =   np.array(lowerCamelCase_   )

    if reduce_labels:
        UpperCamelCase__							:       List[str]      =   255
        UpperCamelCase__							:       Union[str, Any]      =   label - 1
        UpperCamelCase__							:       Optional[Any]      =   255

    UpperCamelCase__							:       Dict      =   label != ignore_index
    UpperCamelCase__							:       List[Any]      =   np.not_equal(lowerCamelCase_	,     lowerCamelCase_   )
    UpperCamelCase__							:       int      =   pred_label[mask]
    UpperCamelCase__							:       Optional[Any]      =   np.array(lowerCamelCase_   )[mask]

    UpperCamelCase__							:       Union[str, Any]      =   pred_label[pred_label == label]

    UpperCamelCase__							:       int      =   np.histogram(lowerCamelCase_	,     bins=lowerCamelCase_	,     range=(0, num_labels - 1)   )[0]
    UpperCamelCase__							:       Optional[int]      =   np.histogram(lowerCamelCase_	,     bins=lowerCamelCase_	,     range=(0, num_labels - 1)   )[0]
    UpperCamelCase__							:       Optional[int]      =   np.histogram(lowerCamelCase_	,     bins=lowerCamelCase_	,     range=(0, num_labels - 1)   )[0]

    UpperCamelCase__							:       int      =   area_pred_label + area_label - area_intersect

    return area_intersect, area_union, area_pred_label, area_label




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Any	,     __UpperCAmelCase:    Tuple	,     __UpperCAmelCase:    Union[str, Any]	,     __UpperCAmelCase:    Optional[Any]	,     __UpperCAmelCase:    int = None	,     __UpperCAmelCase:    str = False	,     )   ->			List[Any]:
    UpperCamelCase__							:       Optional[int]      =   np.zeros((num_labels,)	,     dtype=np.floataa   )
    UpperCamelCase__							:       Dict      =   np.zeros((num_labels,)	,     dtype=np.floataa   )
    UpperCamelCase__							:       int      =   np.zeros((num_labels,)	,     dtype=np.floataa   )
    UpperCamelCase__							:       Tuple      =   np.zeros((num_labels,)	,     dtype=np.floataa   )
    for result, gt_seg_map in zip(lowerCamelCase_	,     lowerCamelCase_   ):
        UpperCamelCase__							:       Tuple      =   intersect_and_union(
            lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_   )
        total_area_intersect += area_intersect
        total_area_union += area_union
        total_area_pred_label += area_pred_label
        total_area_label += area_label
    return total_area_intersect, total_area_union, total_area_pred_label, total_area_label




def 	lowerCAmelCase_					(						__UpperCAmelCase:    Dict	,     __UpperCAmelCase:    int	,     __UpperCAmelCase:    int	,     __UpperCAmelCase:    Optional[Any]	,     __UpperCAmelCase:    int = None	,     __UpperCAmelCase:    Any = None	,     __UpperCAmelCase:    List[str] = False	,     )   ->			Optional[Any]:
    UpperCamelCase__							:       Dict      =   total_intersect_and_union(
        lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_	,     lowerCamelCase_   )

    # compute metrics
    UpperCamelCase__							:       Optional[int]      =   {}

    UpperCamelCase__							:       List[Any]      =   total_area_intersect.sum() / total_area_label.sum()
    UpperCamelCase__							:       Tuple      =   total_area_intersect / total_area_union
    UpperCamelCase__							:       str      =   total_area_intersect / total_area_label

    UpperCamelCase__							:       Union[str, Any]      =   np.nanmean(lowerCamelCase_   )
    UpperCamelCase__							:       List[Any]      =   np.nanmean(lowerCamelCase_   )
    UpperCamelCase__							:       Any      =   all_acc
    UpperCamelCase__							:       Optional[int]      =   iou
    UpperCamelCase__							:       Union[str, Any]      =   acc

    if nan_to_num is not None:
        UpperCamelCase__							:       Optional[int]      =   {metric: np.nan_to_num(lowerCamelCase_	,     nan=lowerCamelCase_   ) for metric, metric_value in metrics.items()}

    return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,       _KWARGS_DESCRIPTION       )
class 					lowercase__ (			datasets.Metric       ):

   '''simple docstring'''


   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       return datasets.MetricInfo(
           description=_DESCRIPTION,	citation=_CITATION,	inputs_description=_KWARGS_DESCRIPTION,	features=datasets.Features(
               # 1st Seq - height dim, 2nd - width dim
               {
                   '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''							)							)							),
                   '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''							)							)							),
               }							),	reference_urls=[
               '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'''
           ],	)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__,	__magic_name__,	__magic_name__ = None,	__magic_name__ = None,	__magic_name__ = False,	)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   mean_iou(
           results=UpperCAmelCase_,	gt_seg_maps=UpperCAmelCase_,	num_labels=UpperCAmelCase_,	ignore_index=UpperCAmelCase_,	nan_to_num=UpperCAmelCase_,	label_map=UpperCAmelCase_,	reduce_labels=UpperCAmelCase_,	)
       return iou_result








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

   '''simple docstring'''


   def __init__(					self,	__magic_name__,	__magic_name__ = 13,	__magic_name__ = 64,	__magic_name__ = 2,	__magic_name__ = 3,	__magic_name__ = 3,	__magic_name__ = True,	__magic_name__ = True,	__magic_name__ = 128,	__magic_name__=[16, 32, 64, 128],	__magic_name__ = 7,	__magic_name__ = 4,	__magic_name__ = 37,	__magic_name__ = "gelu",	__magic_name__ = 0.1,	__magic_name__ = 0.1,	__magic_name__ = 10,	__magic_name__ = 0.02,	__magic_name__ = 2,	__magic_name__ = 1,	__magic_name__ = 128,	__magic_name__ = [2, 2, 2, 2],	__magic_name__ = 2,	__magic_name__ = 2,	)				->   List[str]:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   parent
       UpperCamelCase__							:       Optional[int]      =   batch_size
       UpperCamelCase__							:       Optional[Any]      =   image_size
       UpperCamelCase__							:       Optional[int]      =   patch_size
       UpperCamelCase__							:       Any      =   num_channels
       UpperCamelCase__							:       int      =   is_training
       UpperCamelCase__							:       str      =   use_labels
       UpperCamelCase__							:       Optional[Any]      =   hidden_size
       UpperCamelCase__							:       Tuple      =   num_hidden_layers
       UpperCamelCase__							:       str      =   num_attention_heads
       UpperCamelCase__							:       Any      =   intermediate_size
       UpperCamelCase__							:       int      =   hidden_act
       UpperCamelCase__							:       Dict      =   hidden_dropout_prob
       UpperCamelCase__							:       str      =   attention_probs_dropout_prob
       UpperCamelCase__							:       Tuple      =   type_sequence_label_size
       UpperCamelCase__							:       Optional[Any]      =   initializer_range
       UpperCamelCase__							:       Optional[int]      =   encoder_stride
       UpperCamelCase__							:       Any      =   num_attention_outputs
       UpperCamelCase__							:       Dict      =   embed_dim
       UpperCamelCase__							:       str      =   embed_dim + 1
       UpperCamelCase__							:       int      =   resolution
       UpperCamelCase__							:       List[str]      =   depths
       UpperCamelCase__							:       str      =   hidden_sizes
       UpperCamelCase__							:       Tuple      =   dim
       UpperCamelCase__							:       Optional[int]      =   mlp_expansion_ratio




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






       """simple docstring"""
       UpperCamelCase__							:       Union[str, Any]      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

       UpperCamelCase__							:       Dict      =   None
       if self.use_labels:
           UpperCamelCase__							:       Optional[Any]      =   ids_tensor([self.batch_size],	self.type_sequence_label_size							)

       UpperCamelCase__							:       int      =   self.get_config()

       return config, pixel_values, labels




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       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=__magic_name__,	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    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       Dict      =   TFEfficientFormerModel(config=__magic_name__							)
       UpperCamelCase__							:       str      =   model(__magic_name__,	training=__magic_name__							)
       self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[int]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[int]      =   self.type_sequence_label_size
       UpperCamelCase__							:       Dict      =   TFEfficientFormerForImageClassification(__magic_name__							)
       UpperCamelCase__							:       Any      =   model(__magic_name__,	labels=__magic_name__,	training=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)

       # test greyscale images
       UpperCamelCase__							:       Optional[Any]      =   1
       UpperCamelCase__							:       List[str]      =   TFEfficientFormerForImageClassification(__magic_name__							)

       UpperCamelCase__							:       List[Any]      =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
       UpperCamelCase__							:       Union[str, Any]      =   model(__magic_name__,	labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)




   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   self.prepare_config_and_inputs()
       UpperCamelCase__     ,UpperCamelCase__     ,UpperCamelCase__							:       Dict      =   config_and_inputs
       UpperCamelCase__							:       Any      =   {'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_tf
class 					lowercase__ (			__lowerCamelCase    ,       __lowerCamelCase    ,       unittest.TestCase       ):

   '''simple docstring'''


   a		:							int     	=	(
       (
           TFEfficientFormerModel,
           TFEfficientFormerForImageClassificationWithTeacher,
           TFEfficientFormerForImageClassification,
       )
       if is_tf_available()
       else ()
   )
   a		:							Union[str, Any]     	=	(
       {
           "feature-extraction": TFEfficientFormerModel,
           "image-classification": (
               TFEfficientFormerForImageClassification,
               TFEfficientFormerForImageClassificationWithTeacher,
           ),
       }
       if is_tf_available()
       else {}
   )

   a		:							Any     	=	False

   a		:							Tuple     	=	False
   a		:							Any     	=	False
   a		:							int     	=	False
   a		:							Tuple     	=	False




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






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   TFEfficientFormerModelTester(self							)
       UpperCamelCase__							:       int      =   ConfigTester(
           self,	config_class=__magic_name__,	has_text_modality=__magic_name__,	hidden_size=37							)




   def    UpperCamelCase__						(					self							)				->   str:






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




   @unittest.skip(reason='''EfficientFormer does not use inputs_embeds'''							)
   def    UpperCamelCase__						(					self							)				->   Any:






       """simple docstring"""
       pass




   @unittest.skip(reason='''EfficientFormer does not support input and output embeddings'''							)
   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       pass




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       Any      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       List[str]      =   model_class(__magic_name__							)
           UpperCamelCase__							:       List[Any]      =   inspect.signature(model.call							)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           UpperCamelCase__							:       List[str]      =   [*signature.parameters.keys()]

           UpperCamelCase__							:       int      =   ['''pixel_values''']
           self.assertListEqual(arg_names[:1],	__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       def check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							):
           UpperCamelCase__							:       Union[str, Any]      =   model_class(__magic_name__							)

           UpperCamelCase__							:       str      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)
           UpperCamelCase__							:       Tuple      =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           UpperCamelCase__							:       Optional[int]      =   getattr(
               self.model_tester,	'''expected_num_hidden_layers''',	self.model_tester.num_hidden_layers + 1							)
           self.assertEqual(len(__magic_name__							),	__magic_name__							)

           if hasattr(self.model_tester,	'''encoder_seq_length'''							):
               UpperCamelCase__							:       Dict      =   self.model_tester.encoder_seq_length
               if hasattr(self.model_tester,	'''chunk_length'''							) and self.model_tester.chunk_length > 1:
                   UpperCamelCase__							:       Tuple      =   seq_length * self.model_tester.chunk_length
           else:
               UpperCamelCase__							:       Optional[Any]      =   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:
               UpperCamelCase__							:       List[str]      =   outputs.decoder_hidden_states

               self.asseretIsInstance(__magic_name__,	(list, tuple)							)
               self.assertEqual(len(__magic_name__							),	__magic_name__							)
               UpperCamelCase__							:       str      =   getattr(self.model_tester,	'''seq_length''',	__magic_name__							)
               UpperCamelCase__							:       Optional[Any]      =   getattr(self.model_tester,	'''decoder_seq_length''',	__magic_name__							)

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

       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       List[str]      =   True
           check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           UpperCamelCase__							:       List[Any]      =   True

           check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							)




   def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__=False							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   super()._prepare_for_class(__magic_name__,	__magic_name__,	return_labels=__magic_name__							)

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

       return inputs_dict




   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   @unittest.skip(reason='''EfficientFormer does not implement masked image modeling yet'''							)
   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:       Optional[int]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       List[Any]      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__magic_name__							)




   @slow
   def    UpperCamelCase__						(					self							)				->   Optional[int]:






       """simple docstring"""
       for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:       Dict      =   TFEfficientFormerModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Tuple:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__							:       Dict      =   True

       UpperCamelCase__							:       Optional[Any]      =   getattr(self.model_tester,	'''seq_length''',	__magic_name__							)
       UpperCamelCase__							:       Any      =   getattr(self.model_tester,	'''encoder_seq_length''',	__magic_name__							)
       UpperCamelCase__							:       Tuple      =   getattr(self.model_tester,	'''key_length''',	__magic_name__							)
       UpperCamelCase__							:       Union[str, Any]      =   getattr(self.model_tester,	'''chunk_length''',	__magic_name__							)

       if chunk_length is not None and hasattr(self.model_tester,	'''num_hashes'''							):
           UpperCamelCase__							:       Dict      =   encoder_seq_length * self.model_tester.num_hashes

       for model_class in self.all_model_classes:
           UpperCamelCase__							:       Dict      =   True
           UpperCamelCase__							:       Optional[int]      =   False
           UpperCamelCase__							:       Any      =   True
           UpperCamelCase__							:       str      =   model_class(__magic_name__							)

           UpperCamelCase__							:       Optional[int]      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)
           UpperCamelCase__							:       List[str]      =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__magic_name__							),	self.model_tester.num_attention_outputs							)

           # check that output_attentions also work using config
           del inputs_dict["output_attentions"]
           UpperCamelCase__							:       Optional[int]      =   True
           UpperCamelCase__							:       int      =   model_class(__magic_name__							)
           UpperCamelCase__							:       str      =   model(**self._prepare_for_class(__magic_name__,	__magic_name__							),	training=__magic_name__							)

           UpperCamelCase__							:       List[str]      =   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__magic_name__							),	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    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       # 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
       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

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




def 	lowerCAmelCase_					(						)   ->			List[str]:
    UpperCamelCase__							:       Any      =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
    return image






@require_tf
@require_vision
class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


   @cached_property
   def    UpperCamelCase__						(					self							)				->   Union[str, Any]:






       """simple docstring"""
       return (
           EfficientFormerImageProcessor.from_pretrained('''snap-research/efficientformer-l1-300'''							)
           if is_vision_available()
           else None
       )




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






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   TFEfficientFormerForImageClassification.from_pretrained('''snap-research/efficientformer-l1-300'''							)
       UpperCamelCase__							:       Dict      =   self.default_image_processor
       UpperCamelCase__							:       List[str]      =   prepare_img()
       UpperCamelCase__							:       str      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)
       # forward pass
       UpperCamelCase__							:       Dict      =   model(**__magic_name__,	training=__magic_name__							)
       # verify the logits
       UpperCamelCase__							:       Tuple      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)
       UpperCamelCase__							:       List[str]      =   tf.constant([-0.0555, 0.4825, -0.0852]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3],	__magic_name__,	atol=1E-4							)							)




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






       """simple docstring"""
       UpperCamelCase__							:       str      =   TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
           '''snap-research/efficientformer-l1-300'''							)
       UpperCamelCase__							:       List[str]      =   self.default_image_processor
       UpperCamelCase__							:       Union[str, Any]      =   prepare_img()
       UpperCamelCase__							:       int      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)
       # forward pass
       UpperCamelCase__							:       Tuple      =   model(**__magic_name__,	training=__magic_name__							)
       # verify the logits
       UpperCamelCase__							:       Tuple      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)
       UpperCamelCase__							:       Optional[int]      =   tf.constant([-0.1312, 0.4353, -1.0499]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3],	__magic_name__,	atol=1E-4							)							)

