


"""simple docstring"""






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


  def __init__(			self:						Any							,__lowerCAmelCase:						Dict							,__lowerCAmelCase:						Optional[Any]=13							,__lowerCAmelCase:						Any=32							,__lowerCAmelCase:						Tuple=3							,__lowerCAmelCase:						Dict=4							,__lowerCAmelCase:						int=[10, 20, 30, 40]							,__lowerCAmelCase:						str=[2, 2, 3, 2]							,__lowerCAmelCase:						Optional[int]=True							,__lowerCAmelCase:						Any=True							,__lowerCAmelCase:						Optional[int]=37							,__lowerCAmelCase:						Optional[int]="gelu"							,__lowerCAmelCase:						List[Any]=10							,__lowerCAmelCase:						Union[str, Any]=0.02							,__lowerCAmelCase:						str=["stage2", "stage3", "stage4"]							,__lowerCAmelCase:						str=[2, 3, 4]							,__lowerCAmelCase:						Optional[Any]=None							,):







     '''simple docstring'''







     _lowerCamelCase   :				List[str]							=     parent
     _lowerCamelCase   :				List[str]							=     batch_size
     _lowerCamelCase   :				int							=     image_size
     _lowerCamelCase   :				List[str]							=     num_channels
     _lowerCamelCase   :				Any							=     num_stages
     _lowerCamelCase   :				Union[str, Any]							=     hidden_sizes
     _lowerCamelCase   :				Union[str, Any]							=     depths
     _lowerCamelCase   :				str							=     is_training
     _lowerCamelCase   :				Optional[int]							=     use_labels
     _lowerCamelCase   :				Optional[Any]							=     intermediate_size
     _lowerCamelCase   :				int							=     hidden_act
     _lowerCamelCase   :				List[str]							=     num_labels
     _lowerCamelCase   :				Optional[Any]							=     initializer_range
     _lowerCamelCase   :				Union[str, Any]							=     out_features
     _lowerCamelCase   :				int							=     out_indices
     _lowerCamelCase   :				Optional[int]							=     scope


  def 							_lowercase					(			self:						List[Any]    ):







     '''simple docstring'''







     _lowerCamelCase   :				Any							=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

     _lowerCamelCase   :				int							=     self.get_config()

     return config, pixel_values, labels


  def 							_lowercase					(			self:						int    ):







     '''simple docstring'''







     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=__lowerCAmelCase							,initializer_range=self.initializer_range							,out_features=self.out_features							,out_indices=self.out_indices							,num_labels=self.num_labels							,)


  def 							_lowercase					(			self:						Union[str, Any]							,__lowerCAmelCase:						str							,__lowerCAmelCase:						Optional[Any]							,__lowerCAmelCase:						List[str]    ):







     '''simple docstring'''







     _lowerCamelCase   :				int							=     ConvNextVaModel(config=__lowerCAmelCase    )
     model.to(__lowerCAmelCase    )
     model.eval()
     _lowerCamelCase   :				Union[str, Any]							=     model(__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 							_lowercase					(			self:						List[Any]							,__lowerCAmelCase:						Union[str, Any]							,__lowerCAmelCase:						Optional[int]							,__lowerCAmelCase:						Optional[Any]    ):







     '''simple docstring'''







     _lowerCamelCase   :				Optional[Any]							=     ConvNextVaForImageClassification(__lowerCAmelCase    )
     model.to(__lowerCAmelCase    )
     model.eval()
     _lowerCamelCase   :				List[Any]							=     model(__lowerCAmelCase							,labels=__lowerCAmelCase    )
     self.parent.assertEqual(result.logits.shape							,(self.batch_size, self.num_labels)    )


  def 							_lowercase					(			self:						int							,__lowerCAmelCase:						Any							,__lowerCAmelCase:						List[Any]							,__lowerCAmelCase:						List[Any]    ):







     '''simple docstring'''







     _lowerCamelCase   :				str							=     ConvNextVaBackbone(config=__lowerCAmelCase    )
     model.to(__lowerCAmelCase    )
     model.eval()
     _lowerCamelCase   :				Union[str, Any]							=     model(__lowerCAmelCase    )

     # 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
     _lowerCamelCase   :				Union[str, Any]							=     None
     _lowerCamelCase   :				Union[str, Any]							=     ConvNextVaBackbone(config=__lowerCAmelCase    )
     model.to(__lowerCAmelCase    )
     model.eval()
     _lowerCamelCase   :				str							=     model(__lowerCAmelCase    )

     # 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 							_lowercase					(			self:						Any    ):







     '''simple docstring'''







     _lowerCamelCase   :				Union[str, Any]							=     self.prepare_config_and_inputs()
     _lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase   :				Dict							=     config_and_inputs
     _lowerCamelCase   :				Any							=     {"pixel_values": pixel_values}
     return config, inputs_dict






  def 							_lowercase					(			self:						Any    ):







     '''simple docstring'''







     _lowerCamelCase   :				Tuple							=     self.prepare_config_and_inputs()
     _lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase   :				Union[str, Any]							=     config_and_inputs
     _lowerCamelCase   :				Optional[int]							=     {"pixel_values": pixel_values, "labels": labels}
     return config, inputs_dict




@require_torch
class 							A_      (       _a     ,	_a     ,	unittest.TestCase ):
  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 							_lowercase					(			self:						List[Any]    ):







     '''simple docstring'''







     _lowerCamelCase   :				List[str]							=     ConvNextVaModelTester(self    )
     _lowerCamelCase   :				Dict							=     ConfigTester(self							,config_class=__lowerCAmelCase							,has_text_modality=__lowerCAmelCase							,hidden_size=37    )


  def 							_lowercase					(			self:						Optional[Any]    ):







     '''simple docstring'''







     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 							_lowercase					(			self:						List[str]    ):







     '''simple docstring'''







     return


  @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"    )
  def 							_lowercase					(			self:						Dict    ):







     '''simple docstring'''







     pass


  @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"    )
  def 							_lowercase					(			self:						str    ):







     '''simple docstring'''







     pass


  @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"    )
  def 							_lowercase					(			self:						List[str]    ):







     '''simple docstring'''







     pass


  def 							_lowercase					(			self:						Any    ):







     '''simple docstring'''







     if not self.model_tester.is_training:
        return

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

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

        _lowerCamelCase   :				Union[str, Any]							=     model_class(__lowerCAmelCase    )
        model.to(__lowerCAmelCase    )
        model.train()
        _lowerCamelCase   :				Any							=     self._prepare_for_class(__lowerCAmelCase							,__lowerCAmelCase							,return_labels=__lowerCAmelCase    )
        _lowerCamelCase   :				Tuple							=     model(**__lowerCAmelCase    ).loss
        loss.backward()


  def 							_lowercase					(			self:						Optional[int]    ):







     '''simple docstring'''







     if not self.model_tester.is_training:
        return

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

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

        _lowerCamelCase   :				List[Any]							=     model_class(__lowerCAmelCase    )
        model.to(__lowerCAmelCase    )
        model.gradient_checkpointing_enable()
        model.train()
        _lowerCamelCase   :				List[Any]							=     self._prepare_for_class(__lowerCAmelCase							,__lowerCAmelCase							,return_labels=__lowerCAmelCase    )
        _lowerCamelCase   :				str							=     model(**__lowerCAmelCase    ).loss
        loss.backward()


  def 							_lowercase					(			self:						Dict    ):







     '''simple docstring'''







     _lowerCamelCase,					_lowerCamelCase   :				Optional[Any]							=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        _lowerCamelCase   :				str							=     model_class(__lowerCAmelCase    )
        _lowerCamelCase   :				str							=     inspect.signature(model.forward    )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        _lowerCamelCase   :				Optional[int]							=     [*signature.parameters.keys()]

        _lowerCamelCase   :				Tuple							=     ["pixel_values"]
        self.assertListEqual(arg_names[:1]							,__lowerCAmelCase    )


  def 							_lowercase					(			self:						str    ):







     '''simple docstring'''







     _lowerCamelCase   :				List[str]							=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCAmelCase    )


  def 							_lowercase					(			self:						Optional[Any]    ):







     '''simple docstring'''







     def check_hidden_states_output(__lowerCAmelCase:						Any							,__lowerCAmelCase:						Dict							,__lowerCAmelCase:						List[Any]    ):
        _lowerCamelCase   :				List[str]							=     model_class(__lowerCAmelCase    )
        model.to(__lowerCAmelCase    )
        model.eval()

        with torch.no_grad():
           _lowerCamelCase   :				Optional[Any]							=     model(**self._prepare_for_class(__lowerCAmelCase							,__lowerCAmelCase    )    )

        _lowerCamelCase   :				List[Any]							=     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        _lowerCamelCase   :				Dict							=     self.model_tester.num_stages
        self.assertEqual(len(__lowerCAmelCase    )							,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]							,)

     _lowerCamelCase,					_lowerCamelCase   :				Any							=     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        _lowerCamelCase   :				Optional[Any]							=     True
        check_hidden_states_output(__lowerCAmelCase							,__lowerCAmelCase							,__lowerCAmelCase    )

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

        check_hidden_states_output(__lowerCAmelCase							,__lowerCAmelCase							,__lowerCAmelCase    )


  def 							_lowercase					(			self:						Tuple    ):







     '''simple docstring'''







     _lowerCamelCase   :				str							=     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase    )






  @slow
  def 							_lowercase					(			self:						Optional[int]    ):







     '''simple docstring'''







     for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _lowerCamelCase   :				Any							=     ConvNextVaModel.from_pretrained(__lowerCAmelCase    )
        self.assertIsNotNone(__lowerCAmelCase    )







def        lowerCamelCase_(		)    ->     Any:
   '''simple docstring'''





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




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


  @cached_property
  def 							_lowercase					(			self:						Dict    ):







     '''simple docstring'''







     return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"    ) if is_vision_available() else None






  @slow
  def 							_lowercase					(			self:						List[str]    ):







     '''simple docstring'''







     _lowerCamelCase   :				Union[str, Any]							=     ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"    ).to(__lowerCAmelCase    )

     _lowerCamelCase   :				int							=     self.default_image_processor
     _lowerCamelCase   :				Union[str, Any]							=     prepare_img()
     _lowerCamelCase   :				Tuple							=     preprocessor(images=__lowerCAmelCase							,return_tensors="pt"    ).to(__lowerCAmelCase    )

     # forward pass
     with torch.no_grad():
        _lowerCamelCase   :				str							=     model(**__lowerCAmelCase    )

     # verify the logits
     _lowerCamelCase   :				Optional[Any]							=     torch.Size((1, 1_000)    )
     self.assertEqual(outputs.logits.shape							,__lowerCAmelCase    )

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


'''simple docstring'''




def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : int = 1000    ):
  UpperCAmelCase    				=						-1
  UpperCAmelCase    				=						0
  for a in range(1							, n // 3    ):
    # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
    UpperCAmelCase    				=						(n * n - 2 * a * n) // (2 * n - 2 * a)
    UpperCAmelCase    				=						n - a - b
    if c * c == (a * a + b * b):
      UpperCAmelCase    				=						a * b * c
      if candidate >= product:
        UpperCAmelCase    				=						candidate
  return product


if __name__ == "__main__":
  print(F'''{solution() = }''')


