


import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
       import jax
       import jax.numpy as jnp

       from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor







class        UpperCamelCase__   (	unittest.TestCase   ):

     def __init__(     self       :   List[str]							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Optional[int]=3							,					UpperCamelCase__       :   Tuple=32							,					UpperCamelCase__       :   Optional[Any]=3							,					UpperCamelCase__       :   Optional[int]=10							,					UpperCamelCase__       :   List[str]=[10, 20, 30, 40]							,					UpperCamelCase__       :   Any=[1, 1, 2, 1]							,					UpperCamelCase__       :   int=True							,					UpperCamelCase__       :   List[str]=True							,					UpperCamelCase__       :   str="relu"							,					UpperCamelCase__       :   str=3							,					UpperCamelCase__       :   Any=None							,					):






          '''simple docstring'''






          lowercase_  							=			parent
          lowercase_  							=			batch_size
          lowercase_  							=			image_size
          lowercase_  							=			num_channels
          lowercase_  							=			embeddings_size
          lowercase_  							=			hidden_sizes
          lowercase_  							=			depths
          lowercase_  							=			is_training
          lowercase_  							=			use_labels
          lowercase_  							=			hidden_act
          lowercase_  							=			num_labels
          lowercase_  							=			scope
          lowercase_  							=			len(lowercase_       )

     def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






          '''simple docstring'''






          lowercase_  							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

          lowercase_  							=			self.get_config()

          return config, pixel_values

     def   UpperCAmelCase__       (     self       :   Tuple       ):






          '''simple docstring'''






          return RegNetConfig(
              num_channels=self.num_channels							,					embeddings_size=self.embeddings_size							,					hidden_sizes=self.hidden_sizes							,					depths=self.depths							,					hidden_act=self.hidden_act							,					num_labels=self.num_labels							,					image_size=self.image_size							,					)

     def   UpperCAmelCase__       (     self       :   Any							,					UpperCamelCase__       :   Optional[int]							,					UpperCamelCase__       :   Dict       ):






          '''simple docstring'''






          lowercase_  							=			FlaxRegNetModel(config=lowercase_       )
          lowercase_  							=			model(lowercase_       )

          # Output shape (b, c, h, w)
          self.parent.assertEqual(
              result.last_hidden_state.shape							,					(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)							,					)

     def   UpperCAmelCase__       (     self       :   Tuple							,					UpperCamelCase__       :   Optional[int]							,					UpperCamelCase__       :   List[str]       ):






          '''simple docstring'''






          lowercase_  							=			self.num_labels
          lowercase_  							=			FlaxRegNetForImageClassification(config=lowercase_       )
          lowercase_  							=			model(lowercase_       )
          self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.num_labels)       )







     def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






          '''simple docstring'''






          lowercase_  							=			self.prepare_config_and_inputs()
          lowercase_  							=			config_and_inputs
          lowercase_  							=			{"pixel_values": pixel_values}
          return config, inputs_dict







@require_flax
class        UpperCamelCase__   (	snake_case__							,				unittest.TestCase   ):
     __SCREAMING_SNAKE_CASE       :  Dict						=   (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

     __SCREAMING_SNAKE_CASE       :  List[Any]						=   False
     __SCREAMING_SNAKE_CASE       :  str						=   False
     __SCREAMING_SNAKE_CASE       :  str						=   False

     def   UpperCAmelCase__       (     self       :   str       ):






          '''simple docstring'''






          lowercase_  							=			FlaxRegNetModelTester(self       )
          lowercase_  							=			ConfigTester(self							,					config_class=lowercase_							,					has_text_modality=lowercase_       )

     def   UpperCAmelCase__       (     self       :   int       ):






          '''simple docstring'''






          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()

     def   UpperCAmelCase__       (     self       :   int       ):






          '''simple docstring'''






          return

     def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






          '''simple docstring'''






          lowercase_  							=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase_       )

     def   UpperCAmelCase__       (     self       :   Any       ):






          '''simple docstring'''






          lowercase_  							=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase_       )

     @unittest.skip(reason="""RegNet does not use inputs_embeds"""       )
     def   UpperCAmelCase__       (     self       :   Dict       ):






          '''simple docstring'''






          pass

     @unittest.skip(reason="""RegNet does not support input and output embeddings"""       )
     def   UpperCAmelCase__       (     self       :   List[str]       ):






          '''simple docstring'''






          pass

     def   UpperCAmelCase__       (     self       :   Dict       ):






          '''simple docstring'''






          lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase_  							=			["pixel_values"]
               self.assertListEqual(arg_names[:1]							,					lowercase_       )

     def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






          '''simple docstring'''






          def check_hidden_states_output(UpperCamelCase__       :   str							,					UpperCamelCase__       :   Dict							,					UpperCamelCase__       :   Union[str, Any]       ):
               lowercase_  							=			model_class(lowercase_       )

               lowercase_  							=			model(**self._prepare_for_class(lowercase_							,					lowercase_       )       )

               lowercase_  							=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               lowercase_  							=			self.model_tester.num_stages
               self.assertEqual(len(lowercase_       )							,					expected_num_stages + 1       )

          lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

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

               check_hidden_states_output(lowercase_							,					lowercase_							,					lowercase_       )







     def   UpperCAmelCase__       (     self       :   List[Any]       ):






          '''simple docstring'''






          lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               with self.subTest(model_class.__name__       ):
                    lowercase_  							=			self._prepare_for_class(lowercase_							,					lowercase_       )
                    lowercase_  							=			model_class(lowercase_       )

                    @jax.jit
                    def model_jitted(UpperCamelCase__       :   str							,					**UpperCamelCase__       :   Optional[int]       ):
                         return model(pixel_values=lowercase_							,					**lowercase_       )

                    with self.subTest("""JIT Enabled"""       ):
                         lowercase_  							=			model_jitted(**lowercase_       ).to_tuple()

                    with self.subTest("""JIT Disabled"""       ):
                         with jax.disable_jit():
                              lowercase_  							=			model_jitted(**lowercase_       ).to_tuple()

                    self.assertEqual(len(lowercase_       )							,					len(lowercase_       )       )
                    for jitted_output, output in zip(lowercase_							,					lowercase_       ):
                         self.assertEqual(jitted_output.shape							,					output.shape       )



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







@require_flax
class        UpperCamelCase__   (	unittest.TestCase   ):

     @cached_property
     def   UpperCAmelCase__       (     self       :   Optional[int]       ):






          '''simple docstring'''






          return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040"""       ) if is_vision_available() else None







     @slow
     def   UpperCAmelCase__       (     self       :   Dict       ):






          '''simple docstring'''






          lowercase_  							=			FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040"""       )

          lowercase_  							=			self.default_image_processor
          lowercase_  							=			prepare_img()
          lowercase_  							=			image_processor(images=lowercase_							,					return_tensors="""np"""       )

          lowercase_  							=			model(**lowercase_       )

          # verify the logits
          lowercase_  							=			(1, 1_000)
          self.assertEqual(outputs.logits.shape							,					lowercase_       )

          lowercase_  							=			jnp.array([-0.4_180, -1.5_051, -3.4_836]       )

          self.assertTrue(jnp.allclose(outputs.logits[0, :3]							,					lowercase_							,					atol=1e-4       )       )






from __future__ import annotations

import sys
from collections import deque
from typing import Generic, TypeVar

a					  =     TypeVar('T')







class        UpperCamelCase__   (	Generic[T]   ):
					__SCREAMING_SNAKE_CASE       :  deque[T]  # Cache store of keys
					__SCREAMING_SNAKE_CASE       :  set[T]  # References of the keys in cache
					__SCREAMING_SNAKE_CASE       :  int						=   10  # Maximum capacity of cache

					def __init__(     self       :   str							,					UpperCamelCase__       :   int       ):






										'''simple docstring'''






										lowercase_  							=			deque()
										lowercase_  							=			set()
										if not n:
															lowercase_  							=			sys.maxsize
										elif n < 0:
															raise ValueError("""n should be an integer greater than 0."""       )
										else:
															lowercase_  							=			n

					def   UpperCAmelCase__       (     self       :   Optional[int]							,					UpperCamelCase__       :   T       ):






										'''simple docstring'''






										if x not in self.key_reference:
															if len(self.dq_store       ) == LRUCache._MAX_CAPACITY:
																				lowercase_  							=			self.dq_store.pop()
																				self.key_reference.remove(UpperCamelCase__       )
										else:
															self.dq_store.remove(UpperCamelCase__       )

										self.dq_store.appendleft(UpperCamelCase__       )
										self.key_reference.add(UpperCamelCase__       )

					def   UpperCAmelCase__       (     self       :   List[Any]       ):






										'''simple docstring'''






										for k in self.dq_store:
															print(UpperCamelCase__       )







					def __repr__(     self       :   Optional[Any]       ):






										'''simple docstring'''






										return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store       )}'''


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							a					  =     LRUCache(4)
							lru_cache.refer('A')
							lru_cache.refer(2)
							lru_cache.refer(3)
							lru_cache.refer('A')
							lru_cache.refer(4)
							lru_cache.refer(5)
							lru_cache.display()

							print(lru_cache)
							assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"


