"""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 							__snake_case:


    '''simple docstring'''





    def __init__(  self					,       __lowerCamelCase					,       __lowerCamelCase=13					,       __lowerCamelCase=32					,       __lowerCamelCase=3					,       __lowerCamelCase=4					,       __lowerCamelCase=[10, 20, 30, 40]					,       __lowerCamelCase=[2, 2, 3, 2]					,       __lowerCamelCase=True					,       __lowerCamelCase=True					,       __lowerCamelCase=37					,       __lowerCamelCase="gelu"					,       __lowerCamelCase=10					,       __lowerCamelCase=0.02					,       __lowerCamelCase=3					,       __lowerCamelCase=None					,       ):




         '''simple docstring'''



         __A					:					Optional[int]								=		parent
         __A					:					List[str]								=		batch_size
         __A					:					Tuple								=		image_size
         __A					:					Optional[int]								=		num_channels
         __A					:					int								=		num_stages
         __A					:					List[str]								=		hidden_sizes
         __A					:					Tuple								=		depths
         __A					:					Optional[Any]								=		is_training
         __A					:					List[str]								=		use_labels
         __A					:					Tuple								=		intermediate_size
         __A					:					Dict								=		hidden_act
         __A					:					int								=		type_sequence_label_size
         __A					:					Any								=		initializer_range
         __A					:					Tuple								=		scope
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

         __A					:					Optional[Any]								=		None
         if self.use_labels:
              __A					:					Tuple								=		ids_tensor([self.batch_size]					,       self.type_sequence_label_size	)

         __A					:					Tuple								=		self.get_config()

         return config, pixel_values, labels
    def 						_a							(  self	):




         '''simple docstring'''



         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 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					int								=		TFConvNextModel(config=__lowerCamelCase	)
         __A					:					Optional[Any]								=		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 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					List[str]								=		self.type_sequence_label_size
         __A					:					Optional[Any]								=		TFConvNextForImageClassification(__lowerCamelCase	)
         __A					:					Tuple								=		model(__lowerCamelCase					,       labels=__lowerCamelCase					,       training=__lowerCamelCase	)
         self.parent.assertEqual(result.logits.shape					,       (self.batch_size, self.type_sequence_label_size)	)

    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Any								=		self.prepare_config_and_inputs()
         __A						,		__A						,		__A					:					Dict								=		config_and_inputs
         __A					:					List[str]								=		{'pixel_values': pixel_values}
         return config, inputs_dict







@require_tf
class 							__snake_case(					A_				,	A_				,	unittest.TestCase	):


    '''simple docstring'''





    _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 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		TFConvNextModelTester(self	)
         __A					:					Optional[Any]								=		ConfigTester(
             self					,       config_class=__lowerCamelCase					,       has_text_modality=__lowerCamelCase					,       hidden_size=37					,       )
    @unittest.skip(reason='ConvNext does not use inputs_embeds'	)
    def 						_a							(  self	):




         '''simple docstring'''



         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 						_a							(  self	):




         '''simple docstring'''



         super().test_keras_fit()
    @unittest.skip(reason='ConvNext does not support input and output embeddings'	)
    def 						_a							(  self	):




         '''simple docstring'''



         pass
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					List[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

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

              __A					:					Optional[int]								=		['pixel_values']
              self.assertListEqual(arg_names[:1]					,       __lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[Any]								=		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 						_a							(  self	):




         '''simple docstring'''



         super().test_dataset_conversion()
    def 						_a							(  self	):




         '''simple docstring'''



         def check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):
              __A					:					Union[str, Any]								=		model_class(__lowerCamelCase	)

              __A					:					Dict								=		model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)	)
              __A					:					Tuple								=		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	)

              # 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]					,       )

         __A						,		__A					:					str								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __A					:					Union[str, 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					:					List[str]								=		True

              check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					str								=		self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase={}	):
              __A					:					List[str]								=		model(__lowerCamelCase					,       return_dict=__lowerCamelCase					,       **__lowerCamelCase	)
              __A					:					str								=		model(__lowerCamelCase					,       return_dict=__lowerCamelCase					,       **__lowerCamelCase	).to_tuple()

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

              __A					:					Optional[Any]								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)
              __A					:					Tuple								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)
              check_equivalence(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)

              __A					:					Optional[Any]								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase					,       return_labels=__lowerCamelCase	)
              __A					:					str								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase					,       return_labels=__lowerCamelCase	)
              check_equivalence(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)

              __A					:					Tuple								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)
              __A					:					Tuple								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)
              check_equivalence(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       {'output_hidden_states': True}	)

              __A					:					Optional[Any]								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase					,       return_labels=__lowerCamelCase	)
              __A					:					str								=		self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase					,       return_labels=__lowerCamelCase	)
              check_equivalence(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase					,       {'output_hidden_states': True}	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase	)

    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'	)
         self.assertIsNotNone(__lowerCamelCase	)







def 						_lowercase				(  )    ->     Any:







     '''simple docstring'''


     __A					:					List[Any]								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
     return image






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


    '''simple docstring'''





    @cached_property
    def 						_a							(  self	):




         '''simple docstring'''



         return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'	) if is_vision_available() else None

    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[str]								=		TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'	)

         __A					:					Any								=		self.default_image_processor
         __A					:					Tuple								=		prepare_img()
         __A					:					List[str]								=		image_processor(images=__lowerCamelCase					,       return_tensors='tf'	)

         # forward pass
         __A					:					Optional[Any]								=		model(**__lowerCamelCase	)

         # verify the logits
         __A					:					int								=		tf.TensorShape((1, 1000)	)
         self.assertEqual(outputs.logits.shape					,       __lowerCamelCase	)

         __A					:					Optional[Any]								=		tf.constant([-0.02_60, -0.47_39, 0.19_11]	)

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




"""simple docstring"""







from typing import Dict, Optional, Tuple

import torch




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor						)    ->     torch.Tensor:







     '''simple docstring'''


     __A					:					List[str]								=		boundaries[1] - boundaries[0]
     __A					:					int								=		boundaries + step / 2
     __A					:					Union[str, Any]								=		torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1						)]  ,       dim=0						)
     return bin_centers




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       )    ->     Tuple[torch.Tensor, torch.Tensor]:







     '''simple docstring'''


     __A					:					str								=		_calculate_bin_centers(_SCREAMING_SNAKE_CASE						)
     return (
         torch.sum(aligned_distance_error_probs * bin_centers  ,       dim=-1						),
         bin_centers[-1],
     )




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				int = 31  ,       _SCREAMING_SNAKE_CASE				:				int = 64  ,       **_SCREAMING_SNAKE_CASE				:				Optional[Any]  ,       )    ->     Dict[str, torch.Tensor]:







     '''simple docstring'''


     __A					:					int								=		torch.linspace(0  ,       _SCREAMING_SNAKE_CASE  ,       steps=(no_bins - 1)  ,       device=logits.device						)

     __A					:					Any								=		torch.nn.functional.softmax(_SCREAMING_SNAKE_CASE  ,       dim=-1						)
     __A						,		__A					:					Tuple								=		_calculate_expected_aligned_error(
         alignment_confidence_breaks=_SCREAMING_SNAKE_CASE  ,       aligned_distance_error_probs=_SCREAMING_SNAKE_CASE  ,       )

     return {
         "aligned_confidence_probs": aligned_confidence_probs,
         "predicted_aligned_error": predicted_aligned_error,
         "max_predicted_aligned_error": max_predicted_aligned_error,
     }




def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				torch.Tensor  ,       _SCREAMING_SNAKE_CASE				:				Optional[torch.Tensor] = None  ,       _SCREAMING_SNAKE_CASE				:				int = 31  ,       _SCREAMING_SNAKE_CASE				:				int = 64  ,       _SCREAMING_SNAKE_CASE				:				float = 1E-8  ,       **_SCREAMING_SNAKE_CASE				:				Union[str, Any]  ,       )    ->     torch.Tensor:







     '''simple docstring'''


     if residue_weights is None:
          __A					:					Optional[int]								=		logits.new_ones(logits.shape[-2]						)

     __A					:					List[str]								=		torch.linspace(0  ,       _SCREAMING_SNAKE_CASE  ,       steps=(no_bins - 1)  ,       device=logits.device						)

     __A					:					Tuple								=		_calculate_bin_centers(_SCREAMING_SNAKE_CASE						)
     torch.sum(_SCREAMING_SNAKE_CASE						)
     __A					:					int								=		logits.shape[-2]
     __A					:					str								=		max(_SCREAMING_SNAKE_CASE  ,       19						)

     __A					:					Tuple								=		1.24 * (clipped_n - 15) ** (1.0 / 3) - 1.8

     __A					:					Tuple								=		torch.nn.functional.softmax(_SCREAMING_SNAKE_CASE  ,       dim=-1						)

     __A					:					List[str]								=		1.0 / (1 + (bin_centers**2) / (da**2))
     __A					:					int								=		torch.sum(probs * tm_per_bin  ,       dim=-1						)

     __A					:					Any								=		residue_weights / (eps + residue_weights.sum())
     __A					:					List[Any]								=		torch.sum(predicted_tm_term * normed_residue_mask  ,       dim=-1						)

     __A					:					int								=		per_alignment * residue_weights

     __A					:					Optional[int]								=		(weighted == torch.max(_SCREAMING_SNAKE_CASE						)).nonzero()[0]
     return per_alignment[tuple(_SCREAMING_SNAKE_CASE						)]



