





'''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 			_lowerCAmelCase		:






     """simple docstring"""






     def __init__(   self							:			Optional[int]   ,       __snake_case							:			Union[str, Any]   ,       __snake_case							:			int = 13   ,       __snake_case							:			int = 64   ,       __snake_case							:			int = 2   ,       __snake_case							:			int = 3   ,       __snake_case							:			int = 3   ,       __snake_case							:			bool = True   ,       __snake_case							:			bool = True   ,       __snake_case							:			int = 1_28   ,       __snake_case							:			int=[16, 32, 64, 1_28]   ,       __snake_case							:			int = 7   ,       __snake_case							:			int = 4   ,       __snake_case							:			int = 37   ,       __snake_case							:			str = "gelu"   ,       __snake_case							:			float = 0.1   ,       __snake_case							:			float = 0.1   ,       __snake_case							:			int = 10   ,       __snake_case							:			float = 0.02   ,       __snake_case							:			int = 2   ,       __snake_case							:			int = 1   ,       __snake_case							:			int = 1_28   ,       __snake_case							:			List[int] = [2, 2, 2, 2]   ,       __snake_case							:			int = 2   ,       __snake_case							:			int = 2   ,       )->	List[Any]:
        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      lowerCAmelCase			(   self							:			Tuple						)->	Optional[int]:
        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      lowerCAmelCase			(   self							:			Tuple						)->	Optional[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=__snake_case   ,       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							:			Tuple   ,       __snake_case							:			Optional[Any]   ,       __snake_case							:			Optional[Any]   ,       __snake_case							:			List[Any]						)->	Optional[int]:
        snake_case 						=   TFEfficientFormerModel(config=__snake_case						)
        snake_case 						=   model(__snake_case   ,       training=__snake_case						)
        self.parent.assertEqual(result.last_hidden_state.shape   ,       (self.batch_size, self.seq_length, self.hidden_size)						)



     def      lowerCAmelCase			(   self							:			int   ,       __snake_case							:			Dict   ,       __snake_case							:			int   ,       __snake_case							:			Optional[int]						)->	Tuple:
        snake_case 						=   self.type_sequence_label_size
        snake_case 						=   TFEfficientFormerForImageClassification(__snake_case						)
        snake_case 						=   model(__snake_case   ,       labels=__snake_case   ,       training=__snake_case						)
        self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.type_sequence_label_size)						)

        # test greyscale images
        snake_case 						=   1
        snake_case 						=   TFEfficientFormerForImageClassification(__snake_case						)

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



     def      lowerCAmelCase			(   self							:			Union[str, Any]						)->	Optional[int]:
        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 			_lowerCAmelCase		(			A__							,     A__							,     unittest.TestCase	):






     """simple docstring"""






     snake_case_						      =   (
         (
             TFEfficientFormerModel,
             TFEfficientFormerForImageClassificationWithTeacher,
             TFEfficientFormerForImageClassification,
         )
         if is_tf_available()
         else ()
     )
     snake_case_						      =   (
         {
             "feature-extraction": TFEfficientFormerModel,
             "image-classification": (
                 TFEfficientFormerForImageClassification,
                 TFEfficientFormerForImageClassificationWithTeacher,
             ),
         }
         if is_tf_available()
         else {}
     )

     snake_case_						      =   False

     snake_case_						      =   False
     snake_case_						      =   False
     snake_case_						      =   False
     snake_case_						      =   False



     def      lowerCAmelCase			(   self							:			Optional[Any]						)->	str:
        snake_case 						=   TFEfficientFormerModelTester(self						)
        snake_case 						=   ConfigTester(
            self   ,       config_class=__snake_case   ,       has_text_modality=__snake_case   ,       hidden_size=37						)



     def      lowerCAmelCase			(   self							:			List[str]						)->	List[str]:
        self.config_tester.run_common_tests()



     @unittest.skip(reason="""EfficientFormer does not use inputs_embeds"""						)
     def      lowerCAmelCase			(   self							:			Optional[Any]						)->	List[str]:
        pass



     @unittest.skip(reason="""EfficientFormer does not support input and output embeddings"""						)
     def      lowerCAmelCase			(   self							:			int						)->	Dict:
        pass



     def      lowerCAmelCase			(   self							:			List[str]						)->	Dict:
        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(__snake_case						)
           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]   ,       __snake_case						)



     def      lowerCAmelCase			(   self							:			Union[str, Any]						)->	Optional[int]:
        def check_hidden_states_output(__snake_case							:			int   ,       __snake_case							:			str   ,       __snake_case							:			Any						):
           snake_case 						=   model_class(__snake_case						)

           snake_case 						=   model(**self._prepare_for_class(__snake_case   ,       __snake_case						)   ,       training=__snake_case						)
           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(__snake_case						)   ,       __snake_case						)

           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(__snake_case   ,       (list, tuple)						)
              self.assertEqual(len(__snake_case						)   ,       __snake_case						)
              snake_case 						=   getattr(self.model_tester   ,       """seq_length"""   ,       __snake_case						)
              snake_case 						=   getattr(self.model_tester   ,       """decoder_seq_length"""   ,       __snake_case						)

              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(__snake_case   ,       __snake_case   ,       __snake_case						)

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

           check_hidden_states_output(__snake_case   ,       __snake_case   ,       __snake_case						)



     def      lowerCAmelCase			(   self							:			str   ,       __snake_case							:			List[str]   ,       __snake_case							:			Any   ,       __snake_case							:			Dict=False						)->	Optional[Any]:
        snake_case 						=   super()._prepare_for_class(__snake_case   ,       __snake_case   ,       return_labels=__snake_case						)

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

        return inputs_dict



     def      lowerCAmelCase			(   self							:			Tuple						)->	str:
        snake_case 						=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__snake_case						)



     @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet"""						)
     def      lowerCAmelCase			(   self							:			Optional[Any]						)->	List[str]:
        snake_case 						=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case						)



     def      lowerCAmelCase			(   self							:			Tuple						)->	Optional[int]:
        snake_case 						=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__snake_case						)



     @slow
     def      lowerCAmelCase			(   self							:			str						)->	Dict:
        for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case 						=   TFEfficientFormerModel.from_pretrained(__snake_case						)
           self.assertIsNotNone(__snake_case						)



     def      lowerCAmelCase			(   self							:			List[Any]						)->	Optional[int]:
        snake_case						,    snake_case 						=   self.model_tester.prepare_config_and_inputs_for_common()
        snake_case 						=   True

        snake_case 						=   getattr(self.model_tester   ,       """seq_length"""   ,       __snake_case						)
        snake_case 						=   getattr(self.model_tester   ,       """encoder_seq_length"""   ,       __snake_case						)
        snake_case 						=   getattr(self.model_tester   ,       """key_length"""   ,       __snake_case						)
        snake_case 						=   getattr(self.model_tester   ,       """chunk_length"""   ,       __snake_case						)

        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(__snake_case						)

           snake_case 						=   model(**self._prepare_for_class(__snake_case   ,       __snake_case						)   ,       training=__snake_case						)
           snake_case 						=   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__snake_case						)   ,       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(__snake_case						)
           snake_case 						=   model(**self._prepare_for_class(__snake_case   ,       __snake_case						)   ,       training=__snake_case						)

           snake_case 						=   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
           self.assertEqual(len(__snake_case						)   ,       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							:			Tuple						)->	str:
        # 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(__snake_case						)
           # 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=__snake_case						)
               for key, val in model.input_signature.items()
               if key in model.dummy_inputs
           }
           snake_case 						=   model(__snake_case						)
           self.assertTrue(outputs_dict is not None						)





def 	__lowerCamelCase			(      )		->  str:
   snake_case 						=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
   return image


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






     """simple docstring"""






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



     @slow
     def      lowerCAmelCase			(   self							:			Any						)->	int:
        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=__snake_case   ,       return_tensors="""tf"""						)
        # forward pass
        snake_case 						=   model(**__snake_case   ,       training=__snake_case						)
        # verify the logits
        snake_case 						=   tf.TensorShape((1, 10_00)						)
        self.assertEqual(outputs.logits.shape   ,       __snake_case						)
        snake_case 						=   tf.constant([-0.05_55, 0.48_25, -0.08_52]						)
        self.assertTrue(np.allclose(outputs.logits[0, :3]   ,       __snake_case   ,       atol=1e-4						)						)



     @slow
     def      lowerCAmelCase			(   self							:			Tuple						)->	Optional[Any]:
        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=__snake_case   ,       return_tensors="""tf"""						)
        # forward pass
        snake_case 						=   model(**__snake_case   ,       training=__snake_case						)
        # verify the logits
        snake_case 						=   tf.TensorShape((1, 10_00)						)
        self.assertEqual(outputs.logits.shape   ,       __snake_case						)
        snake_case 						=   tf.constant([-0.13_12, 0.43_53, -1.04_99]						)
        self.assertTrue(np.allclose(outputs.logits[0, :3]   ,       __snake_case   ,       atol=1e-4						)						)








'''simple docstring'''




from __future__ import annotations





def 	__lowerCamelCase			(      __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float		)		->  float:
   if days_between_payments <= 0:
      raise ValueError("""days_between_payments must be > 0"""		)
   if daily_interest_rate < 0:
      raise ValueError("""daily_interest_rate must be >= 0"""		)
   if principal <= 0:
      raise ValueError("""principal must be > 0"""		)
   return principal * daily_interest_rate * days_between_payments





def 	__lowerCamelCase			(      __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float      ,    )		->  float:
   if number_of_compounding_periods <= 0:
      raise ValueError("""number_of_compounding_periods must be > 0"""		)
   if nominal_annual_interest_rate_percentage < 0:
      raise ValueError("""nominal_annual_interest_rate_percentage must be >= 0"""		)
   if principal <= 0:
      raise ValueError("""principal must be > 0"""		)

   return principal * (
       (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
       - 1
   )





def 	__lowerCamelCase			(      __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float      ,    __lowerCAmelCase       :							float      ,    )		->  float:
   if number_of_years <= 0:
      raise ValueError("""number_of_years must be > 0"""		)
   if nominal_annual_percentage_rate < 0:
      raise ValueError("""nominal_annual_percentage_rate must be >= 0"""		)
   if principal <= 0:
      raise ValueError("""principal must be > 0"""		)

   return compound_interest(
       __lowerCAmelCase      ,    nominal_annual_percentage_rate / 3_65      ,    number_of_years * 3_65		)


if __name__ == "__main__":
 import doctest

 doctest.testmod()

