





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







      def __init__(    self		,      lowerCAmelCase__		,      lowerCAmelCase__=1_3		,      lowerCAmelCase__=3_2		,      lowerCAmelCase__=3		,      lowerCAmelCase__=4		,      lowerCAmelCase__=[1_0, 2_0, 3_0, 4_0]		,      lowerCAmelCase__=[2, 2, 3, 2]		,      lowerCAmelCase__=True		,      lowerCAmelCase__=True		,      lowerCAmelCase__=3_7		,      lowerCAmelCase__="gelu"		,      lowerCAmelCase__=1_0		,      lowerCAmelCase__=0.02		,      lowerCAmelCase__=["stage2", "stage3", "stage4"]		,      lowerCAmelCase__=[2, 3, 4]		,      lowerCAmelCase__=None		,      )   ->						Optional[int]:



        '''simple docstring'''




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







      def    _lowercase  (    self							)   ->						Union[str, Any]:



        '''simple docstring'''




        a__	:					Dict										=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

        a__	:					Dict										=self.get_config()

        return config, pixel_values, labels







      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''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		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)   ->						str:



        '''simple docstring'''




        a__	:					List[Any]										=ConvNextVaModel(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__	:					Tuple										=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 // 3_2, self.image_size // 3_2)		,      )







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)   ->						Dict:



        '''simple docstring'''




        a__	:					Optional[int]										=ConvNextVaForImageClassification(lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__	:					Dict										=model(lowerCAmelCase__		,      labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)							)







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Dict										=ConvNextVaBackbone(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__	:					Dict										=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
        a__	:					str										=None
        a__	:					int										=ConvNextVaBackbone(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__	:					int										=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							)   ->						Optional[int]:



        '''simple docstring'''




        a__	:					Dict										=self.prepare_config_and_inputs()
        a__					,							a__					,							a__	:					int										=config_and_inputs
        a__	:					Dict										={"pixel_values": pixel_values}
        return config, inputs_dict







      def    _lowercase  (    self							)   ->						List[str]:



        '''simple docstring'''




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







@require_torch
class 				__lowerCAmelCase       (    UpperCamelCase__						,				UpperCamelCase__						,				unittest.TestCase):
      _lowercase				:					str						=			(
          (
              ConvNextVaModel,
              ConvNextVaForImageClassification,
              ConvNextVaBackbone,
          )
          if is_torch_available()
          else ()
      )
      _lowercase				:					Any						=			(
          {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
          if is_torch_available()
          else {}
      )

      _lowercase				:					List[str]						=			False
      _lowercase				:					List[str]						=			False
      _lowercase				:					List[str]						=			False
      _lowercase				:					List[str]						=			False
      _lowercase				:					List[str]						=			False







      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''simple docstring'''




        a__	:					Optional[int]										=ConvNextVaModelTester(self							)
        a__	:					str										=ConfigTester(self		,      config_class=lowerCAmelCase__		,      has_text_modality=lowerCAmelCase__		,      hidden_size=3_7							)







      def    _lowercase  (    self							)   ->						str:



        '''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							)   ->						Tuple:



        '''simple docstring'''




        return







      @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"							)
      def    _lowercase  (    self							)   ->						Optional[Any]:



        '''simple docstring'''




        pass







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



        '''simple docstring'''




        pass







      @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"							)
      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        pass







      def    _lowercase  (    self							)   ->						Dict:



        '''simple docstring'''




        if not self.model_tester.is_training:
          return

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

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

          a__	:					Any										=model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.train()
          a__	:					Tuple										=self._prepare_for_class(lowerCAmelCase__		,      lowerCAmelCase__		,      return_labels=lowerCAmelCase__							)
          a__	:					Tuple										=model(**lowerCAmelCase__							).loss
          loss.backward()







      def    _lowercase  (    self							)   ->						Union[str, Any]:



        '''simple docstring'''




        if not self.model_tester.is_training:
          return

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

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

          a__	:					List[Any]										=model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.gradient_checkpointing_enable()
          model.train()
          a__	:					Dict										=self._prepare_for_class(lowerCAmelCase__		,      lowerCAmelCase__		,      return_labels=lowerCAmelCase__							)
          a__	:					List[Any]										=model(**lowerCAmelCase__							).loss
          loss.backward()







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        a__					,							a__	:					int										=self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          a__	:					List[Any]										=model_class(lowerCAmelCase__							)
          a__	:					Any										=inspect.signature(model.forward							)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          a__	:					Dict										=[*signature.parameters.keys()]

          a__	:					int										=["pixel_values"]
          self.assertListEqual(arg_names[:1]		,      lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						Tuple:



        '''simple docstring'''




        a__	:					Union[str, Any]										=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						List[Any]:



        '''simple docstring'''




        def check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							):
          a__	:					Optional[int]										=model_class(lowerCAmelCase__							)
          model.to(lowerCAmelCase__							)
          model.eval()

          with torch.no_grad():
            a__	:					List[Any]										=model(**self._prepare_for_class(lowerCAmelCase__		,      lowerCAmelCase__							)							)

          a__	:					Optional[Any]										=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          a__	:					Any										=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]		,      )

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

        for model_class in self.all_model_classes:
          a__	:					str										=True
          check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)

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

          check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__							)







      def    _lowercase  (    self							)   ->						Union[str, Any]:



        '''simple docstring'''




        a__	:					Optional[int]										=self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)







      @slow
      def    _lowercase  (    self							)   ->						int:



        '''simple docstring'''




        for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__	:					Union[str, Any]										=ConvNextVaModel.from_pretrained(lowerCAmelCase__							)
          self.assertIsNotNone(lowerCAmelCase__							)
def      _A       (		):





  """simple docstring"""



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







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







      @cached_property
      def    _lowercase  (    self							)   ->						Optional[int]:



        '''simple docstring'''




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







      @slow
      def    _lowercase  (    self							)   ->						Any:



        '''simple docstring'''




        a__	:					Optional[Any]										=ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"							).to(lowerCAmelCase__							)

        a__	:					Any										=self.default_image_processor
        a__	:					Any										=prepare_img()
        a__	:					str										=preprocessor(images=lowerCAmelCase__		,      return_tensors="pt"							).to(lowerCAmelCase__							)

        # forward pass
        with torch.no_grad():
          a__	:					List[str]										=model(**lowerCAmelCase__							)

        # verify the logits
        a__	:					str										=torch.Size((1, 1_0_0_0)							)
        self.assertEqual(outputs.logits.shape		,      lowerCAmelCase__							)

        a__	:					str										=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							)							)










from __future__ import annotations

from collections.abc import Callable

UpperCAmelCase__   	=							list[list[float | int]]
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			Matrix:







 """simple docstring"""


 _lowercase							      =len(__snake_case						)
 _lowercase							      =[[0 for _ in range(size + 1						)] for _ in range(__snake_case						)]
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42

 for row in range(__snake_case						):
  for col in range(__snake_case						):
   _lowercase							      =matrix[row][col]

  _lowercase							      =vector[row][0]

 _lowercase							      =0
 _lowercase							      =0
 while row < size and col < size:
  # pivoting
  _lowercase							      =max((abs(augmented[rowa][col]						), rowa) for rowa in range(__snake_case     ,						__snake_case						)						)[
      1
  ]
  if augmented[pivot_row][col] == 0:
   col += 1
   continue
  else:
   _lowercase      ,    _lowercase							      =augmented[pivot_row], augmented[row]

  for rowa in range(row + 1     ,						__snake_case						):
   _lowercase							      =augmented[rowa][col] / augmented[row][col]
   _lowercase							      =0
   for cola in range(col + 1     ,						size + 1						):
    augmented[rowa][cola] -= augmented[row][cola] * ratio

  row += 1
  col += 1

 # back substitution
 for col in range(1     ,						__snake_case						):
  for row in range(__snake_case						):
   _lowercase							      =augmented[row][col] / augmented[col][col]
   for cola in range(__snake_case     ,						size + 1						):
    augmented[row][cola] -= augmented[col][cola] * ratio

    # round to get rid of numbers like 2.000000000000004
 return [
     [round(augmented[row][size] / augmented[row][row]     ,						10						)] for row in range(__snake_case						)
 ]
def 				UpperCAmelCase_					(							__snake_case						)     ->			Callable[[int], int]:







 """simple docstring"""


 _lowercase							      =len(__snake_case						)
 _lowercase							      =[[0 for _ in range(__snake_case						)] for _ in range(__snake_case						)]
 _lowercase							      =[[0] for _ in range(__snake_case						)]
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42
 _lowercase							      =42

 for x_val, y_val in enumerate(__snake_case						):
  for col in range(__snake_case						):
   _lowercase							      =(x_val + 1) ** (size - col - 1)
  _lowercase							      =y_val

 _lowercase							      =solve(__snake_case     ,						__snake_case						)

 def interpolated_func(__snake_case						) -> int:
  return sum(
      round(coeffs[x_val][0]						) * (var ** (size - x_val - 1))
      for x_val in range(__snake_case						)						)

 return interpolated_func
def 				UpperCAmelCase_					(							__snake_case						)     ->			int:







 """simple docstring"""


 return (
     1
     - variable
     + variable**2
     - variable**3
     + variable**4
     - variable**5
     + variable**6
     - variable**7
     + variable**8
     - variable**9
     + variable**10
 )
def 				UpperCAmelCase_					(							__snake_case = question_function     ,						__snake_case = 10						)     ->			int:







 """simple docstring"""


 _lowercase							      =[func(__snake_case						) for x_val in range(1     ,						order + 1						)]

 _lowercase							      =[
     interpolate(data_points[:max_coeff]						) for max_coeff in range(1     ,						order + 1						)
 ]

 _lowercase							      =0
 _lowercase							      =42
 _lowercase							      =42

 for poly in polynomials:
  _lowercase							      =1
  while func(__snake_case						) == poly(__snake_case						):
   x_val += 1

  ret += poly(__snake_case						)

 return ret


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

