


'''simple docstring'''






from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class  a     :
 def __init__( self      ,				__magic_name__      ,				__magic_name__=3      ,				__magic_name__=32      ,				__magic_name__=3      ,				__magic_name__=10      ,				__magic_name__=[10, 20, 30, 40]      ,				__magic_name__=[1, 1, 2, 1]      ,				__magic_name__=True      ,				__magic_name__=True      ,				__magic_name__="relu"      ,				__magic_name__=3      ,				__magic_name__=None      ,				)					->							int:
      _a			      =							parent
      _a			      =							batch_size
      _a			      =							image_size
      _a			      =							num_channels
      _a			      =							embeddings_size
      _a			      =							hidden_sizes
      _a			      =							depths
      _a			      =							is_training
      _a			      =							use_labels
      _a			      =							hidden_act
      _a			      =							num_labels
      _a			      =							scope
      _a			      =							len(__magic_name__						)
 def 							__UpperCAmelCase		( self						)					->							Dict:
      _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.num_labels						)

      _a			      =							self.get_config()
      return config, pixel_values, labels
 def 							__UpperCAmelCase		( self						)					->							List[Any]:
      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      ,				)
 def 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__      ,				__magic_name__						)					->							Union[str, Any]:
      _a			      =							TFRegNetModel(config=__magic_name__						)
      _a			      =							model(__magic_name__      ,				training=__magic_name__						)
      # expected last hidden states: B, C, H // 32, W // 32
      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      ,				__magic_name__      ,				__magic_name__      ,				__magic_name__						)					->							Optional[int]:
      _a			      =							self.num_labels
      _a			      =							TFRegNetForImageClassification(__magic_name__						)
      _a			      =							model(__magic_name__      ,				labels=__magic_name__      ,				training=__magic_name__						)
      self.parent.assertEqual(result.logits.shape      ,				(self.batch_size, self.num_labels)						)




 def 							__UpperCAmelCase		( self						)					->							Optional[int]:
      _a			      =							self.prepare_config_and_inputs()
      _a      ,   _a      ,   _a			      =							config_and_inputs
      _a			      =							{'pixel_values': pixel_values}
      return config, inputs_dict





@require_tf
class  a     (     _SCREAMING_SNAKE_CASE  ,				_SCREAMING_SNAKE_CASE  ,				unittest.TestCase       ):
 _lowerCAmelCase 					=	(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
 _lowerCAmelCase 					=	(
     {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
     if is_tf_available()
     else {}
 )

 _lowerCAmelCase 					=	False
 _lowerCAmelCase 					=	False
 _lowerCAmelCase 					=	False
 _lowerCAmelCase 					=	False
 _lowerCAmelCase 					=	False
 def 							__UpperCAmelCase		( self						)					->							Tuple:
      _a			      =							TFRegNetModelTester(self						)
      _a			      =							ConfigTester(self      ,				config_class=__magic_name__      ,				has_text_modality=__magic_name__						)
 def 							__UpperCAmelCase		( self						)					->							Tuple:
      return
 @unittest.skip(reason='RegNet does not use inputs_embeds'						)
 def 							__UpperCAmelCase		( self						)					->							Union[str, Any]:
      pass
 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('GPU'						)						) == 0      ,				reason='TF does not support backprop for grouped convolutions on CPU.'      ,				)
 @slow
 def 							__UpperCAmelCase		( self						)					->							int:
      super().test_keras_fit()
 @unittest.skip(reason='RegNet does not support input and output embeddings'						)
 def 							__UpperCAmelCase		( self						)					->							Optional[int]:
      pass
 def 							__UpperCAmelCase		( self						)					->							Any:
      _a      ,   _a			      =							self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
           _a			      =							model_class(__magic_name__						)
           _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]      ,				__magic_name__						)
 def 							__UpperCAmelCase		( self						)					->							List[Any]:
      _a			      =							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__magic_name__						)
 def 							__UpperCAmelCase		( self						)					->							Dict:
      def check_hidden_states_output(__magic_name__      ,				__magic_name__      ,				__magic_name__						):
           _a			      =							model_class(__magic_name__						)
           _a			      =							model(**self._prepare_for_class(__magic_name__      ,				__magic_name__						)      ,				training=__magic_name__						)

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

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

           # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
           self.assertListEqual(
               list(hidden_states[0].shape[-2:]						)      ,				[self.model_tester.image_size // 2, self.model_tester.image_size // 2]      ,				)

      _a      ,   _a			      =							self.model_tester.prepare_config_and_inputs_for_common()
      _a			      =							['basic', 'bottleneck']
      for model_class in self.all_model_classes:
           for layer_type in layers_type:
                _a			      =							layer_type
                _a			      =							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"]
                _a			      =							True

                check_hidden_states_output(__magic_name__      ,				__magic_name__      ,				__magic_name__						)
 def 							__UpperCAmelCase		( self						)					->							Optional[int]:
      _a      ,   _a			      =							self.model_tester.prepare_config_and_inputs_for_common()

      def check_equivalence(__magic_name__      ,				__magic_name__      ,				__magic_name__      ,				__magic_name__={}						):
           _a			      =							model(__magic_name__      ,				return_dict=__magic_name__      ,				**__magic_name__						)
           _a			      =							model(__magic_name__      ,				return_dict=__magic_name__      ,				**__magic_name__						).to_tuple()

           def recursive_check(__magic_name__      ,				__magic_name__						):
                if isinstance(__magic_name__      ,				(List, Tuple)						):
                     for tuple_iterable_value, dict_iterable_value in zip(__magic_name__      ,				__magic_name__						):
                          recursive_check(__magic_name__      ,				__magic_name__						)
                elif tuple_object is None:
                     return
                else:
                     self.assertTrue(
                         all(tf.equal(__magic_name__      ,				__magic_name__						)						)      ,				msg=(
                             'Tuple and dict output are not equal. Difference:'
                             f' {tf.math.reduce_max(tf.abs(tuple_object - dict_object						)						)}'
                         )      ,				)

                recursive_check(__magic_name__      ,				__magic_name__						)

      for model_class in self.all_model_classes:
           _a			      =							model_class(__magic_name__						)

           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__						)
           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__						)
           check_equivalence(__magic_name__      ,				__magic_name__      ,				__magic_name__						)

           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__      ,				return_labels=__magic_name__						)
           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__      ,				return_labels=__magic_name__						)
           check_equivalence(__magic_name__      ,				__magic_name__      ,				__magic_name__						)

           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__						)
           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__						)
           check_equivalence(__magic_name__      ,				__magic_name__      ,				__magic_name__      ,				{'output_hidden_states': True}						)

           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__      ,				return_labels=__magic_name__						)
           _a			      =							self._prepare_for_class(__magic_name__      ,				__magic_name__      ,				return_labels=__magic_name__						)
           check_equivalence(__magic_name__      ,				__magic_name__      ,				__magic_name__      ,				{'output_hidden_states': True}						)
 def 							__UpperCAmelCase		( self						)					->							str:
      _a			      =							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__magic_name__						)




 @slow
 def 							__UpperCAmelCase		( self						)					->							Any:
      for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _a			      =							TFRegNetModel.from_pretrained(__magic_name__						)
           self.assertIsNotNone(__magic_name__						)






def 	_A				()   ->  Optional[Any]:




     '''simple docstring'''



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






@require_tf
@require_vision
class  a     (     unittest.TestCase       ):
 @cached_property
 def 							__UpperCAmelCase		( self						)					->							List[str]:
      return (
          AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
          if is_vision_available()
          else None
      )




 @slow
 def 							__UpperCAmelCase		( self						)					->							Any:
      _a			      =							TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

      _a			      =							self.default_image_processor
      _a			      =							prepare_img()
      _a			      =							image_processor(images=__magic_name__      ,				return_tensors='tf'						)

      # forward pass
      _a			      =							model(**__magic_name__      ,				training=__magic_name__						)

      # verify the logits
      _a			      =							tf.TensorShape((1, 10_00)						)
      self.assertEqual(outputs.logits.shape      ,				__magic_name__						)

      _a			      =							tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]						)

      tf.debugging.assert_near(outputs.logits[0, :3]      ,				__magic_name__      ,				atol=1e-4						)





'''simple docstring'''






import datasets


a_					:    List[Any]          =    "\\n@InProceedings{conneau2018xnli,\n  author = \"Conneau, Alexis\n                 and Rinott, Ruty\n                 and Lample, Guillaume\n                 and Williams, Adina\n                 and Bowman, Samuel R.\n                 and Schwenk, Holger\n                 and Stoyanov, Veselin\",\n  title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",\n  booktitle = \"Proceedings of the 2018 Conference on Empirical Methods\n               in Natural Language Processing\",\n  year = \"2018\",\n  publisher = \"Association for Computational Linguistics\",\n  location = \"Brussels, Belgium\",\n}\n"

a_					:    Optional[Any]          =    "\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n"

a_					:    Optional[Any]          =    "\nComputes XNLI score which is just simple accuracy.\nArgs:\n    predictions: Predicted labels.\n    references: Ground truth labels.\nReturns:\n    'accuracy': accuracy\nExamples:\n\n    >>> predictions = [0, 1]\n    >>> references = [0, 1]\n    >>> xnli_metric = datasets.load_metric(\"xnli\")\n    >>> results = xnli_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n"






def 	_A				(lowerCAmelCase__  :List[Any]				,						lowerCAmelCase__  :Tuple		)   ->  Dict:




     '''simple docstring'''



     return (preds == labels).mean()






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,				_KWARGS_DESCRIPTION       )
class  a     (     datasets.Metric       ):
 def 							__UpperCAmelCase		( self						)					->							Dict:
      return datasets.MetricInfo(
          description=_DESCRIPTION      ,				citation=_CITATION      ,				inputs_description=_KWARGS_DESCRIPTION      ,				features=datasets.Features(
              {
                  'predictions': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32'						),
                  'references': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32'						),
              }						)      ,				codebase_urls=[]      ,				reference_urls=[]      ,				format='numpy'      ,				)




 def 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__						)					->							Dict:
      return {"accuracy": simple_accuracy(__magic_name__      ,				__magic_name__						)}

