

'''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					:      Optional[int]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      Any=1_3			,			snake_case_					:      Dict=3_2			,			snake_case_					:      List[Any]=3			,			snake_case_					:      int=4			,			snake_case_					:      List[Any]=[1_0, 2_0, 3_0, 4_0]			,			snake_case_					:      Union[str, Any]=[2, 2, 3, 2]			,			snake_case_					:      List[Any]=True			,			snake_case_					:      Any=True			,			snake_case_					:      Union[str, Any]=3_7			,			snake_case_					:      Dict="gelu"			,			snake_case_					:      str=1_0			,			snake_case_					:      Any=0.0_2			,			snake_case_					:      Union[str, Any]=["stage2", "stage3", "stage4"]			,			snake_case_					:      Union[str, Any]=[2, 3, 4]			,			snake_case_					:      List[str]=None			,			):



								'''simple docstring'''



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







						def       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

								snake_case__						:       Union[str, Any]       						=  None
								if self.use_labels:
										snake_case__						:       List[Any]       						=  ids_tensor([self.batch_size]			,			self.num_labels  )

								snake_case__						:       str       						=  self.get_config()

								return config, pixel_values, labels







						def       __magic_name__							(							self					:      str  ):



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







						def       __magic_name__							(							self					:      Optional[int]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      str			,			snake_case_					:      Any  ):



								'''simple docstring'''



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



								'''simple docstring'''



								snake_case__						:       Union[str, Any]       						=  ConvNextVaForImageClassification(snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       Any       						=  model(snake_case_			,			labels=snake_case_  )
								self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)  )







						def       __magic_name__							(							self					:      Any			,			snake_case_					:      List[str]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      List[Any]  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  ConvNextVaBackbone(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       Any       						=  model(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
								snake_case__						:       List[str]       						=  None
								snake_case__						:       Optional[int]       						=  ConvNextVaBackbone(config=snake_case_  )
								model.to(snake_case_  )
								model.eval()
								snake_case__						:       str       						=  model(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       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								snake_case__						:       Tuple       						=  self.prepare_config_and_inputs()
								snake_case__						,       snake_case__						,       snake_case__						:       int       						=  config_and_inputs
								snake_case__						:       Tuple       						=  {'''pixel_values''': pixel_values}
								return config, inputs_dict







						def       __magic_name__							(							self					:      List[Any]  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  self.prepare_config_and_inputs()
								snake_case__						,       snake_case__						,       snake_case__						:       int       						=  config_and_inputs
								snake_case__						:       Union[str, Any]       						=  {'''pixel_values''': pixel_values, '''labels''': labels}
								return config, inputs_dict





@require_torch
class     a			(				SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase       ):






						"""simple docstring"""




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

						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False
						__UpperCAmelCase			     =    False







						def       __magic_name__							(							self					:      List[Any]  ):



								'''simple docstring'''



								snake_case__						:       List[Any]       						=  ConvNextVaModelTester(self  )
								snake_case__						:       Any       						=  ConfigTester(self			,			config_class=snake_case_			,			has_text_modality=snake_case_			,			hidden_size=3_7  )







						def       __magic_name__							(							self					:      Tuple  ):



								'''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       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								return







						@unittest.skip(reason='''ConvNextV2 does not use inputs_embeds'''  )
						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								pass







						@unittest.skip(reason='''ConvNextV2 does not support input and output embeddings'''  )
						def       __magic_name__							(							self					:      List[str]  ):



								'''simple docstring'''



								pass







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



								'''simple docstring'''



								pass







						def       __magic_name__							(							self					:      Optional[int]  ):



								'''simple docstring'''



								if not self.model_tester.is_training:
										return

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

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

										snake_case__						:       int       						=  model_class(snake_case_  )
										model.to(snake_case_  )
										model.train()
										snake_case__						:       Union[str, Any]       						=  self._prepare_for_class(snake_case_			,			snake_case_			,			return_labels=snake_case_  )
										snake_case__						:       Union[str, Any]       						=  model(**snake_case_  ).loss
										loss.backward()







						def       __magic_name__							(							self					:      Optional[Any]  ):



								'''simple docstring'''



								if not self.model_tester.is_training:
										return

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

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

										snake_case__						:       Tuple       						=  model_class(snake_case_  )
										model.to(snake_case_  )
										model.gradient_checkpointing_enable()
										model.train()
										snake_case__						:       str       						=  self._prepare_for_class(snake_case_			,			snake_case_			,			return_labels=snake_case_  )
										snake_case__						:       Optional[Any]       						=  model(**snake_case_  ).loss
										loss.backward()







						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



								snake_case__						,       snake_case__						:       List[str]       						=  self.model_tester.prepare_config_and_inputs_for_common()

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

										snake_case__						:       Optional[int]       						=  ['''pixel_values''']
										self.assertListEqual(arg_names[:1]			,			snake_case_  )







						def       __magic_name__							(							self					:      str  ):



								'''simple docstring'''



								snake_case__						:       Optional[Any]       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*snake_case_  )







						def       __magic_name__							(							self					:      int  ):



								'''simple docstring'''



								def check_hidden_states_output(snake_case_					:      Optional[int]			,			snake_case_					:      Optional[Any]			,			snake_case_					:      Union[str, Any]  ):
										snake_case__						:       Union[str, Any]       						=  model_class(snake_case_  )
										model.to(snake_case_  )
										model.eval()

										with torch.no_grad():
												snake_case__						:       Dict       						=  model(**self._prepare_for_class(snake_case_			,			snake_case_  )  )

										snake_case__						:       Dict       						=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

										snake_case__						:       List[Any]       						=  self.model_tester.num_stages
										self.assertEqual(len(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]			,			)

								snake_case__						,       snake_case__						:       List[str]       						=  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
										snake_case__						:       List[Any]       						=  True
										check_hidden_states_output(snake_case_			,			snake_case_			,			snake_case_  )

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

										check_hidden_states_output(snake_case_			,			snake_case_			,			snake_case_  )







						def       __magic_name__							(							self					:      Tuple  ):



								'''simple docstring'''



								snake_case__						:       str       						=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*snake_case_  )







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



								'''simple docstring'''



								for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										snake_case__						:       Optional[int]       						=  ConvNextVaModel.from_pretrained(snake_case_  )
										self.assertIsNotNone(snake_case_  )





def 	_a       (				):

		"""simple docstring"""

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





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






						"""simple docstring"""




						@cached_property
						def       __magic_name__							(							self					:      Any  ):



								'''simple docstring'''



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







						@slow
						def       __magic_name__							(							self					:      Dict  ):



								'''simple docstring'''



								snake_case__						:       Any       						=  ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''  ).to(snake_case_  )

								snake_case__						:       int       						=  self.default_image_processor
								snake_case__						:       Dict       						=  prepare_img()
								snake_case__						:       List[str]       						=  preprocessor(images=snake_case_			,			return_tensors='''pt'''  ).to(snake_case_  )

								# forward pass
								with torch.no_grad():
										snake_case__						:       List[Any]       						=  model(**snake_case_  )

								# verify the logits
								snake_case__						:       Optional[Any]       						=  torch.Size((1, 1_0_0_0)  )
								self.assertEqual(outputs.logits.shape			,			snake_case_  )

								snake_case__						:       List[str]       						=  torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]  ).to(snake_case_  )
								self.assertTrue(torch.allclose(outputs.logits[0, :3]			,			snake_case_			,			atol=1e-4  )  )






'''simple docstring'''


from bisect import bisect
from itertools import accumulate




def 	_a       (				__lowerCAmelCase		:      Optional[int]   ,							__lowerCAmelCase		:      Tuple   ,							__lowerCAmelCase		:      List[Any]   ,							__lowerCAmelCase		:      Optional[Any]     ):

		"""simple docstring"""

		snake_case__						:       Any       						=  sorted(zip(__lowerCAmelCase   ,							__lowerCAmelCase     )   ,							key=lambda __lowerCAmelCase     : x[0] / x[1]   ,							reverse=__lowerCAmelCase     )
		snake_case__						,       snake_case__						:       Union[str, Any]       						=  [i[0] for i in r], [i[1] for i in r]
		snake_case__						:       Dict       						=  list(accumulate(__lowerCAmelCase     )     )
		snake_case__						:       Optional[int]       						=  bisect(__lowerCAmelCase   ,							__lowerCAmelCase     )
		return (
		    0
		    if k == 0
		    else sum(vl[:k]     ) + (w - acc[k - 1]) * (vl[k]) / (wt[k])
		    if k != n
		    else sum(vl[:k]     )
		)


if __name__ == "__main__":
					import doctest

					doctest.testmod()



