




"""simple docstring"""

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	:	Union[str, Any]   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	int = 13   ,							_UpperCAmelCase	:	int = 64   ,							_UpperCAmelCase	:	int = 2   ,							_UpperCAmelCase	:	int = 3   ,							_UpperCAmelCase	:	int = 3   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	bool = True   ,							_UpperCAmelCase	:	int = 128   ,							_UpperCAmelCase	:	int=[16, 32, 64, 128]   ,							_UpperCAmelCase	:	int = 7   ,							_UpperCAmelCase	:	int = 4   ,							_UpperCAmelCase	:	int = 37   ,							_UpperCAmelCase	:	str = "gelu"   ,							_UpperCAmelCase	:	float = 0.1   ,							_UpperCAmelCase	:	float = 0.1   ,							_UpperCAmelCase	:	int = 10   ,							_UpperCAmelCase	:	float = 0.02   ,							_UpperCAmelCase	:	int = 2   ,							_UpperCAmelCase	:	int = 1   ,							_UpperCAmelCase	:	int = 128   ,							_UpperCAmelCase	:	List[int] = [2, 2, 2, 2]   ,							_UpperCAmelCase	:	int = 2   ,							_UpperCAmelCase	:	int = 2   ,							):
       _A        =       parent
       _A        =       batch_size
       _A        =       image_size
       _A        =       patch_size
       _A        =       num_channels
       _A        =       is_training
       _A        =       use_labels
       _A        =       hidden_size
       _A        =       num_hidden_layers
       _A        =       num_attention_heads
       _A        =       intermediate_size
       _A        =       hidden_act
       _A        =       hidden_dropout_prob
       _A        =       attention_probs_dropout_prob
       _A        =       type_sequence_label_size
       _A        =       initializer_range
       _A        =       encoder_stride
       _A        =       num_attention_outputs
       _A        =       embed_dim
       _A        =       embed_dim + 1
       _A        =       resolution
       _A        =       depths
       _A        =       hidden_sizes
       _A        =       dim
       _A        =       mlp_expansion_ratio

 def       lowerCAmelCase_							(			self	:	List[str]		):
       _A        =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

       _A        =       self.get_config()

       return config, pixel_values, labels

 def       lowerCAmelCase_							(			self	:	int		):
       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       lowerCAmelCase_							(			self	:	Dict   ,							_UpperCAmelCase	:	Dict   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	List[Any]		):
       _A        =       TFEfficientFormerModel(config=_lowerCamelCase		)
       _A        =       model(_lowerCamelCase   ,							training=_lowerCamelCase		)
       self.parent.assertEqual(result.last_hidden_state.shape   ,							(self.batch_size, self.seq_length, self.hidden_size)		)

 def       lowerCAmelCase_							(			self	:	List[Any]   ,							_UpperCAmelCase	:	str   ,							_UpperCAmelCase	:	Optional[int]   ,							_UpperCAmelCase	:	Tuple		):
       _A        =       self.type_sequence_label_size
       _A        =       TFEfficientFormerForImageClassification(_lowerCamelCase		)
       _A        =       model(_lowerCamelCase   ,							labels=_lowerCamelCase   ,							training=_lowerCamelCase		)
       self.parent.assertEqual(result.logits.shape   ,							(self.batch_size, self.type_sequence_label_size)		)

       # test greyscale images
       _A        =       1
       _A        =       TFEfficientFormerForImageClassification(_lowerCamelCase		)

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



 def       lowerCAmelCase_							(			self	:	Any		):
       _A        =       self.prepare_config_and_inputs()
       _A       ,   _A       ,   _A        =       config_and_inputs
       _A        =       {'pixel_values': pixel_values}
       return config, inputs_dict





@require_tf
class     lowercase_	(					A_      ,     A_      ,     unittest.TestCase							):



 '''simple docstring'''
 UpperCAmelCase   :					Any				  =     (
     (
         TFEfficientFormerModel,
         TFEfficientFormerForImageClassificationWithTeacher,
         TFEfficientFormerForImageClassification,
     )
     if is_tf_available()
     else ()
 )
 UpperCAmelCase   :					Union[str, Any]				  =     (
     {
         '''feature-extraction''': TFEfficientFormerModel,
         '''image-classification''': (
             TFEfficientFormerForImageClassification,
             TFEfficientFormerForImageClassificationWithTeacher,
         ),
     }
     if is_tf_available()
     else {}
 )

 UpperCAmelCase   :					Optional[int]				  =     False

 UpperCAmelCase   :					List[Any]				  =     False
 UpperCAmelCase   :					Optional[int]				  =     False
 UpperCAmelCase   :					List[str]				  =     False
 UpperCAmelCase   :					Union[str, Any]				  =     False

 def       lowerCAmelCase_							(			self	:	str		):
       _A        =       TFEfficientFormerModelTester(self		)
       _A        =       ConfigTester(
           self   ,							config_class=_lowerCamelCase   ,							has_text_modality=_lowerCamelCase   ,							hidden_size=37		)

 def       lowerCAmelCase_							(			self	:	str		):
       self.config_tester.run_common_tests()

 @unittest.skip(reason='EfficientFormer does not use inputs_embeds'		)
 def       lowerCAmelCase_							(			self	:	Any		):
       pass

 @unittest.skip(reason='EfficientFormer does not support input and output embeddings'		)
 def       lowerCAmelCase_							(			self	:	Dict		):
       pass

 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

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

             _A        =       ['pixel_values']
             self.assertListEqual(arg_names[:1]   ,							_lowerCamelCase		)

 def       lowerCAmelCase_							(			self	:	Tuple		):
       def check_hidden_states_output(_UpperCAmelCase	:	List[Any]   ,							_UpperCAmelCase	:	Optional[Any]   ,							_UpperCAmelCase	:	Dict		):
             _A        =       model_class(_lowerCamelCase		)

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

             _A        =       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'		):
                   _A        =       self.model_tester.encoder_seq_length
                   if hasattr(self.model_tester   ,							'chunk_length'		) and self.model_tester.chunk_length > 1:
                         _A        =       seq_length * self.model_tester.chunk_length
             else:
                   _A        =       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:
                   _A        =       outputs.decoder_hidden_states

                   self.asseretIsInstance(_lowerCamelCase   ,							(list, tuple)		)
                   self.assertEqual(len(_lowerCamelCase		)   ,							_lowerCamelCase		)
                   _A        =       getattr(self.model_tester   ,							'seq_length'   ,							_lowerCamelCase		)
                   _A        =       getattr(self.model_tester   ,							'decoder_seq_length'   ,							_lowerCamelCase		)

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

       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             _A        =       True
             check_hidden_states_output(_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase		)

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

             check_hidden_states_output(_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase		)

 def       lowerCAmelCase_							(			self	:	Dict   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	Optional[int]   ,							_UpperCAmelCase	:	List[Any]=False		):
       _A        =       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       lowerCAmelCase_							(			self	:	Optional[Any]		):
       _A        =       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       lowerCAmelCase_							(			self	:	Tuple		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase		)

 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       _A        =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase		)

 @slow
 def       lowerCAmelCase_							(			self	:	Tuple		):
       for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A        =       TFEfficientFormerModel.from_pretrained(_lowerCamelCase		)
             self.assertIsNotNone(_lowerCamelCase		)

 def       lowerCAmelCase_							(			self	:	int		):
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()
       _A        =       True

       _A        =       getattr(self.model_tester   ,							'seq_length'   ,							_lowerCamelCase		)
       _A        =       getattr(self.model_tester   ,							'encoder_seq_length'   ,							_lowerCamelCase		)
       _A        =       getattr(self.model_tester   ,							'key_length'   ,							_lowerCamelCase		)
       _A        =       getattr(self.model_tester   ,							'chunk_length'   ,							_lowerCamelCase		)

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

       for model_class in self.all_model_classes:
             _A        =       True
             _A        =       False
             _A        =       True
             _A        =       model_class(_lowerCamelCase		)

             _A        =       model(**self._prepare_for_class(_lowerCamelCase   ,							_lowerCamelCase		)   ,							training=_lowerCamelCase		)
             _A        =       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"]
             _A        =       True
             _A        =       model_class(_lowerCamelCase		)
             _A        =       model(**self._prepare_for_class(_lowerCamelCase   ,							_lowerCamelCase		)   ,							training=_lowerCamelCase		)

             _A        =       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       lowerCAmelCase_							(			self	:	Any		):
       # 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
       _A       ,   _A        =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             # Prepare our model
             _A        =       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
             _A        =       {
                 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
             }
             _A        =       model(_lowerCamelCase		)
             self.assertTrue(outputs_dict is not None		)






def 						UpperCAmelCase__					( )   -> List[Any]:






      '''simple docstring'''


      _A        =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
      return image







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



 '''simple docstring'''

 @cached_property
 def       lowerCAmelCase_							(			self	:	Dict		):
       return (
           EfficientFormerImageProcessor.from_pretrained('snap-research/efficientformer-l1-300'		)
           if is_vision_available()
           else None
       )

 @slow
 def       lowerCAmelCase_							(			self	:	Union[str, Any]		):
       _A        =       TFEfficientFormerForImageClassification.from_pretrained('snap-research/efficientformer-l1-300'		)
       _A        =       self.default_image_processor
       _A        =       prepare_img()
       _A        =       image_processor(images=_lowerCamelCase   ,							return_tensors='tf'		)
       # forward pass
       _A        =       model(**_lowerCamelCase   ,							training=_lowerCamelCase		)
       # verify the logits
       _A        =       tf.TensorShape((1, 1_000)		)
       self.assertEqual(outputs.logits.shape   ,							_lowerCamelCase		)
       _A        =       tf.constant([-0.0555, 0.4825, -0.0852]		)
       self.assertTrue(np.allclose(outputs.logits[0, :3]   ,							_lowerCamelCase   ,							atol=1E-4		)		)



 @slow
 def       lowerCAmelCase_							(			self	:	Optional[int]		):
       _A        =       TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
           'snap-research/efficientformer-l1-300'		)
       _A        =       self.default_image_processor
       _A        =       prepare_img()
       _A        =       image_processor(images=_lowerCamelCase   ,							return_tensors='tf'		)
       # forward pass
       _A        =       model(**_lowerCamelCase   ,							training=_lowerCamelCase		)
       # verify the logits
       _A        =       tf.TensorShape((1, 1_000)		)
       self.assertEqual(outputs.logits.shape   ,							_lowerCamelCase		)
       _A        =       tf.constant([-0.1312, 0.4353, -1.0499]		)
       self.assertTrue(np.allclose(outputs.logits[0, :3]   ,							_lowerCamelCase   ,							atol=1E-4		)		)







"""simple docstring"""

from sklearn.metrics import fa_score

import datasets


a         =      '''
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
'''


a         =      '''
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'f1\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'f1\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric("f1")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results[\'f1\'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="macro")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="micro")
        >>> print(round(results[\'f1\'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average="weighted")
        >>> print(round(results[\'f1\'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {\'f1\': array([0.8, 0. , 0. ])}
'''


a         =      '''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''





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



 '''simple docstring'''

 def       lowerCAmelCase_							(			self	:	Any		):
       return datasets.MetricInfo(
           description=_DESCRIPTION   ,							citation=_CITATION   ,							inputs_description=_KWARGS_DESCRIPTION   ,							features=datasets.Features(
               {
                   'predictions': datasets.Sequence(datasets.Value('int32'		)		),
                   'references': datasets.Sequence(datasets.Value('int32'		)		),
               }
               if self.config_name == 'multilabel'
               else {
                   'predictions': datasets.Value('int32'		),
                   'references': datasets.Value('int32'		),
               }		)   ,							reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html']   ,							)



 def       lowerCAmelCase_							(			self	:	int   ,							_UpperCAmelCase	:	Any   ,							_UpperCAmelCase	:	int   ,							_UpperCAmelCase	:	List[str]=None   ,							_UpperCAmelCase	:	Dict=1   ,							_UpperCAmelCase	:	Union[str, Any]="binary"   ,							_UpperCAmelCase	:	List[str]=None		):
       _A        =       fa_score(
           _UpperCAmelCase   ,							_UpperCAmelCase   ,							labels=_UpperCAmelCase   ,							pos_label=_UpperCAmelCase   ,							average=_UpperCAmelCase   ,							sample_weight=_UpperCAmelCase		)
       return {"f1": float(_UpperCAmelCase		) if score.size == 1 else score}

