






"""simple docstring"""

# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
			import tensorflow as tf

class     A_				(   TensorFormatter[Mapping, '''tf.Tensor''', Mapping]	):







				def __init__(				self				:    Tuple    ,     __lowerCamelCase				:    Dict=None    ,     **__lowerCamelCase				:    Union[str, Any]						)					->       int:
										super().__init__(features=__lowerCamelCase						)
										__magic_name__      =  tf_tensor_kwargs
										import tensorflow as tf  # noqa: import tf at initialization







				def      _snake_case       (				self				:    Any    ,     __lowerCamelCase				:    Tuple						)					->       List[Any]:
										import tensorflow as tf

										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						) and column:
																if all(
																    isinstance(__lowerCamelCase    ,     tf.Tensor						) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column						):
																						return tf.stack(__lowerCamelCase						)
																elif all(
																    isinstance(__lowerCamelCase    ,     (tf.Tensor, tf.RaggedTensor)						) and x.ndim == 1 and x.dtype == column[0].dtype
																    for x in column						):
																						# only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
																						return tf.ragged.stack(__lowerCamelCase						)

										return column







				def      _snake_case       (				self				:    Union[str, Any]    ,     __lowerCamelCase				:    int						)					->       Any:
										import tensorflow as tf

										if value is None:
																return value

										__magic_name__      =  {}

										if isinstance(__lowerCamelCase    ,     (np.number, np.ndarray)						) and np.issubdtype(value.dtype    ,     np.integer						):
																__magic_name__      =  {"dtype": tf.intaa}
										elif isinstance(__lowerCamelCase    ,     (np.number, np.ndarray)						) and np.issubdtype(value.dtype    ,     np.floating						):
																__magic_name__      =  {"dtype": tf.floataa}
										elif config.PIL_AVAILABLE and "PIL" in sys.modules:
																import PIL.Image

																if isinstance(__lowerCamelCase    ,     PIL.Image.Image						):
																						__magic_name__      =  np.asarray(__lowerCamelCase						)

										return tf.convert_to_tensor(__lowerCamelCase    ,     **{**default_dtype, **self.tf_tensor_kwargs}						)







				def      _snake_case       (				self				:    Tuple    ,     __lowerCamelCase				:    Optional[Any]						)					->       str:
										import tensorflow as tf

										# support for torch, tf, jax etc.
										if config.TORCH_AVAILABLE and "torch" in sys.modules:
																import torch

																if isinstance(__lowerCamelCase    ,     torch.Tensor						):
																						return self._tensorize(data_struct.detach().cpu().numpy()[()]						)
										if hasattr(__lowerCamelCase    ,     "__array__"						) and not isinstance(__lowerCamelCase    ,     tf.Tensor						):
																__magic_name__      =  data_struct.__array__()
										# support for nested types like struct of list of struct
										if isinstance(__lowerCamelCase    ,     np.ndarray						):
																if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
																						return self._consolidate([self.recursive_tensorize(__lowerCamelCase						) for substruct in data_struct]						)
										elif isinstance(__lowerCamelCase    ,     (list, tuple)						):
																return self._consolidate([self.recursive_tensorize(__lowerCamelCase						) for substruct in data_struct]						)
										return self._tensorize(__lowerCamelCase						)







				def      _snake_case       (				self				:    Dict    ,     __lowerCamelCase				:    dict						)					->       str:
										return map_nested(self._recursive_tensorize    ,     __lowerCamelCase    ,     map_list=__lowerCamelCase						)







				def      _snake_case       (				self				:    Tuple    ,     __lowerCamelCase				:    pa.Table						)					->       Mapping:
										__magic_name__      =  self.numpy_arrow_extractor().extract_row(__lowerCamelCase						)
										__magic_name__      =  self.python_features_decoder.decode_row(__lowerCamelCase						)
										return self.recursive_tensorize(__lowerCamelCase						)







				def      _snake_case       (				self				:    Dict    ,     __lowerCamelCase				:    pa.Table						)					->       "tf.Tensor":
										__magic_name__      =  self.numpy_arrow_extractor().extract_column(__lowerCamelCase						)
										__magic_name__      =  self.python_features_decoder.decode_column(__lowerCamelCase    ,     pa_table.column_names[0]						)
										__magic_name__      =  self.recursive_tensorize(__lowerCamelCase						)
										__magic_name__      =  self._consolidate(__lowerCamelCase						)
										return column







				def      _snake_case       (				self				:    Any    ,     __lowerCamelCase				:    pa.Table						)					->       Mapping:
										__magic_name__      =  self.numpy_arrow_extractor().extract_batch(__lowerCamelCase						)
										__magic_name__      =  self.python_features_decoder.decode_batch(__lowerCamelCase						)
										__magic_name__      =  self.recursive_tensorize(__lowerCamelCase						)
										for column_name in batch:
																__magic_name__      =  self._consolidate(batch[column_name]						)
										return batch











"""simple docstring"""

from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
			from PIL import Image

			from transformers import ConvNextImageProcessor

class     A_				:







				def __init__(				self				:    Optional[int]    ,     __lowerCamelCase				:    Tuple    ,     __lowerCamelCase				:    int=1_3    ,     __lowerCamelCase				:    Any=3_2    ,     __lowerCamelCase				:    Dict=3    ,     __lowerCamelCase				:    List[Any]=4    ,     __lowerCamelCase				:    Union[str, Any]=[1_0, 2_0, 3_0, 4_0]    ,     __lowerCamelCase				:    int=[2, 2, 3, 2]    ,     __lowerCamelCase				:    str=True    ,     __lowerCamelCase				:    List[str]=True    ,     __lowerCamelCase				:    List[Any]=3_7    ,     __lowerCamelCase				:    Optional[Any]="gelu"    ,     __lowerCamelCase				:    str=1_0    ,     __lowerCamelCase				:    int=0.02    ,     __lowerCamelCase				:    Optional[int]=3    ,     __lowerCamelCase				:    Any=None    ,     )					->       List[Any]:
										__magic_name__      =  parent
										__magic_name__      =  batch_size
										__magic_name__      =  image_size
										__magic_name__      =  num_channels
										__magic_name__      =  num_stages
										__magic_name__      =  hidden_sizes
										__magic_name__      =  depths
										__magic_name__      =  is_training
										__magic_name__      =  use_labels
										__magic_name__      =  intermediate_size
										__magic_name__      =  hidden_act
										__magic_name__      =  type_sequence_label_size
										__magic_name__      =  initializer_range
										__magic_name__      =  scope







				def      _snake_case       (				self				:    Optional[Any]						)					->       int:
										__magic_name__      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

										__magic_name__      =  self.get_config()

										return config, pixel_values, labels







				def      _snake_case       (				self				:    Optional[int]						)					->       Union[str, Any]:
										return ConvNextConfig(
										    num_channels=self.num_channels    ,     hidden_sizes=self.hidden_sizes    ,     depths=self.depths    ,     num_stages=self.num_stages    ,     hidden_act=self.hidden_act    ,     is_decoder=__lowerCamelCase    ,     initializer_range=self.initializer_range    ,     )







				def      _snake_case       (				self				:    List[Any]    ,     __lowerCamelCase				:    List[str]    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Optional[Any]						)					->       List[str]:
										__magic_name__      =  TFConvNextModel(config=__lowerCamelCase						)
										__magic_name__      =  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 // 3_2, self.image_size // 3_2)    ,     )







				def      _snake_case       (				self				:    List[Any]    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Tuple    ,     __lowerCamelCase				:    List[str]						)					->       int:
										__magic_name__      =  self.type_sequence_label_size
										__magic_name__      =  TFConvNextForImageClassification(__lowerCamelCase						)
										__magic_name__      =  model(__lowerCamelCase    ,     labels=__lowerCamelCase    ,     training=__lowerCamelCase						)
										self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.type_sequence_label_size)						)







				def      _snake_case       (				self				:    List[str]						)					->       str:
										__magic_name__      =  self.prepare_config_and_inputs()
										__magic_name__   ,     __magic_name__   ,     __magic_name__      =  config_and_inputs
										__magic_name__      =  {"pixel_values": pixel_values}
										return config, inputs_dict





@require_tf
class     A_				(   snake_case_       ,				snake_case_       ,				unittest.TestCase	):
				UpperCAmelCase__										=					(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
				UpperCAmelCase__										=					(
				    {'''feature-extraction''': TFConvNextModel, '''image-classification''': TFConvNextForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False
				UpperCAmelCase__										=					False







				def      _snake_case       (				self				:    str						)					->       str:
										__magic_name__      =  TFConvNextModelTester(self						)
										__magic_name__      =  ConfigTester(
										    self    ,     config_class=__lowerCamelCase    ,     has_text_modality=__lowerCamelCase    ,     hidden_size=3_7    ,     )







				@unittest.skip(reason="ConvNext does not use inputs_embeds"						)
				def      _snake_case       (				self				:    Dict						)					->       Dict:
										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      _snake_case       (				self				:    List[str]						)					->       Tuple:
										super().test_keras_fit()







				@unittest.skip(reason="ConvNext does not support input and output embeddings"						)
				def      _snake_case       (				self				:    str						)					->       Tuple:
										pass







				def      _snake_case       (				self				:    Union[str, Any]						)					->       Optional[int]:
										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

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

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







				def      _snake_case       (				self				:    Dict						)					->       Optional[int]:
										__magic_name__      =  self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__lowerCamelCase						)







				@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."    ,     )
				def      _snake_case       (				self				:    Optional[int]						)					->       Tuple:
										super().test_dataset_conversion()







				def      _snake_case       (				self				:    int						)					->       List[str]:
										def check_hidden_states_output(__lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Dict    ,     __lowerCamelCase				:    List[str]						):
																__magic_name__      =  model_class(__lowerCamelCase						)

																__magic_name__      =  model(**self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)						)
																__magic_name__      =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

																# ConvNext'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 // 4, self.model_tester.image_size // 4]    ,     )

										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

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

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

																check_hidden_states_output(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    List[str]						)					->       Dict:
										__magic_name__   ,     __magic_name__      =  self.model_tester.prepare_config_and_inputs_for_common()

										def check_equivalence(__lowerCamelCase				:    Dict    ,     __lowerCamelCase				:    Any    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Any={}						):
																__magic_name__      =  model(__lowerCamelCase    ,     return_dict=__lowerCamelCase    ,     **__lowerCamelCase						)
																__magic_name__      =  model(__lowerCamelCase    ,     return_dict=__lowerCamelCase    ,     **__lowerCamelCase						).to_tuple()

																def recursive_check(__lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    Union[str, 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:
																__magic_name__      =  model_class(__lowerCamelCase						)

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

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

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     {"output_hidden_states": True}						)

																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																__magic_name__      =  self._prepare_for_class(__lowerCamelCase    ,     __lowerCamelCase    ,     return_labels=__lowerCamelCase						)
																check_equivalence(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     {"output_hidden_states": True}						)







				def      _snake_case       (				self				:    Union[str, Any]						)					->       Dict:
										__magic_name__      =  self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase						)







				@slow
				def      _snake_case       (				self				:    List[str]						)					->       Tuple:
										__magic_name__      =  TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"						)
										self.assertIsNotNone(__lowerCamelCase						)






def _lowerCAmelCase						(	):

						'''simple docstring'''






						__magic_name__      =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
						return image


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







				@cached_property
				def      _snake_case       (				self				:    Tuple						)					->       Any:
										return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"						) if is_vision_available() else None







				@slow
				def      _snake_case       (				self				:    Any						)					->       str:
										__magic_name__      =  TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"						)

										__magic_name__      =  self.default_image_processor
										__magic_name__      =  prepare_img()
										__magic_name__      =  image_processor(images=__lowerCamelCase    ,     return_tensors="tf"						)

										# forward pass
										__magic_name__      =  model(**__lowerCamelCase						)

										# verify the logits
										__magic_name__      =  tf.TensorShape((1, 1_0_0_0)						)
										self.assertEqual(outputs.logits.shape    ,     __lowerCamelCase						)

										__magic_name__      =  tf.constant([-0.0260, -0.4739, 0.1911]						)

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



