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







     """simple docstring"""






     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.0_2     ,			_lowerCamelCase=["stage2", "stage3", "stage4"]     ,			_lowerCamelCase=[2, 3, 4]     ,			_lowerCamelCase=None     ,			):
         __UpperCamelCase	:	str		    =  parent
         __UpperCamelCase	:	Optional[Any]		    =  batch_size
         __UpperCamelCase	:	Union[str, Any]		    =  image_size
         __UpperCamelCase	:	Dict		    =  num_channels
         __UpperCamelCase	:	Union[str, Any]		    =  num_stages
         __UpperCamelCase	:	Union[str, Any]		    =  hidden_sizes
         __UpperCamelCase	:	Optional[int]		    =  depths
         __UpperCamelCase	:	Optional[Any]		    =  is_training
         __UpperCamelCase	:	Optional[int]		    =  use_labels
         __UpperCamelCase	:	Tuple		    =  intermediate_size
         __UpperCamelCase	:	List[Any]		    =  hidden_act
         __UpperCamelCase	:	int		    =  num_labels
         __UpperCamelCase	:	List[Any]		    =  initializer_range
         __UpperCamelCase	:	int		    =  out_features
         __UpperCamelCase	:	Optional[Any]		    =  out_indices
         __UpperCamelCase	:	Optional[int]		    =  scope







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	int		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

         __UpperCamelCase	:	Optional[Any]		    =  self.get_config()

         return config, pixel_values, labels







     def lowerCAmelCase     (		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=__lowerCamelCase     ,			initializer_range=self.initializer_range     ,			out_features=self.out_features     ,			out_indices=self.out_indices     ,			num_labels=self.num_labels     ,			)







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	int		    =  ConvNextVaModel(config=__lowerCamelCase    )
         model.to(__lowerCamelCase    )
         model.eval()
         __UpperCamelCase	:	List[Any]		    =  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 lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	List[Any]		    =  ConvNextVaForImageClassification(__lowerCamelCase    )
         model.to(__lowerCamelCase    )
         model.eval()
         __UpperCamelCase	:	List[str]		    =  model(__lowerCamelCase     ,			labels=__lowerCamelCase    )
         self.parent.assertEqual(result.logits.shape     ,			(self.batch_size, self.num_labels)    )







     def lowerCAmelCase     (		self     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	Dict		    =  ConvNextVaBackbone(config=__lowerCamelCase    )
         model.to(__lowerCamelCase    )
         model.eval()
         __UpperCamelCase	:	int		    =  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
         __UpperCamelCase	:	Optional[int]		    =  None
         __UpperCamelCase	:	Union[str, Any]		    =  ConvNextVaBackbone(config=__lowerCamelCase    )
         model.to(__lowerCamelCase    )
         model.eval()
         __UpperCamelCase	:	Any		    =  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 lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Any		    =  self.prepare_config_and_inputs()
         __UpperCamelCase	:	int		    =  config_and_inputs
         __UpperCamelCase	:	Tuple		    =  {'''pixel_values''': pixel_values}
         return config, inputs_dict







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  self.prepare_config_and_inputs()
         __UpperCamelCase	:	Optional[int]		    =  config_and_inputs
         __UpperCamelCase	:	List[Any]		    =  {'''pixel_values''': pixel_values, '''labels''': labels}
         return config, inputs_dict






@require_torch
class 			__lowercase		(						lowerCamelCase__			,							lowerCamelCase__			,							unittest.TestCase						):







     """simple docstring"""






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

     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						False







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Any		    =  ConvNextVaModelTester(self    )
         __UpperCamelCase	:	Optional[int]		    =  ConfigTester(self     ,			config_class=__lowerCamelCase     ,			has_text_modality=__lowerCamelCase     ,			hidden_size=3_7    )







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







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







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







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







     def lowerCAmelCase     (		self    ):






         if not self.model_tester.is_training:
             return

         for model_class in self.all_model_classes:
             __UpperCamelCase	:	Any		    =  self.model_tester.prepare_config_and_inputs_with_labels()
             __UpperCamelCase	:	Any		    =  True

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

             __UpperCamelCase	:	Any		    =  model_class(__lowerCamelCase    )
             model.to(__lowerCamelCase    )
             model.train()
             __UpperCamelCase	:	Any		    =  self._prepare_for_class(__lowerCamelCase     ,			__lowerCamelCase     ,			return_labels=__lowerCamelCase    )
             __UpperCamelCase	:	str		    =  model(**__lowerCamelCase    ).loss
             loss.backward()







     def lowerCAmelCase     (		self    ):






         if not self.model_tester.is_training:
             return

         for model_class in self.all_model_classes:
             __UpperCamelCase	:	List[Any]		    =  self.model_tester.prepare_config_and_inputs_with_labels()
             __UpperCamelCase	:	Tuple		    =  False
             __UpperCamelCase	:	int		    =  True

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

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  self.model_tester.prepare_config_and_inputs_for_common()

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

             __UpperCamelCase	:	Optional[Any]		    =  ['''pixel_values''']
             self.assertListEqual(arg_names[:1]     ,			__lowerCamelCase    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase    )







     def lowerCAmelCase     (		self    ):






         def check_hidden_states_output(_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase    ):
             __UpperCamelCase	:	int		    =  model_class(__lowerCamelCase    )
             model.to(__lowerCamelCase    )
             model.eval()

             with torch.no_grad():
                 __UpperCamelCase	:	Dict		    =  model(**self._prepare_for_class(__lowerCamelCase     ,			__lowerCamelCase    )    )

             __UpperCamelCase	:	List[Any]		    =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             __UpperCamelCase	:	Optional[int]		    =  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]     ,			)

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

         for model_class in self.all_model_classes:
             __UpperCamelCase	:	Tuple		    =  True
             check_hidden_states_output(__lowerCamelCase     ,			__lowerCamelCase     ,			__lowerCamelCase    )

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

             check_hidden_states_output(__lowerCamelCase     ,			__lowerCamelCase     ,			__lowerCamelCase    )







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Optional[int]		    =  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase    )







     @slow
     def lowerCAmelCase     (		self    ):






         for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __UpperCamelCase	:	Dict		    =  ConvNextVaModel.from_pretrained(__lowerCamelCase    )
             self.assertIsNotNone(__lowerCamelCase    )







def  _UpperCamelCase (     ):




    """simple docstring"""



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






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







     """simple docstring"""






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







     @slow
     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	str		    =  ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'    ).to(__lowerCamelCase    )

         __UpperCamelCase	:	str		    =  self.default_image_processor
         __UpperCamelCase	:	str		    =  prepare_img()
         __UpperCamelCase	:	List[str]		    =  preprocessor(images=__lowerCamelCase     ,			return_tensors='pt'    ).to(__lowerCamelCase    )

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

         # verify the logits
         __UpperCamelCase	:	Any		    =  torch.Size((1, 1_0_0_0)    )
         self.assertEqual(outputs.logits.shape     ,			__lowerCamelCase    )

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


'''simple docstring'''
import os
import unittest

from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast
from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin






@require_tokenizers
class 			__lowercase		(						_lowerCamelCase			,							unittest.TestCase						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						LayoutLMTokenizer
     SCREAMING_SNAKE_CASE__		   =						LayoutLMTokenizerFast
     SCREAMING_SNAKE_CASE__		   =						True
     SCREAMING_SNAKE_CASE__		   =						True







     def lowerCAmelCase     (		self    ):
         super().setUp()

         __UpperCamelCase	:	List[str]		    =  [
             '[UNK]',
             '[CLS]',
             '[SEP]',
             'want',
             '##want',
             '##ed',
             'wa',
             'un',
             'runn',
             '##ing',
             ',',
             'low',
             'lowest',
         ]
         __UpperCamelCase	:	Union[str, Any]		    =  os.path.join(self.tmpdirname     ,			VOCAB_FILES_NAMES['vocab_file']    )
         with open(self.vocab_file     ,			'w'     ,			encoding='utf-8'    ) as vocab_writer:
             vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]    )    )







     def lowerCAmelCase     (		self     ,			**_lowerCamelCase    ):
         return LayoutLMTokenizer.from_pretrained(self.tmpdirname     ,			**_lowerCamelCase    )







     def lowerCAmelCase     (		self     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	Dict		    =  'UNwant\u00E9d,running'
         __UpperCamelCase	:	Union[str, Any]		    =  'unwanted, running'
         return input_text, output_text







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Dict		    =  self.tokenizer_class(self.vocab_file    )

         __UpperCamelCase	:	Optional[Any]		    =  tokenizer.tokenize('UNwant\u00E9d,running'    )
         self.assertListEqual(_lowerCamelCase     ,			['un', '##want', '##ed', ',', 'runn', '##ing']    )
         self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase    )     ,			[7, 4, 5, 1_0, 8, 9]    )







     def lowerCAmelCase     (		self    ):
         pass



