



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



 """simple docstring"""

 def __init__(    self					:					Optional[int]			,						__lowerCAmelCase					:					Optional[int]			,						__lowerCAmelCase					:					Tuple=13			,						__lowerCAmelCase					:					List[str]=32			,						__lowerCAmelCase					:					Optional[int]=3			,						__lowerCAmelCase					:					Optional[int]=4			,						__lowerCAmelCase					:					List[Any]=[10, 20, 30, 40]			,						__lowerCAmelCase					:					str=[2, 2, 3, 2]			,						__lowerCAmelCase					:					Optional[Any]=True			,						__lowerCAmelCase					:					str=True			,						__lowerCAmelCase					:					Optional[Any]=37			,						__lowerCAmelCase					:					Dict="gelu"			,						__lowerCAmelCase					:					List[Any]=10			,						__lowerCAmelCase					:					int=0.02			,						__lowerCAmelCase					:					Any=["stage2", "stage3", "stage4"]			,						__lowerCAmelCase					:					List[Any]=[2, 3, 4]			,						__lowerCAmelCase					:					List[Any]=None			,						)   ->	Optional[int]:
    _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     snake_case_      (    self					:					Any      )   ->	List[Any]:
    _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     snake_case_      (    self					:					Tuple      )   ->	List[str]:
    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     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Any			,						__lowerCAmelCase					:					int			,						__lowerCAmelCase					:					int      )   ->	List[str]:
    _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     snake_case_      (    self					:					List[Any]			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					int			,						__lowerCAmelCase					:					Any      )   ->	Optional[Any]:
    _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     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					int			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					Dict      )   ->	int:
    _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     snake_case_      (    self					:					Any      )   ->	Union[str, Any]:
    _A      =       self.prepare_config_and_inputs()
    _A  ,    _A  ,    _A      =       config_and_inputs
    _A      =       {'''pixel_values''': pixel_values}
    return config, inputs_dict

 def     snake_case_      (    self					:					Optional[int]      )   ->	Optional[Any]:
    _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 	lowerCamelCase__	(       _A							,  _A							,  unittest.TestCase):



 """simple docstring"""

 a__					: Optional[int] =  (
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 a__					: Tuple =  (
     {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 a__					: Optional[Any] =  False
 a__					: Any =  False
 a__					: Dict =  False
 a__					: Optional[Any] =  False
 a__					: Optional[Any] =  False

 def     snake_case_      (    self					:					Optional[int]      )   ->	List[str]:
    _A      =       ConvNextVaModelTester(self      )
    _A      =       ConfigTester(self			,						config_class=__lowerCAmelCase			,						has_text_modality=__lowerCAmelCase			,						hidden_size=37      )

 def     snake_case_      (    self					:					Optional[Any]      )   ->	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     snake_case_      (    self					:					Any      )   ->	str:
    return

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

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

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

 def     snake_case_      (    self					:					int      )   ->	List[Any]:
    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     snake_case_      (    self					:					List[str]      )   ->	Any:
    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     snake_case_      (    self					:					Union[str, Any]      )   ->	str:
    _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     snake_case_      (    self					:					str      )   ->	List[Any]:
    _A      =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase      )

 def     snake_case_      (    self					:					Tuple      )   ->	Any:
    def check_hidden_states_output(__lowerCAmelCase					:					Tuple			,						__lowerCAmelCase					:					int			,						__lowerCAmelCase					:					List[str]      ):
       _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     snake_case_      (    self					:					Optional[int]      )   ->	List[Any]:
    _A      =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase      )

 @slow
 def     snake_case_      (    self					:					List[str]      )   ->	Union[str, Any]:
    for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _A      =       ConvNextVaModel.from_pretrained(__lowerCAmelCase      )
       self.assertIsNotNone(__lowerCAmelCase      )

def 	SCREAMING_SNAKE_CASE_							(	)  ->     Tuple:
   _A      =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
   return image


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



 """simple docstring"""

 @cached_property
 def     snake_case_      (    self					:					List[str]      )   ->	Dict:
    return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224'''      ) if is_vision_available() else None

 @slow
 def     snake_case_      (    self					:					Tuple      )   ->	int:
    _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, 10_00)      )
    self.assertEqual(outputs.logits.shape			,						__lowerCAmelCase      )

    _A      =       torch.tensor([0.9996, 0.1966, -0.4386]      ).to(__lowerCAmelCase      )
    self.assertTrue(torch.allclose(outputs.logits[0, :3]			,						__lowerCAmelCase			,						atol=1E-4      )      )








import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase_		 =					logging.get_logger(__name__)

UpperCAmelCase_		 =					"""▁"""

UpperCAmelCase_		 =					{"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""}

UpperCAmelCase_		 =					{
    """vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""",
    },
    """monolingual_vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""",
    },
}

UpperCAmelCase_		 =					{"""vinai/bartpho-syllable""": 1_0_2_4}


class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 a__					: int =  VOCAB_FILES_NAMES
 a__					: Tuple =  PRETRAINED_VOCAB_FILES_MAP
 a__					: Optional[int] =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 a__					: Tuple =  ["input_ids", "attention_mask"]

 def __init__(    self					:					Union[str, Any]			,						__lowerCAmelCase					:					Dict			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					Union[str, Any]="<s>"			,						__lowerCAmelCase					:					Dict="</s>"			,						__lowerCAmelCase					:					List[Any]="</s>"			,						__lowerCAmelCase					:					Optional[Any]="<s>"			,						__lowerCAmelCase					:					Tuple="<unk>"			,						__lowerCAmelCase					:					int="<pad>"			,						__lowerCAmelCase					:					Optional[Any]="<mask>"			,						__lowerCAmelCase					:					Optional[Dict[str, Any]] = None			,						**__lowerCAmelCase					:					Tuple			,						)   ->	None:
    # Mask token behave like a normal word, i.e. include the space before it
    _A      =       AddedToken(__lowerCAmelCase			,						lstrip=__lowerCAmelCase			,						rstrip=__lowerCAmelCase      ) if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ) else mask_token

    _A      =       {} if sp_model_kwargs is None else sp_model_kwargs

    super().__init__(
        bos_token=__lowerCAmelCase			,						eos_token=__lowerCAmelCase			,						unk_token=__lowerCAmelCase			,						sep_token=__lowerCAmelCase			,						cls_token=__lowerCAmelCase			,						pad_token=__lowerCAmelCase			,						mask_token=__lowerCAmelCase			,						sp_model_kwargs=self.sp_model_kwargs			,						**__lowerCAmelCase			,						)

    _A      =       vocab_file
    _A      =       monolingual_vocab_file
    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.Load(str(__lowerCAmelCase      )      )

    # Load the reduced vocab

    # Keep order of special tokens for backward compatibility
    _A      =       {}
    _A      =       0
    for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
       if str(__lowerCAmelCase      ) not in self.fairseq_tokens_to_ids:
          _A      =       cnt
          cnt += 1
    with open(__lowerCAmelCase			,						'''r'''			,						encoding='''utf-8'''      ) as f:
       for line in f.readlines():
          _A      =       line.strip().split()[0]
          _A      =       len(self.fairseq_tokens_to_ids      )
    if str(__lowerCAmelCase      ) not in self.fairseq_tokens_to_ids:
       _A      =       len(self.fairseq_tokens_to_ids      )

    _A      =       {v: k for k, v in self.fairseq_tokens_to_ids.items()}

 def __getstate__(    self					:					Any      )   ->	List[Any]:
    _A      =       self.__dict__.copy()
    _A      =       None
    _A      =       self.sp_model.serialized_model_proto()
    return state

 def __setstate__(    self					:					Union[str, Any]			,						__lowerCAmelCase					:					Dict      )   ->	List[Any]:
    _A      =       d

    # for backward compatibility
    if not hasattr(self			,						'''sp_model_kwargs'''      ):
       _A      =       {}

    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto      )

 def     snake_case_      (    self					:					Optional[Any]			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:

    if token_ids_a is None:
       return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
    _A      =       [self.cls_token_id]
    _A      =       [self.sep_token_id]
    return cls + token_ids_a + sep + sep + token_ids_a + sep

 def     snake_case_      (    self					:					List[Any]			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None			,						__lowerCAmelCase					:					bool = False      )   ->	List[int]:

    if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=__lowerCAmelCase			,						token_ids_a=__lowerCAmelCase			,						already_has_special_tokens=__lowerCAmelCase      )

    if token_ids_a is None:
       return [1] + ([0] * len(__lowerCAmelCase      )) + [1]
    return [1] + ([0] * len(__lowerCAmelCase      )) + [1, 1] + ([0] * len(__lowerCAmelCase      )) + [1]

 def     snake_case_      (    self					:					Any			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:
    _A      =       [self.sep_token_id]
    _A      =       [self.cls_token_id]

    if token_ids_a is None:
       return len(cls + token_ids_a + sep      ) * [0]
    return len(cls + token_ids_a + sep + sep + token_ids_a + sep      ) * [0]

 @property
 def     snake_case_      (    self					:					Optional[int]      )   ->	Union[str, Any]:
    return len(self.fairseq_ids_to_tokens      )

 def     snake_case_      (    self					:					Dict      )   ->	Optional[Any]:
    _A      =       {self.convert_ids_to_tokens(__lowerCAmelCase      ): i for i in range(self.vocab_size      )}
    vocab.update(self.added_tokens_encoder      )
    return vocab

 def     snake_case_      (    self					:					List[str]			,						__lowerCAmelCase					:					str      )   ->	List[str]:
    return self.sp_model.encode(__lowerCAmelCase			,						out_type=__lowerCAmelCase      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Optional[Any]      )   ->	Dict:
    if token in self.fairseq_tokens_to_ids:
       return self.fairseq_tokens_to_ids[token]
    else:
       return self.unk_token_id

 def     snake_case_      (    self					:					int			,						__lowerCAmelCase					:					Optional[int]      )   ->	List[str]:
    return self.fairseq_ids_to_tokens[index]

 def     snake_case_      (    self					:					List[str]			,						__lowerCAmelCase					:					Union[str, Any]      )   ->	Tuple:
    _A      =       ''''''.join(__lowerCAmelCase      ).replace(__lowerCAmelCase			,						''' '''      ).strip()
    return out_string

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Optional[str] = None      )   ->	Tuple[str]:
    if not os.path.isdir(__lowerCAmelCase      ):
       logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''      )
       return
    _A      =       os.path.join(
        __lowerCAmelCase			,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )
    _A      =       os.path.join(
        __lowerCAmelCase			,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file''']			,						)

    if os.path.abspath(self.vocab_file      ) != os.path.abspath(__lowerCAmelCase      ) and os.path.isfile(self.vocab_file      ):
       copyfile(self.vocab_file			,						__lowerCAmelCase      )
    elif not os.path.isfile(self.vocab_file      ):
       with open(__lowerCAmelCase			,						'''wb'''      ) as fi:
          _A      =       self.sp_model.serialized_model_proto()
          fi.write(__lowerCAmelCase      )

    if os.path.abspath(self.monolingual_vocab_file      ) != os.path.abspath(
        __lowerCAmelCase      ) and os.path.isfile(self.monolingual_vocab_file      ):
       copyfile(self.monolingual_vocab_file			,						__lowerCAmelCase      )
    elif not os.path.isfile(self.monolingual_vocab_file      ):
       with open(__lowerCAmelCase			,						'''w'''			,						encoding='''utf-8'''      ) as fp:
          for token in self.fairseq_tokens_to_ids:
             if token not in self.all_special_tokens:
                fp.write(f'''{str(__lowerCAmelCase      )} \n'''      )

    return out_vocab_file, out_monolingual_vocab_file



