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






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







       '''simple docstring'''



       __A						=	parent
       __A						=	batch_size
       __A						=	image_size
       __A						=	num_channels
       __A						=	num_stages
       __A						=	hidden_sizes
       __A						=	depths
       __A						=	is_training
       __A						=	use_labels
       __A						=	intermediate_size
       __A						=	hidden_act
       __A						=	num_labels
       __A						=	initializer_range
       __A						=	out_features
       __A						=	out_indices
       __A						=	scope






 def 		lowercase_  (	self     :Any	) ->	str:







       '''simple docstring'''



       __A						=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

       __A						=	self.get_config()

       return config, pixel_values, labels






 def 		lowercase_  (	self     :str	) ->	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=lowerCAmelCase_		, initializer_range=self.initializer_range		, out_features=self.out_features		, out_indices=self.out_indices		, num_labels=self.num_labels		, )






 def 		lowercase_  (	self     :int		, _A     :str		, _A     :Any		, _A     :List[str]	) ->	Tuple:







       '''simple docstring'''



       __A						=	ConvNextVaModel(config=lowerCAmelCase_	)
       model.to(lowerCAmelCase_	)
       model.eval()
       __A						=	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     :str		, _A     :Optional[int]		, _A     :Tuple		, _A     :Tuple	) ->	Dict:







       '''simple docstring'''



       __A						=	ConvNextVaForImageClassification(lowerCAmelCase_	)
       model.to(lowerCAmelCase_	)
       model.eval()
       __A						=	model(lowerCAmelCase_		, labels=lowerCAmelCase_	)
       self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.num_labels)	)






 def 		lowercase_  (	self     :List[str]		, _A     :Dict		, _A     :Any		, _A     :Optional[Any]	) ->	Any:







       '''simple docstring'''



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







       '''simple docstring'''



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






 def 		lowercase_  (	self     :List[str]	) ->	Any:







       '''simple docstring'''



       __A						=	self.prepare_config_and_inputs()
       __A		,					__A		,					__A						=	config_and_inputs
       __A						=	{'pixel_values': pixel_values, 'labels': labels}
       return config, inputs_dict


@require_torch
class        UpperCamelCase__     (			__lowerCAmelCase					,   __lowerCAmelCase					,   unittest.TestCase):
 UpperCAmelCase__			:			str   =    (
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase__			:			Optional[int]   =    (
     {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase__			:			List[str]   =    False
 UpperCAmelCase__			:			int   =    False
 UpperCAmelCase__			:			List[str]   =    False
 UpperCAmelCase__			:			Union[str, Any]   =    False
 UpperCAmelCase__			:			str   =    False






 def 		lowercase_  (	self     :int	) ->	Tuple:







       '''simple docstring'''



       __A						=	ConvNextVaModelTester(self	)
       __A						=	ConfigTester(self		, config_class=lowerCAmelCase_		, has_text_modality=lowerCAmelCase_		, hidden_size=37	)






 def 		lowercase_  (	self     :Optional[int]	) ->	List[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     :Tuple	) ->	Optional[Any]:







       '''simple docstring'''



       return






 @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'	)
 def 		lowercase_  (	self     :List[str]	) ->	Dict:







       '''simple docstring'''



       pass






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







       '''simple docstring'''



       pass






 @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'	)
 def 		lowercase_  (	self     :List[Any]	) ->	Union[str, Any]:







       '''simple docstring'''



       pass






 def 		lowercase_  (	self     :int	) ->	int:







       '''simple docstring'''



       if not self.model_tester.is_training:
             return

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

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

             __A						=	model_class(lowerCAmelCase_	)
             model.to(lowerCAmelCase_	)
             model.train()
             __A						=	self._prepare_for_class(lowerCAmelCase_		, lowerCAmelCase_		, return_labels=lowerCAmelCase_	)
             __A						=	model(**lowerCAmelCase_	).loss
             loss.backward()






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







       '''simple docstring'''



       if not self.model_tester.is_training:
             return

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

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

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






 def 		lowercase_  (	self     :Union[str, Any]	) ->	Optional[int]:







       '''simple docstring'''



       __A		,					__A						=	self.model_tester.prepare_config_and_inputs_for_common()

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

             __A						=	['pixel_values']
             self.assertListEqual(arg_names[:1]		, lowerCAmelCase_	)






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







       '''simple docstring'''



       __A						=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCAmelCase_	)






 def 		lowercase_  (	self     :Tuple	) ->	Any:







       '''simple docstring'''



       def check_hidden_states_output(_A     :Union[str, Any]		, _A     :List[str]		, _A     :Dict	):
             __A						=	model_class(lowerCAmelCase_	)
             model.to(lowerCAmelCase_	)
             model.eval()

             with torch.no_grad():
                   __A						=	model(**self._prepare_for_class(lowerCAmelCase_		, lowerCAmelCase_	)	)

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

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

       for model_class in self.all_model_classes:
             __A						=	True
             check_hidden_states_output(lowerCAmelCase_		, lowerCAmelCase_		, lowerCAmelCase_	)

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

             check_hidden_states_output(lowerCAmelCase_		, lowerCAmelCase_		, lowerCAmelCase_	)






 def 		lowercase_  (	self     :Dict	) ->	Optional[Any]:







       '''simple docstring'''



       __A						=	self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_	)






 @slow
 def 		lowercase_  (	self     :Optional[Any]	) ->	str:







       '''simple docstring'''



       for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __A						=	ConvNextVaModel.from_pretrained(lowerCAmelCase_	)
             self.assertIsNotNone(lowerCAmelCase_	)





def 				snake_case							(						)->	List[str]:







      """simple docstring"""
      __A						=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
      return image


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






 @cached_property
 def 		lowercase_  (	self     :List[str]	) ->	Optional[int]:







       '''simple docstring'''



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






 @slow
 def 		lowercase_  (	self     :Optional[int]	) ->	Optional[Any]:







       '''simple docstring'''



       __A						=	ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'	).to(lowerCAmelCase_	)

       __A						=	self.default_image_processor
       __A						=	prepare_img()
       __A						=	preprocessor(images=lowerCAmelCase_		, return_tensors='pt'	).to(lowerCAmelCase_	)

       # forward pass
       with torch.no_grad():
             __A						=	model(**lowerCAmelCase_	)

       # verify the logits
       __A						=	torch.Size((1, 1_000)	)
       self.assertEqual(outputs.logits.shape		, lowerCAmelCase_	)

       __A						=	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	)	)







def  snake_case  (       snake_case__			:str = "The quick brown fox jumps over the lazy dog"   ,	)						->   bool:
       _A        =  set()

       # Replace all the whitespace in our sentence
       _A        =  input_str.replace(""" """   ,	"""""")
       for alpha in input_str:
              if "a" <= alpha.lower() <= "z":
                     frequency.add(alpha.lower())
       return len(snake_case__) == 26






def  snake_case  (       snake_case__			:str = "The quick brown fox jumps over the lazy dog"   ,	)						->   bool:
       _A        =  [False] * 26
       for char in input_str:
              if char.islower():
                     _A        =  True
              elif char.isupper():
                     _A        =  True
       return all(snake_case__)






def  snake_case  (       snake_case__			:str = "The quick brown fox jumps over the lazy dog"   ,	)						->   bool:
       return len({char for char in input_str.lower() if char.isalpha()}) == 26






def  snake_case  (       )						->   None:
       from timeit import timeit

       _A        =  """from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"""
       print(timeit("""is_pangram()"""   ,	setup=snake_case__))
       print(timeit("""is_pangram_faster()"""   ,	setup=snake_case__))
       print(timeit("""is_pangram_fastest()"""   ,	setup=snake_case__))
       # 5.348480500048026, 2.6477354579837993, 1.8470395830227062
       # 5.036091582966037, 2.644472333951853,  1.8869528750656173


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    benchmark()




