






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 ,						):
											_lowercase							:   Any 							=   parent
											_lowercase							:   Tuple 							=   batch_size
											_lowercase							:   int 							=   image_size
											_lowercase							:   Union[str, Any] 							=   num_channels
											_lowercase							:   str 							=   num_stages
											_lowercase							:   List[str] 							=   hidden_sizes
											_lowercase							:   Union[str, Any] 							=   depths
											_lowercase							:   Dict 							=   is_training
											_lowercase							:   Dict 							=   use_labels
											_lowercase							:   Tuple 							=   intermediate_size
											_lowercase							:   Optional[int] 							=   hidden_act
											_lowercase							:   Optional[int] 							=   num_labels
											_lowercase							:   Optional[Any] 							=   initializer_range
											_lowercase							:   str 							=   out_features
											_lowercase							:   Any 							=   out_indices
											_lowercase							:   int 							=   scope


				def 						__a					(					self      ):
											_lowercase							:   List[str] 							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

											_lowercase							:   Union[str, Any] 							=   self.get_config()

											return config, pixel_values, labels


				def 						__a					(					self      ):
											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 ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
											_lowercase							:   Dict 							=   ConvNextVaModel(config=__SCREAMING_SNAKE_CASE      )
											model.to(__SCREAMING_SNAKE_CASE      )
											model.eval()
											_lowercase							:   Union[str, 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 // 3_2, self.image_size // 3_2) ,						)


				def 						__a					(					self ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
											_lowercase							:   Dict 							=   ConvNextVaForImageClassification(__SCREAMING_SNAKE_CASE      )
											model.to(__SCREAMING_SNAKE_CASE      )
											model.eval()
											_lowercase							:   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 ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
											_lowercase							:   Dict 							=   ConvNextVaBackbone(config=__SCREAMING_SNAKE_CASE      )
											model.to(__SCREAMING_SNAKE_CASE      )
											model.eval()
											_lowercase							:   int 							=   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
											_lowercase							:   Optional[int] 							=   None
											_lowercase							:   int 							=   ConvNextVaBackbone(config=__SCREAMING_SNAKE_CASE      )
											model.to(__SCREAMING_SNAKE_CASE      )
											model.eval()
											_lowercase							:   List[Any] 							=   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      ):
											_lowercase							:   Union[str, Any] 							=   self.prepare_config_and_inputs()
											_lowercase							,							_lowercase							,							_lowercase							:   Optional[int] 							=   config_and_inputs
											_lowercase							:   str 							=   {'pixel_values': pixel_values}
											return config, inputs_dict


				def 						__a					(					self      ):
											_lowercase							:   Any 							=   self.prepare_config_and_inputs()
											_lowercase							,							_lowercase							,							_lowercase							:   List[Any] 							=   config_and_inputs
											_lowercase							:   List[str] 							=   {'pixel_values': pixel_values, 'labels': labels}
											return config, inputs_dict




@require_torch
class 				lowerCAmelCase_	(		__snake_case   ,		__snake_case   ,		unittest.TestCase			):
				_UpperCamelCase					:       Optional[Any]							       = (
				    (
				        ConvNextVaModel,
				        ConvNextVaForImageClassification,
				        ConvNextVaBackbone,
				    )
				    if is_torch_available()
				    else ()
				)
				_UpperCamelCase					:       int							       = (
				    {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
				    if is_torch_available()
				    else {}
				)

				_UpperCamelCase					:       int							       = False
				_UpperCamelCase					:       Optional[Any]							       = False
				_UpperCamelCase					:       str							       = False
				_UpperCamelCase					:       Union[str, Any]							       = False
				_UpperCamelCase					:       Optional[Any]							       = False


				def 						__a					(					self      ):
											_lowercase							:   Union[str, Any] 							=   ConvNextVaModelTester(self      )
											_lowercase							:   Dict 							=   ConfigTester(self ,						config_class=__SCREAMING_SNAKE_CASE ,						has_text_modality=__SCREAMING_SNAKE_CASE ,						hidden_size=3_7      )


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


				@unittest.skip(reason='ConvNextV2 does not use inputs_embeds'      )
				def 						__a					(					self      ):
											pass


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


				@unittest.skip(reason='ConvNextV2 does not use feedforward chunking'      )
				def 						__a					(					self      ):
											pass


				def 						__a					(					self      ):
											if not self.model_tester.is_training:
																		return

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

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

																		_lowercase							:   Optional[Any] 							=   model_class(__SCREAMING_SNAKE_CASE      )
																		model.to(__SCREAMING_SNAKE_CASE      )
																		model.train()
																		_lowercase							:   Dict 							=   self._prepare_for_class(__SCREAMING_SNAKE_CASE ,						__SCREAMING_SNAKE_CASE ,						return_labels=__SCREAMING_SNAKE_CASE      )
																		_lowercase							:   int 							=   model(**__SCREAMING_SNAKE_CASE      ).loss
																		loss.backward()


				def 						__a					(					self      ):
											if not self.model_tester.is_training:
																		return

											for model_class in self.all_model_classes:
																		_lowercase							,							_lowercase							:   Optional[Any] 							=   self.model_tester.prepare_config_and_inputs_with_labels()
																		_lowercase							:   Tuple 							=   False
																		_lowercase							:   Optional[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

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


				def 						__a					(					self      ):
											_lowercase							,							_lowercase							:   Tuple 							=   self.model_tester.prepare_config_and_inputs_for_common()

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

																		_lowercase							:   Any 							=   ['pixel_values']
																		self.assertListEqual(arg_names[:1] ,						__SCREAMING_SNAKE_CASE      )


				def 						__a					(					self      ):
											_lowercase							:   Dict 							=   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE      )


				def 						__a					(					self      ):
											def check_hidden_states_output(_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
																		_lowercase							:   Union[str, Any] 							=   model_class(__SCREAMING_SNAKE_CASE      )
																		model.to(__SCREAMING_SNAKE_CASE      )
																		model.eval()

																		with torch.no_grad():
																									_lowercase							:   Optional[int] 							=   model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE ,						__SCREAMING_SNAKE_CASE      )      )

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

																		_lowercase							:   int 							=   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] ,						)

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

											for model_class in self.all_model_classes:
																		_lowercase							:   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"]
																		_lowercase							:   Optional[int] 							=   True

																		check_hidden_states_output(__SCREAMING_SNAKE_CASE ,						__SCREAMING_SNAKE_CASE ,						__SCREAMING_SNAKE_CASE      )


				def 						__a					(					self      ):
											_lowercase							:   List[Any] 							=   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE      )


				@slow
				def 						__a					(					self      ):
											for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		_lowercase							:   List[str] 							=   ConvNextVaModel.from_pretrained(__SCREAMING_SNAKE_CASE      )
																		self.assertIsNotNone(__SCREAMING_SNAKE_CASE      )






def    __magic_name__    (	)     ->    List[Any]:
							_lowercase							:   int 							=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
							return image






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


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


				@slow
				def 						__a					(					self      ):
											_lowercase							:   Any 							=   ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'      ).to(__SCREAMING_SNAKE_CASE      )

											_lowercase							:   Any 							=   self.default_image_processor
											_lowercase							:   List[Any] 							=   prepare_img()
											_lowercase							:   List[Any] 							=   preprocessor(images=__SCREAMING_SNAKE_CASE ,						return_tensors='pt'      ).to(__SCREAMING_SNAKE_CASE      )

											# forward pass
											with torch.no_grad():
																		_lowercase							:   str 							=   model(**__SCREAMING_SNAKE_CASE      )

											# verify the logits
											_lowercase							:   int 							=   torch.Size((1, 1_0_0_0)      )
											self.assertEqual(outputs.logits.shape ,						__SCREAMING_SNAKE_CASE      )

											_lowercase							:   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      )      )












"""simple docstring"""





_SCREAMING_SNAKE_CASE   :							Optional[int]          =		8.314_4598







def 	lowerCamelCase__			(				_lowerCamelCase			:						float						,							_lowerCamelCase			:						float					) ->							float:
  if temperature < 0:
    raise Exception('Temperature cannot be less than 0 K'					)
  if molar_mass <= 0:
    raise Exception('Molar mass cannot be less than or equal to 0 kg/mol'					)
  else:
    return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5


if __name__ == "__main__":
  import doctest

  # run doctest
  doctest.testmod()

  # example
  _SCREAMING_SNAKE_CASE   :							List[Any]          =		300
  _SCREAMING_SNAKE_CASE   :							Dict          =		28
  _SCREAMING_SNAKE_CASE   :							List[str]          =		rms_speed_of_molecule(temperature, molar_mass)
  print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')




