


'''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__							:





							'''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_=["stage2", "stage3", "stage4"]   ,       lowerCamelCase_=[2, 3, 4]   ,       lowerCamelCase_=None   ,       )			->				Dict:
														lowerCAmelCase__			  =      parent
														lowerCAmelCase__			  =      batch_size
														lowerCAmelCase__			  =      image_size
														lowerCAmelCase__			  =      num_channels
														lowerCAmelCase__			  =      num_stages
														lowerCAmelCase__			  =      hidden_sizes
														lowerCAmelCase__			  =      depths
														lowerCAmelCase__			  =      is_training
														lowerCAmelCase__			  =      use_labels
														lowerCAmelCase__			  =      intermediate_size
														lowerCAmelCase__			  =      hidden_act
														lowerCAmelCase__			  =      num_labels
														lowerCAmelCase__			  =      initializer_range
														lowerCAmelCase__			  =      out_features
														lowerCAmelCase__			  =      out_indices
														lowerCAmelCase__			  =      scope







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														lowerCAmelCase__			  =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

														lowerCAmelCase__			  =      None
														if self.use_labels:
																					lowerCAmelCase__			  =      ids_tensor([self.batch_size]   ,       self.num_labels  )

														lowerCAmelCase__			  =      self.get_config()

														return config, pixel_values, labels







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Dict:
														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     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Any:
														lowerCAmelCase__			  =      ConvNextVaModel(config=lowerCamelCase_  )
														model.to(lowerCamelCase_  )
														model.eval()
														lowerCAmelCase__			  =      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     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				Any:
														lowerCAmelCase__			  =      ConvNextVaForImageClassification(lowerCamelCase_  )
														model.to(lowerCamelCase_  )
														model.eval()
														lowerCAmelCase__			  =      model(lowerCamelCase_   ,       labels=lowerCamelCase_  )
														self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.num_labels)  )







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  )			->				List[Any]:
														lowerCAmelCase__			  =      ConvNextVaBackbone(config=lowerCamelCase_  )
														model.to(lowerCamelCase_  )
														model.eval()
														lowerCAmelCase__			  =      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__			  =      None
														lowerCAmelCase__			  =      ConvNextVaBackbone(config=lowerCamelCase_  )
														model.to(lowerCamelCase_  )
														model.eval()
														lowerCAmelCase__			  =      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     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      self.prepare_config_and_inputs()
														lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__			  =      config_and_inputs
														lowerCAmelCase__			  =      {'''pixel_values''': pixel_values}
														return config, inputs_dict







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      self.prepare_config_and_inputs()
														lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__			  =      config_and_inputs
														lowerCAmelCase__			  =      {'''pixel_values''': pixel_values, '''labels''': labels}
														return config, inputs_dict




@require_torch
class 						a__							(				a__							,							a__							,							unittest.TestCase    ):





							'''simple docstring'''






							lowercase__     :  int      		= (
							    (
							        ConvNextVaModel,
							        ConvNextVaForImageClassification,
							        ConvNextVaBackbone,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase__     :  Any      		= (
							    {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
							    if is_torch_available()
							    else {}
							)

							lowercase__     :  Dict      		= False
							lowercase__     :  Any      		= False
							lowercase__     :  Dict      		= False
							lowercase__     :  List[Any]      		= False
							lowercase__     :  Optional[int]      		= False







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      ConvNextVaModelTester(self  )
														lowerCAmelCase__			  =      ConfigTester(self   ,       config_class=lowerCamelCase_   ,       has_text_modality=lowerCamelCase_   ,       hidden_size=37  )







							def     __SCREAMING_SNAKE_CASE				(						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     __SCREAMING_SNAKE_CASE				(						self  )			->				int:
														return







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







							@unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''  )
							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														pass







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







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[Any]:
														if not self.model_tester.is_training:
																					return

														for model_class in self.all_model_classes:
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      self.model_tester.prepare_config_and_inputs_with_labels()
																					lowerCAmelCase__			  =      True

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

																					lowerCAmelCase__			  =      model_class(lowerCamelCase_  )
																					model.to(lowerCamelCase_  )
																					model.train()
																					lowerCAmelCase__			  =      self._prepare_for_class(lowerCamelCase_   ,       lowerCamelCase_   ,       return_labels=lowerCamelCase_  )
																					lowerCAmelCase__			  =      model(**lowerCamelCase_  ).loss
																					loss.backward()







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[str]:
														if not self.model_tester.is_training:
																					return

														for model_class in self.all_model_classes:
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      self.model_tester.prepare_config_and_inputs_with_labels()
																					lowerCAmelCase__			  =      False
																					lowerCAmelCase__			  =      True

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

																					lowerCAmelCase__			  =      model_class(lowerCamelCase_  )
																					model.to(lowerCamelCase_  )
																					model.gradient_checkpointing_enable()
																					model.train()
																					lowerCAmelCase__			  =      self._prepare_for_class(lowerCamelCase_   ,       lowerCamelCase_   ,       return_labels=lowerCamelCase_  )
																					lowerCAmelCase__			  =      model(**lowerCamelCase_  ).loss
																					loss.backward()







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Dict:
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCAmelCase__			  =      ['''pixel_values''']
																					self.assertListEqual(arg_names[:1]   ,       lowerCamelCase_  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[str]:
														lowerCAmelCase__			  =      self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*lowerCamelCase_  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				int:
														def check_hidden_states_output(lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  ):
																					lowerCAmelCase__			  =      model_class(lowerCamelCase_  )
																					model.to(lowerCamelCase_  )
																					model.eval()

																					with torch.no_grad():
																												lowerCAmelCase__			  =      model(**self._prepare_for_class(lowerCamelCase_   ,       lowerCamelCase_  )  )

																					lowerCAmelCase__			  =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																					lowerCAmelCase__			  =      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__			  =      self.model_tester.prepare_config_and_inputs_for_common()

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

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

																					check_hidden_states_output(lowerCamelCase_   ,       lowerCamelCase_   ,       lowerCamelCase_  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Union[str, Any]:
														lowerCAmelCase__			  =      self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*lowerCamelCase_  )







							@slow
							def     __SCREAMING_SNAKE_CASE				(						self  )			->				str:
														for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCAmelCase__			  =      ConvNextVaModel.from_pretrained(lowerCamelCase_  )
																					self.assertIsNotNone(lowerCamelCase_  )


def    _snake_case  (	)		->       int:
							lowerCAmelCase__			  =      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
							return image






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





							'''simple docstring'''






							@cached_property
							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''  ) if is_vision_available() else None







							@slow
							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Union[str, Any]:
														lowerCAmelCase__			  =      ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''  ).to(lowerCamelCase_  )

														lowerCAmelCase__			  =      self.default_image_processor
														lowerCAmelCase__			  =      prepare_img()
														lowerCAmelCase__			  =      preprocessor(images=lowerCamelCase_   ,       return_tensors='''pt'''  ).to(lowerCamelCase_  )

														# forward pass
														with torch.no_grad():
																					lowerCAmelCase__			  =      model(**lowerCamelCase_  )

														# verify the logits
														lowerCAmelCase__			  =      torch.Size((1, 10_00)  )
														self.assertEqual(outputs.logits.shape   ,       lowerCamelCase_  )

														lowerCAmelCase__			  =      torch.tensor([0.9_996, 0.1_966, -0.4_386]  ).to(lowerCamelCase_  )
														self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,       lowerCamelCase_   ,       atol=1e-4  )  )



'''simple docstring'''

import unittest

import numpy as np

def _SCREAMING_SNAKE_CASE (A    ,					A    ,					A    ,					A = None    ,					)			->			np.ndarray:






       """simple docstring"""







       lowercase__      =					np.shape(A			)
       lowercase__      =					np.shape(A			)
       lowercase__      =					np.shape(A			)

       if shape_a[0] != shape_b[0]:
              lowercase__      =					(
                  '''Expected the same number of rows for A and B. '''
                  f"Instead found A of size {shape_a} and B of size {shape_b}"
              )
              raise ValueError(A			)

       if shape_b[1] != shape_c[1]:
              lowercase__      =					(
                  '''Expected the same number of columns for B and C. '''
                  f"Instead found B of size {shape_b} and C of size {shape_c}"
              )
              raise ValueError(A			)

       lowercase__      =					pseudo_inv
       if a_inv is None:
              try:
                     lowercase__      =					np.linalg.inv(A			)
              except np.linalg.LinAlgError:
                     raise ValueError(
                         '''Input matrix A is not invertible. Cannot compute Schur complement.'''			)

       return mat_c - mat_b.T @ a_inv @ mat_b
class     __lowerCAmelCase		(unittest.TestCase	):





      '''simple docstring'''






      def  UpperCamelCase__						(self       :       Dict					):

             '''simple docstring'''







             lowercase__      =					np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]					)
             lowercase__      =					np.array([[0, 3], [3, 0], [2, 3]]					)
             lowercase__      =					np.array([[2, 1], [6, 3]]					)

             lowercase__      =					schur_complement(UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)

             lowercase__      =					np.block([[a, b], [b.T, c]]					)

             lowercase__      =					np.linalg.det(UpperCamelCase					)
             lowercase__      =					np.linalg.det(UpperCamelCase					)
             lowercase__      =					np.linalg.det(UpperCamelCase					)

             self.assertAlmostEqual(UpperCamelCase  ,		det_a * det_s					)



      def  UpperCamelCase__						(self       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]					)
             lowercase__      =					np.array([[0, 3], [3, 0], [2, 3]]					)
             lowercase__      =					np.array([[2, 1], [6, 3]]					)

             with self.assertRaises(UpperCamelCase					):
                    schur_complement(UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)






      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             lowercase__      =					np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]					)
             lowercase__      =					np.array([[0, 3], [3, 0], [2, 3]]					)
             lowercase__      =					np.array([[2, 1, 3], [6, 3, 5]]					)

             with self.assertRaises(UpperCamelCase					):
                    schur_complement(UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 unittest.main()




