




import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
     from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor

class   __a:






    """simple docstring"""





    def __init__(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=13       ,_SCREAMING_SNAKE_CASE=32       ,_SCREAMING_SNAKE_CASE=3       ,_SCREAMING_SNAKE_CASE=4       ,_SCREAMING_SNAKE_CASE=[10, 20, 30, 40]       ,_SCREAMING_SNAKE_CASE=[2, 2, 3, 2]       ,_SCREAMING_SNAKE_CASE=True       ,_SCREAMING_SNAKE_CASE=True       ,_SCREAMING_SNAKE_CASE=37       ,_SCREAMING_SNAKE_CASE="gelu"       ,_SCREAMING_SNAKE_CASE=10       ,_SCREAMING_SNAKE_CASE=0.02       ,_SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"]       ,_SCREAMING_SNAKE_CASE=[2, 3, 4]       ,_SCREAMING_SNAKE_CASE=None       ,)			->		Dict:
         UpperCAmelCase_      :							Optional[int]       =      parent
         UpperCAmelCase_      :							List[str]       =      batch_size
         UpperCAmelCase_      :							List[str]       =      image_size
         UpperCAmelCase_      :							int       =      num_channels
         UpperCAmelCase_      :							Tuple       =      num_stages
         UpperCAmelCase_      :							Optional[int]       =      hidden_sizes
         UpperCAmelCase_      :							List[Any]       =      depths
         UpperCAmelCase_      :							Any       =      is_training
         UpperCAmelCase_      :							str       =      use_labels
         UpperCAmelCase_      :							int       =      intermediate_size
         UpperCAmelCase_      :							Any       =      hidden_act
         UpperCAmelCase_      :							Optional[Any]       =      num_labels
         UpperCAmelCase_      :							Union[str, Any]       =      initializer_range
         UpperCAmelCase_      :							Any       =      out_features
         UpperCAmelCase_      :							Dict       =      out_indices
         UpperCAmelCase_      :							Union[str, Any]       =      scope





    def 							a__				(				self  )			->		Tuple:
         UpperCAmelCase_      :							Any       =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

         UpperCAmelCase_      :							Tuple       =      self.get_config()

         return config, pixel_values, labels





    def 							a__				(				self  )			->		Optional[Any]:
         return ConvNextVaConfig(
             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=_SCREAMING_SNAKE_CASE       ,initializer_range=self.initializer_range       ,out_features=self.out_features       ,out_indices=self.out_indices       ,num_labels=self.num_labels       ,)





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Dict:
         UpperCAmelCase_      :							Union[str, Any]       =      ConvNextVaModel(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Optional[Any]       =      model(_SCREAMING_SNAKE_CASE  )
         # 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       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Optional[Any]:
         UpperCAmelCase_      :							Any       =      ConvNextVaForImageClassification(_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							Union[str, Any]       =      model(_SCREAMING_SNAKE_CASE       ,labels=_SCREAMING_SNAKE_CASE  )
         self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		Dict:
         UpperCAmelCase_      :							Optional[int]       =      ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							List[str]       =      model(_SCREAMING_SNAKE_CASE  )

         # verify hidden states
         self.parent.assertEqual(len(result.feature_maps  )       ,len(config.out_features  )  )
         self.parent.assertListEqual(list(result.feature_maps[0].shape  )       ,[self.batch_size, self.hidden_sizes[1], 4, 4]  )

         # verify channels
         self.parent.assertEqual(len(model.channels  )       ,len(config.out_features  )  )
         self.parent.assertListEqual(model.channels       ,config.hidden_sizes[1:]  )

         # verify backbone works with out_features=None
         UpperCAmelCase_      :							Union[str, Any]       =      None
         UpperCAmelCase_      :							str       =      ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE  )
         model.to(_SCREAMING_SNAKE_CASE  )
         model.eval()
         UpperCAmelCase_      :							str       =      model(_SCREAMING_SNAKE_CASE  )

         # verify feature maps
         self.parent.assertEqual(len(result.feature_maps  )       ,1  )
         self.parent.assertListEqual(list(result.feature_maps[0].shape  )       ,[self.batch_size, self.hidden_sizes[-1], 1, 1]  )

         # verify channels
         self.parent.assertEqual(len(model.channels  )       ,1  )
         self.parent.assertListEqual(model.channels       ,[config.hidden_sizes[-1]]  )





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Union[str, Any]       =      self.prepare_config_and_inputs()
         UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							List[Any]       =      config_and_inputs
         UpperCAmelCase_      :							Dict       =      {'''pixel_values''': pixel_values}
         return config, inputs_dict





    def 							a__				(				self  )			->		int:
         UpperCAmelCase_      :							Optional[Any]       =      self.prepare_config_and_inputs()
         UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							Union[str, Any]       =      config_and_inputs
         UpperCAmelCase_      :							Optional[Any]       =      {'''pixel_values''': pixel_values, '''labels''': labels}
         return config, inputs_dict


@require_torch
class   __a(					_a    ,						_a    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase        =				(
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    lowerCAmelCase        =				(
        {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

    lowerCAmelCase        =				False
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False
    lowerCAmelCase        =				False





    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							List[str]       =      ConvNextVaModelTester(self  )
         UpperCAmelCase_      :							Optional[Any]       =      ConfigTester(self       ,config_class=_SCREAMING_SNAKE_CASE       ,has_text_modality=_SCREAMING_SNAKE_CASE       ,hidden_size=37  )





    def 							a__				(				self  )			->		List[Any]:
         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 							a__				(				self  )			->		Optional[Any]:
         return





    @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds'''  )
    def 							a__				(				self  )			->		Dict:
         pass





    @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''  )
    def 							a__				(				self  )			->		Optional[int]:
         pass





    @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''  )
    def 							a__				(				self  )			->		Union[str, Any]:
         pass





    def 							a__				(				self  )			->		Dict:
         if not self.model_tester.is_training:
              return

         for model_class in self.all_model_classes:
              UpperCAmelCase_,   UpperCAmelCase_      :							List[str]       =      self.model_tester.prepare_config_and_inputs_with_labels()
              UpperCAmelCase_      :							Optional[Any]       =      True

              if model_class.__name__ in [
                  *get_values(_SCREAMING_SNAKE_CASE  ),
                  *get_values(_SCREAMING_SNAKE_CASE  ),
              ]:
                   continue

              UpperCAmelCase_      :							Union[str, Any]       =      model_class(_SCREAMING_SNAKE_CASE  )
              model.to(_SCREAMING_SNAKE_CASE  )
              model.train()
              UpperCAmelCase_      :							List[str]       =      self._prepare_for_class(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,return_labels=_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Optional[int]       =      model(**_SCREAMING_SNAKE_CASE  ).loss
              loss.backward()





    def 							a__				(				self  )			->		str:
         if not self.model_tester.is_training:
              return

         for model_class in self.all_model_classes:
              UpperCAmelCase_,   UpperCAmelCase_      :							Dict       =      self.model_tester.prepare_config_and_inputs_with_labels()
              UpperCAmelCase_      :							Optional[int]       =      False
              UpperCAmelCase_      :							List[Any]       =      True

              if (
                  model_class.__name__
                  in [*get_values(_SCREAMING_SNAKE_CASE  ), *get_values(_SCREAMING_SNAKE_CASE  )]
                  or not model_class.supports_gradient_checkpointing
              ):
                   continue

              UpperCAmelCase_      :							int       =      model_class(_SCREAMING_SNAKE_CASE  )
              model.to(_SCREAMING_SNAKE_CASE  )
              model.gradient_checkpointing_enable()
              model.train()
              UpperCAmelCase_      :							Optional[int]       =      self._prepare_for_class(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,return_labels=_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Union[str, Any]       =      model(**_SCREAMING_SNAKE_CASE  ).loss
              loss.backward()





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_,   UpperCAmelCase_      :							int       =      self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_      :							Tuple       =      model_class(_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Union[str, Any]       =      inspect.signature(model.forward  )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase_      :							Optional[Any]       =      [*signature.parameters.keys()]

              UpperCAmelCase_      :							List[Any]       =      ['''pixel_values''']
              self.assertListEqual(arg_names[:1]       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Any:
         UpperCAmelCase_      :							Dict       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Any:
         def check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              UpperCAmelCase_      :							int       =      model_class(_SCREAMING_SNAKE_CASE  )
              model.to(_SCREAMING_SNAKE_CASE  )
              model.eval()

              with torch.no_grad():
                   UpperCAmelCase_      :							Any       =      model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )  )

              UpperCAmelCase_      :							Any       =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              UpperCAmelCase_      :							Any       =      self.model_tester.num_stages
              self.assertEqual(len(_SCREAMING_SNAKE_CASE  )       ,expected_num_stages + 1  )

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

         UpperCAmelCase_,   UpperCAmelCase_      :							Tuple       =      self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_      :							Union[str, Any]       =      True
              check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCAmelCase_      :							List[Any]       =      True

              check_hidden_states_output(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Tuple:
         UpperCAmelCase_      :							Optional[Any]       =      self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE  )





    @slow
    def 							a__				(				self  )			->		str:
         for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase_      :							int       =      ConvNextVaModel.from_pretrained(_SCREAMING_SNAKE_CASE  )
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE  )







def lowerCamelCase__       (      ):

     '''simple docstring'''


     UpperCAmelCase_      :							Optional[int]       =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
     return image



@require_torch
@require_vision
class   __a(					unittest.TestCase       ):






    """simple docstring"""





    @cached_property
    def 							a__				(				self  )			->		Optional[int]:
         return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''  ) if is_vision_available() else None





    @slow
    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Optional[Any]       =      ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''  ).to(_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Tuple       =      self.default_image_processor
         UpperCAmelCase_      :							Optional[int]       =      prepare_img()
         UpperCAmelCase_      :							Optional[int]       =      preprocessor(images=_SCREAMING_SNAKE_CASE       ,return_tensors='''pt'''  ).to(_SCREAMING_SNAKE_CASE  )

         # forward pass
         with torch.no_grad():
              UpperCAmelCase_      :							Optional[Any]       =      model(**_SCREAMING_SNAKE_CASE  )

         # verify the logits
         UpperCAmelCase_      :							List[str]       =      torch.Size((1, 1_000)  )
         self.assertEqual(outputs.logits.shape       ,_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Dict       =      torch.tensor([0.99_96, 0.19_66, -0.43_86]  ).to(_SCREAMING_SNAKE_CASE  )
         self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-4  )  )





from __future__ import annotations

from fractions import Fraction







def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     return (
         num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den
     )







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Optional[int]       =      []
     UpperCAmelCase_      :							Tuple       =      11
     UpperCAmelCase_      :							int       =      int('''1''' + '''0''' * digit_len				)
     for num in range(_lowercase			,						_lowercase				):
          while den <= 99:
               if (num != den) and (num % 10 == den // 10) and (den % 10 != 0):
                    if is_digit_cancelling(_lowercase			,						_lowercase				):
                         solutions.append(f'''{num}/{den}'''				)
               den += 1
          num += 1
          UpperCAmelCase_      :							Any       =      10
     return solutions







def lowerCamelCase__       (      _lowercase = 2				):

     '''simple docstring'''


     UpperCAmelCase_      :							Tuple       =      1.0
     for fraction in fraction_list(_lowercase				):
          UpperCAmelCase_      :							Optional[Any]       =      Fraction(_lowercase				)
          result *= frac.denominator / frac.numerator
     return int(_lowercase				)


if __name__ == "__main__":
     print(solution())