


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



  """simple docstring"""



  def __init__( self			:  Optional[Any]				,				lowerCamelCase__			:  Any				,				lowerCamelCase__			:  Optional[int]=3				,				lowerCamelCase__			:  Dict=32				,				lowerCamelCase__			:  int=3				,				lowerCamelCase__			:  int=10				,				lowerCamelCase__			:  Optional[Any]=[10, 20, 30, 40]				,				lowerCamelCase__			:  Any=[1, 1, 2, 1]				,				lowerCamelCase__			:  List[Any]=True				,				lowerCamelCase__			:  Optional[Any]=True				,				lowerCamelCase__			:  Tuple="relu"				,				lowerCamelCase__			:  List[Any]=3				,				lowerCamelCase__			:  List[str]=None				,				):
        a__	:  List[str]     =   parent
        a__	:  Tuple     =   batch_size
        a__	:  int     =   image_size
        a__	:  List[str]     =   num_channels
        a__	:  List[Any]     =   embeddings_size
        a__	:  Optional[Any]     =   hidden_sizes
        a__	:  Union[str, Any]     =   depths
        a__	:  Tuple     =   is_training
        a__	:  Any     =   use_labels
        a__	:  List[Any]     =   hidden_act
        a__	:  Dict     =   num_labels
        a__	:  Union[str, Any]     =   scope
        a__	:  Tuple     =   len(lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Any       ):
        a__	:  Optional[int]     =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

        a__	:  Optional[Any]     =   None
        if self.use_labels:
              a__	:  int     =   ids_tensor([self.batch_size]				,				self.num_labels       )

        a__	:  Optional[int]     =   self.get_config()
        return config, pixel_values, labels

  def    _UpperCamelCase( self			:  Dict       ):
        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			:  Tuple				,				lowerCamelCase__			:  Optional[int]				,				lowerCamelCase__			:  int				,				lowerCamelCase__			:  Optional[Any]       ):
        a__	:  Optional[int]     =   TFRegNetModel(config=lowerCamelCase__       )
        a__	:  List[str]     =   model(lowerCamelCase__				,				training=lowerCamelCase__       )
        # 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			:  str				,				lowerCamelCase__			:  Dict				,				lowerCamelCase__			:  Tuple				,				lowerCamelCase__			:  Any       ):
        a__	:  List[Any]     =   self.num_labels
        a__	:  List[Any]     =   TFRegNetForImageClassification(lowerCamelCase__       )
        a__	:  Dict     =   model(lowerCamelCase__				,				labels=lowerCamelCase__				,				training=lowerCamelCase__       )
        self.parent.assertEqual(result.logits.shape				,				(self.batch_size, self.num_labels)       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  Union[str, Any]     =   self.prepare_config_and_inputs()
        a__,	a__,	a__	:  Union[str, Any]     =   config_and_inputs
        a__	:  Optional[Any]     =   {"pixel_values": pixel_values}
        return config, inputs_dict




@require_tf
class A__     ( A__				,		A__				,		unittest.TestCase  ):



  """simple docstring"""



  _lowercase									=		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
  _lowercase									=		(
      {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
      if is_tf_available()
      else {}
  )

  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False
  _lowercase									=		False

  def    _UpperCamelCase( self			:  List[str]       ):
        a__	:  int     =   TFRegNetModelTester(self       )
        a__	:  Optional[Any]     =   ConfigTester(self				,				config_class=lowerCamelCase__				,				has_text_modality=lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Union[str, Any]       ):
        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			:  List[Any]       ):
        super().test_keras_fit()

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

  def    _UpperCamelCase( self			:  Tuple       ):
        a__,	a__	:  str     =   self.model_tester.prepare_config_and_inputs_for_common()

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

              a__	:  List[str]     =   ["pixel_values"]
              self.assertListEqual(arg_names[:1]				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__	:  List[str]     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase__       )

  def    _UpperCamelCase( self			:  List[str]       ):
        def check_hidden_states_output(lowerCamelCase__			:  Union[str, Any]				,				lowerCamelCase__			:  Tuple				,				lowerCamelCase__			:  Optional[int]       ):
              a__	:  List[str]     =   model_class(lowerCamelCase__       )
              a__	:  Optional[Any]     =   model(**self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )				,				training=lowerCamelCase__       )

              a__	:  Dict     =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              a__	:  Optional[Any]     =   self.model_tester.num_stages
              self.assertEqual(len(lowerCamelCase__       )				,				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__	:  Tuple     =   self.model_tester.prepare_config_and_inputs_for_common()
        a__	:  str     =   ["basic", "bottleneck"]
        for model_class in self.all_model_classes:
              for layer_type in layers_type:
                    a__	:  Tuple     =   layer_type
                    a__	:  List[Any]     =   True
                    check_hidden_states_output(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__       )

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    a__	:  Tuple     =   True

                    check_hidden_states_output(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__       )

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        a__,	a__	:  Any     =   self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(lowerCamelCase__			:  List[str]				,				lowerCamelCase__			:  int				,				lowerCamelCase__			:  Union[str, Any]				,				lowerCamelCase__			:  Dict={}       ):
              a__	:  Optional[int]     =   model(lowerCamelCase__				,				return_dict=lowerCamelCase__				,				**lowerCamelCase__       )
              a__	:  List[Any]     =   model(lowerCamelCase__				,				return_dict=lowerCamelCase__				,				**lowerCamelCase__       ).to_tuple()

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

                    recursive_check(lowerCamelCase__				,				lowerCamelCase__       )

        for model_class in self.all_model_classes:
              a__	:  Any     =   model_class(lowerCamelCase__       )

              a__	:  Any     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )
              a__	:  List[Any]     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )
              check_equivalence(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__       )

              a__	:  Optional[Any]     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__				,				return_labels=lowerCamelCase__       )
              a__	:  Optional[Any]     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__				,				return_labels=lowerCamelCase__       )
              check_equivalence(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__       )

              a__	:  Any     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )
              a__	:  Any     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__       )
              check_equivalence(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__				,				{"output_hidden_states": True}       )

              a__	:  Dict     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__				,				return_labels=lowerCamelCase__       )
              a__	:  Optional[int]     =   self._prepare_for_class(lowerCamelCase__				,				lowerCamelCase__				,				return_labels=lowerCamelCase__       )
              check_equivalence(lowerCamelCase__				,				lowerCamelCase__				,				lowerCamelCase__				,				{"output_hidden_states": True}       )

  def    _UpperCamelCase( self			:  int       ):
        a__	:  Tuple     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__       )

  @slow
  def    _UpperCamelCase( self			:  str       ):
        for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              a__	:  Optional[Any]     =   TFRegNetModel.from_pretrained(lowerCamelCase__       )
              self.assertIsNotNone(lowerCamelCase__       )




def UpperCamelCase_				(				)	->   int:
      a__	:  Optional[Any]     =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
      return image



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



  """simple docstring"""



  @cached_property
  def    _UpperCamelCase( self			:  Union[str, Any]       ):
        return (
            AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
            if is_vision_available()
            else None
        )

  @slow
  def    _UpperCamelCase( self			:  Any       ):
        a__	:  Optional[Any]     =   TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

        a__	:  Tuple     =   self.default_image_processor
        a__	:  Union[str, Any]     =   prepare_img()
        a__	:  Union[str, Any]     =   image_processor(images=lowerCamelCase__				,				return_tensors="tf"       )

        # forward pass
        a__	:  Optional[int]     =   model(**lowerCamelCase__				,				training=lowerCamelCase__       )

        # verify the logits
        a__	:  str     =   tf.TensorShape((1, 1_000)       )
        self.assertEqual(outputs.logits.shape				,				lowerCamelCase__       )

        a__	:  int     =   tf.constant([-0.4180, -1.5051, -3.4836]       )

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



"""simple docstring"""




import unittest

from datasets import load_dataset

from transformers import BloomTokenizerFast
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class 			snake_case  (				__lowercase							,      unittest.TestCase ):
							UpperCAmelCase__      =   None
							UpperCAmelCase__      =   BloomTokenizerFast
							UpperCAmelCase__      =   BloomTokenizerFast
							UpperCAmelCase__      =   True
							UpperCAmelCase__      =   False
							UpperCAmelCase__      =   '''tokenizer_file'''
							UpperCAmelCase__      =   {'''bos_token''': '''<s>''', '''eos_token''': '''</s>''', '''unk_token''': '''<unk>''', '''pad_token''': '''<pad>'''}

							def _lowercase       (self     ):

									"""simple docstring"""







									super().setUp()
									SCREAMING_SNAKE_CASE_    			=			BloomTokenizerFast.from_pretrained('''bigscience/tokenizer'''     )
									tokenizer.save_pretrained(self.tmpdirname     )

							def _lowercase       (self							,							**SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									kwargs.update(self.special_tokens_map     )
									return BloomTokenizerFast.from_pretrained(self.tmpdirname							,							**SCREAMING_SNAKE_CASE_     )

							def _lowercase       (self     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			self.get_rust_tokenizer()

									SCREAMING_SNAKE_CASE_    			=			['''The quick brown fox</s>''', '''jumps over the lazy dog</s>''']
									SCREAMING_SNAKE_CASE_    			=			[[21_75, 2_37_14, 7_31_73, 14_42_52, 2], [77, 13_26_19, 34_78, 3_68, 10_95_86, 3_54_33, 2]]

									SCREAMING_SNAKE_CASE_    			=			tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE_     )['''input_ids''']
									self.assertListEqual(SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     )

									SCREAMING_SNAKE_CASE_    			=			tokenizer.batch_decode(SCREAMING_SNAKE_CASE_     )
									self.assertListEqual(SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     )

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_=6     ):

									"""simple docstring"""







									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
											with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})'     ):
													SCREAMING_SNAKE_CASE_    			=			self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_							,							**SCREAMING_SNAKE_CASE_     )
													# tokenizer_r.pad_token = None # Hotfixing padding = None
													# Simple input
													SCREAMING_SNAKE_CASE_    			=			'''This is a simple input'''
													SCREAMING_SNAKE_CASE_    			=			['''This is a simple input 1''', '''This is a simple input 2''']
													SCREAMING_SNAKE_CASE_    			=			('''This is a simple input''', '''This is a pair''')
													SCREAMING_SNAKE_CASE_    			=			[
													    ('''This is a simple input 1''', '''This is a simple input 2'''),
													    ('''This is a simple pair 1''', '''This is a simple pair 2'''),
													]

													# Simple input tests
													try:
															tokenizer_r.encode(SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_     )
															tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_     )

															tokenizer_r.batch_encode_plus(SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_     )
															tokenizer_r.encode(SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_     )
															tokenizer_r.batch_encode_plus(SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_     )
													except ValueError:
															self.fail('''Bloom Tokenizer should be able to deal with padding'''     )

													SCREAMING_SNAKE_CASE_    			=			None  # Hotfixing padding = None
													self.assertRaises(SCREAMING_SNAKE_CASE_							,							tokenizer_r.encode							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''     )

													# Simple input
													self.assertRaises(SCREAMING_SNAKE_CASE_							,							tokenizer_r.encode_plus							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''     )

													# Simple input
													self.assertRaises(
													    SCREAMING_SNAKE_CASE_							,							tokenizer_r.batch_encode_plus							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''							,							)

													# Pair input
													self.assertRaises(SCREAMING_SNAKE_CASE_							,							tokenizer_r.encode							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''     )

													# Pair input
													self.assertRaises(SCREAMING_SNAKE_CASE_							,							tokenizer_r.encode_plus							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''     )

													# Pair input
													self.assertRaises(
													    SCREAMING_SNAKE_CASE_							,							tokenizer_r.batch_encode_plus							,							SCREAMING_SNAKE_CASE_							,							max_length=SCREAMING_SNAKE_CASE_							,							padding='''max_length'''							,							)

							def _lowercase       (self     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			self.get_rust_tokenizer()
									SCREAMING_SNAKE_CASE_    			=			load_dataset('''xnli'''							,							'''all_languages'''							,							split='''test'''							,							streaming=SCREAMING_SNAKE_CASE_     )

									SCREAMING_SNAKE_CASE_    			=			next(iter(SCREAMING_SNAKE_CASE_     )     )['''premise''']  # pick up one data
									SCREAMING_SNAKE_CASE_    			=			list(sample_data.values()     )

									SCREAMING_SNAKE_CASE_    			=			list(map(tokenizer.encode							,							SCREAMING_SNAKE_CASE_     )     )
									SCREAMING_SNAKE_CASE_    			=			[tokenizer.decode(SCREAMING_SNAKE_CASE_							,							clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_     ) for x in output_tokens]
									self.assertListEqual(SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     )







							def _lowercase       (self     ):

									"""simple docstring"""







									self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map     )							,							1     )
									self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values()     )[0]     )							,							1     )