




'''simple docstring'''




import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import (
        MODEL_MAPPING,
        BeitForImageClassification,
        BeitForMaskedImageModeling,
        BeitForSemanticSegmentation,
        BeitModel,
    )
    from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    import PIL
    from PIL import Image

    from transformers import BeitImageProcessor

class     lowerCAmelCase_ :







  '''simple docstring'''







  def __init__(    self     :						Dict    ,		_UpperCAmelCase     :						List[Any]    ,		_UpperCAmelCase     :						str=1_00    ,		_UpperCAmelCase     :						Tuple=13    ,		_UpperCAmelCase     :						Any=30    ,		_UpperCAmelCase     :						Tuple=2    ,		_UpperCAmelCase     :						Optional[Any]=3    ,		_UpperCAmelCase     :						Optional[int]=True    ,		_UpperCAmelCase     :						Optional[int]=True    ,		_UpperCAmelCase     :						List[str]=32    ,		_UpperCAmelCase     :						Dict=4    ,		_UpperCAmelCase     :						List[str]=4    ,		_UpperCAmelCase     :						Any=37    ,		_UpperCAmelCase     :						Optional[int]="gelu"    ,		_UpperCAmelCase     :						int=0.1    ,		_UpperCAmelCase     :						List[str]=0.1    ,		_UpperCAmelCase     :						List[Any]=10    ,		_UpperCAmelCase     :						Optional[Any]=0.02    ,		_UpperCAmelCase     :						Dict=3    ,		_UpperCAmelCase     :						List[Any]=None    ,		_UpperCAmelCase     :						Union[str, Any]=[0, 1, 2, 3]    ,		):






   """simple docstring"""






   UpperCAmelCase__      				=     parent
   UpperCAmelCase__      				=     1_00
   UpperCAmelCase__      				=     batch_size
   UpperCAmelCase__      				=     image_size
   UpperCAmelCase__      				=     patch_size
   UpperCAmelCase__      				=     num_channels
   UpperCAmelCase__      				=     is_training
   UpperCAmelCase__      				=     use_labels
   UpperCAmelCase__      				=     hidden_size
   UpperCAmelCase__      				=     num_hidden_layers
   UpperCAmelCase__      				=     num_attention_heads
   UpperCAmelCase__      				=     intermediate_size
   UpperCAmelCase__      				=     hidden_act
   UpperCAmelCase__      				=     hidden_dropout_prob
   UpperCAmelCase__      				=     attention_probs_dropout_prob
   UpperCAmelCase__      				=     type_sequence_label_size
   UpperCAmelCase__      				=     initializer_range
   UpperCAmelCase__      				=     scope
   UpperCAmelCase__      				=     out_indices
   UpperCAmelCase__      				=     num_labels

   # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
   UpperCAmelCase__      				=     (image_size // patch_size) ** 2
   UpperCAmelCase__      				=     num_patches + 1


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Dict			):






   """simple docstring"""






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

   UpperCAmelCase__      				=     None
   UpperCAmelCase__      				=     None
   if self.use_labels:
    UpperCAmelCase__      				=     ids_tensor([self.batch_size]    ,		self.type_sequence_label_size			)
    UpperCAmelCase__      				=     ids_tensor([self.batch_size, self.image_size, self.image_size]    ,		self.num_labels			)

   UpperCAmelCase__      				=     self.get_config()

   return config, pixel_values, labels, pixel_labels


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   return BeitConfig(
       vocab_size=self.vocab_size    ,		image_size=self.image_size    ,		patch_size=self.patch_size    ,		num_channels=self.num_channels    ,		hidden_size=self.hidden_size    ,		num_hidden_layers=self.num_hidden_layers    ,		num_attention_heads=self.num_attention_heads    ,		intermediate_size=self.intermediate_size    ,		hidden_act=self.hidden_act    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		is_decoder=snake_case_    ,		initializer_range=self.initializer_range    ,		out_indices=self.out_indices    ,		)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int    ,		_UpperCAmelCase     :						Optional[int]    ,		_UpperCAmelCase     :						List[str]    ,		_UpperCAmelCase     :						Tuple    ,		_UpperCAmelCase     :						str			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitModel(config=snake_case_			)
   model.to(snake_case_			)
   model.eval()
   UpperCAmelCase__      				=     model(snake_case_			)
   self.parent.assertEqual(result.last_hidden_state.shape    ,		(self.batch_size, self.seq_length, self.hidden_size)			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[int]    ,		_UpperCAmelCase     :						int    ,		_UpperCAmelCase     :						Tuple    ,		_UpperCAmelCase     :						Union[str, Any]    ,		_UpperCAmelCase     :						Dict			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForMaskedImageModeling(config=snake_case_			)
   model.to(snake_case_			)
   model.eval()
   UpperCAmelCase__      				=     model(snake_case_			)
   self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.seq_length - 1, self.vocab_size)			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Any    ,		_UpperCAmelCase     :						Any    ,		_UpperCAmelCase     :						Optional[int]    ,		_UpperCAmelCase     :						Union[str, Any]    ,		_UpperCAmelCase     :						Optional[int]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.type_sequence_label_size
   UpperCAmelCase__      				=     BeitForImageClassification(snake_case_			)
   model.to(snake_case_			)
   model.eval()
   UpperCAmelCase__      				=     model(snake_case_    ,		labels=snake_case_			)
   self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)			)

   # test greyscale images
   UpperCAmelCase__      				=     1
   UpperCAmelCase__      				=     BeitForImageClassification(snake_case_			)
   model.to(snake_case_			)
   model.eval()

   UpperCAmelCase__      				=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
   UpperCAmelCase__      				=     model(snake_case_    ,		labels=snake_case_			)
   self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]    ,		_UpperCAmelCase     :						str    ,		_UpperCAmelCase     :						Optional[int]    ,		_UpperCAmelCase     :						str    ,		_UpperCAmelCase     :						str			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.num_labels
   UpperCAmelCase__      				=     BeitForSemanticSegmentation(snake_case_			)
   model.to(snake_case_			)
   model.eval()
   UpperCAmelCase__      				=     model(snake_case_			)
   self.parent.assertEqual(
       result.logits.shape    ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)
   UpperCAmelCase__      				=     model(snake_case_    ,		labels=snake_case_			)
   self.parent.assertEqual(
       result.logits.shape    ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)



  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.prepare_config_and_inputs()
   UpperCAmelCase__      				=     config_and_inputs
   UpperCAmelCase__      				=     {"""pixel_values""": pixel_values}
   return config, inputs_dict

@require_torch
class     lowerCAmelCase_ (			__A      ,	__A      ,	unittest.TestCase ):







  '''simple docstring'''







  lowerCAmelCase_					:       Union[str, Any]					  =    (
      (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  lowerCAmelCase_					:       List[Any]					  =    (
      {
          'feature-extraction': BeitModel,
          'image-classification': BeitForImageClassification,
          'image-segmentation': BeitForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  lowerCAmelCase_					:       Union[str, Any]					  =    False
  lowerCAmelCase_					:       Any					  =    False
  lowerCAmelCase_					:       Tuple					  =    False


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitModelTester(self			)
   UpperCAmelCase__      				=     ConfigTester(self    ,		config_class=snake_case_    ,		has_text_modality=snake_case_    ,		hidden_size=37			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   self.config_tester.run_common_tests()


  @unittest.skip(reason="""BEiT does not use inputs_embeds"""			)
  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   pass


  @require_torch_multi_gpu
  @unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""			)
  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   pass


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[int]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    UpperCAmelCase__      				=     model_class(snake_case_			)
    self.assertIsInstance(model.get_input_embeddings()    ,		(nn.Module)			)
    UpperCAmelCase__      				=     model.get_output_embeddings()
    self.assertTrue(x is None or isinstance(snake_case_    ,		nn.Linear			)			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Any			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs_for_common()

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

    UpperCAmelCase__      				=     ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]    ,		snake_case_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Union[str, Any]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*snake_case_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[int]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_masked_lm(*snake_case_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						str			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*snake_case_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						Optional[Any]			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*snake_case_			)


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   if not self.model_tester.is_training:
    return

   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase__      				=     True

   for model_class in self.all_model_classes:
    # we don't test BeitForMaskedImageModeling
    if model_class in [*get_values(snake_case_			), BeitForMaskedImageModeling]:
     continue

    UpperCAmelCase__      				=     model_class(snake_case_			)
    model.to(snake_case_			)
    model.train()
    UpperCAmelCase__      				=     self._prepare_for_class(snake_case_    ,		snake_case_    ,		return_labels=snake_case_			)
    UpperCAmelCase__      				=     model(**snake_case_			).loss
    loss.backward()


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs_for_common()
   if not self.model_tester.is_training:
    return

   UpperCAmelCase__      				=     False
   UpperCAmelCase__      				=     True

   for model_class in self.all_model_classes:
    # we don't test BeitForMaskedImageModeling
    if (
        model_class in [*get_values(snake_case_			), BeitForMaskedImageModeling]
        or not model_class.supports_gradient_checkpointing
    ):
     continue

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


  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   UpperCAmelCase__      				=     self.model_tester.prepare_config_and_inputs_for_common()

   UpperCAmelCase__      				=     _config_zero_init(snake_case_			)
   for model_class in self.all_model_classes:
    UpperCAmelCase__      				=     model_class(config=snake_case_			)
    for name, param in model.named_parameters():
     # we skip lambda parameters as these require special initial values
     # determined by config.layer_scale_init_value
     if "lambda" in name:
      continue
     if param.requires_grad:
      self.assertIn(
          ((param.data.mean() * 1E9).round() / 1E9).item()    ,		[0.0, 1.0]    ,		msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''    ,		)



  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    UpperCAmelCase__      				=     BeitModel.from_pretrained(snake_case_			)
    self.assertIsNotNone(snake_case_			)

def  _UpperCamelCase   (					):
 '''simple docstring'''





 UpperCAmelCase__      				=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
 return image







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







  '''simple docstring'''







  @cached_property
  def 				SCREAMING_SNAKE_CASE__      (    self     :						List[str]			):






   """simple docstring"""






   return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""			) if is_vision_available() else None


  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						Any			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""			).to(snake_case_			)

   UpperCAmelCase__      				=     self.default_image_processor
   UpperCAmelCase__      				=     prepare_img()
   UpperCAmelCase__      				=     image_processor(images=snake_case_    ,		return_tensors="""pt"""			).pixel_values.to(snake_case_			)

   # prepare bool_masked_pos
   UpperCAmelCase__      				=     torch.ones((1, 1_96)    ,		dtype=torch.bool			).to(snake_case_			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__      				=     model(pixel_values=snake_case_    ,		bool_masked_pos=snake_case_			)
   UpperCAmelCase__      				=     outputs.logits

   # verify the logits
   UpperCAmelCase__      				=     torch.Size((1, 1_96, 81_92)			)
   self.assertEqual(logits.shape    ,		snake_case_			)

   UpperCAmelCase__      				=     torch.tensor(
       [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]			).to(snake_case_			)

   self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]    ,		snake_case_    ,		atol=1E-2			)			)


  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						Dict			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""			).to(snake_case_			)

   UpperCAmelCase__      				=     self.default_image_processor
   UpperCAmelCase__      				=     prepare_img()
   UpperCAmelCase__      				=     image_processor(images=snake_case_    ,		return_tensors="""pt"""			).to(snake_case_			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__      				=     model(**snake_case_			)
   UpperCAmelCase__      				=     outputs.logits

   # verify the logits
   UpperCAmelCase__      				=     torch.Size((1, 10_00)			)
   self.assertEqual(logits.shape    ,		snake_case_			)

   UpperCAmelCase__      				=     torch.tensor([-1.2385, -1.0987, -1.0108]			).to(snake_case_			)

   self.assertTrue(torch.allclose(logits[0, :3]    ,		snake_case_    ,		atol=1E-4			)			)

   UpperCAmelCase__      				=     2_81
   self.assertEqual(logits.argmax(-1			).item()    ,		snake_case_			)


  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						int			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""			).to(
       snake_case_			)

   UpperCAmelCase__      				=     self.default_image_processor
   UpperCAmelCase__      				=     prepare_img()
   UpperCAmelCase__      				=     image_processor(images=snake_case_    ,		return_tensors="""pt"""			).to(snake_case_			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__      				=     model(**snake_case_			)
   UpperCAmelCase__      				=     outputs.logits

   # verify the logits
   UpperCAmelCase__      				=     torch.Size((1, 2_18_41)			)
   self.assertEqual(logits.shape    ,		snake_case_			)

   UpperCAmelCase__      				=     torch.tensor([1.6881, -0.2787, 0.5901]			).to(snake_case_			)

   self.assertTrue(torch.allclose(logits[0, :3]    ,		snake_case_    ,		atol=1E-4			)			)

   UpperCAmelCase__      				=     23_96
   self.assertEqual(logits.argmax(-1			).item()    ,		snake_case_			)


  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						str			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""			)
   UpperCAmelCase__      				=     model.to(snake_case_			)

   UpperCAmelCase__      				=     BeitImageProcessor(do_resize=snake_case_    ,		size=6_40    ,		do_center_crop=snake_case_			)

   UpperCAmelCase__      				=     load_dataset("""hf-internal-testing/fixtures_ade20k"""    ,		split="""test"""			)
   UpperCAmelCase__      				=     Image.open(ds[0]["""file"""]			)
   UpperCAmelCase__      				=     image_processor(images=snake_case_    ,		return_tensors="""pt"""			).to(snake_case_			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__      				=     model(**snake_case_			)
   UpperCAmelCase__      				=     outputs.logits

   # verify the logits
   UpperCAmelCase__      				=     torch.Size((1, 1_50, 1_60, 1_60)			)
   self.assertEqual(logits.shape    ,		snake_case_			)

   UpperCAmelCase__      				=     version.parse(PIL.__version__			) < version.parse("""9.0.0"""			)

   if is_pillow_less_than_a:
    UpperCAmelCase__      				=     torch.tensor(
        [
            [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
            [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
            [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
        ]    ,		device=snake_case_    ,		)
   else:
    UpperCAmelCase__      				=     torch.tensor(
        [
            [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
            [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
            [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
        ]    ,		device=snake_case_    ,		)

   self.assertTrue(torch.allclose(logits[0, :3, :3, :3]    ,		snake_case_    ,		atol=1E-4			)			)



  @slow
  def 				SCREAMING_SNAKE_CASE__      (    self     :						Any			):






   """simple docstring"""






   UpperCAmelCase__      				=     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""			)
   UpperCAmelCase__      				=     model.to(snake_case_			)

   UpperCAmelCase__      				=     BeitImageProcessor(do_resize=snake_case_    ,		size=6_40    ,		do_center_crop=snake_case_			)

   UpperCAmelCase__      				=     load_dataset("""hf-internal-testing/fixtures_ade20k"""    ,		split="""test"""			)
   UpperCAmelCase__      				=     Image.open(ds[0]["""file"""]			)
   UpperCAmelCase__      				=     image_processor(images=snake_case_    ,		return_tensors="""pt"""			).to(snake_case_			)

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__      				=     model(**snake_case_			)

   UpperCAmelCase__      				=     outputs.logits.detach().cpu()

   UpperCAmelCase__      				=     image_processor.post_process_semantic_segmentation(outputs=snake_case_    ,		target_sizes=[(5_00, 3_00)]			)
   UpperCAmelCase__      				=     torch.Size((5_00, 3_00)			)
   self.assertEqual(segmentation[0].shape    ,		snake_case_			)

   UpperCAmelCase__      				=     image_processor.post_process_semantic_segmentation(outputs=snake_case_			)
   UpperCAmelCase__      				=     torch.Size((1_60, 1_60)			)
   self.assertEqual(segmentation[0].shape    ,		snake_case_			)

"""simple docstring"""



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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_UpperCamelCase								=		logging.get_logger(__name__)

_UpperCamelCase								=		{"vocab_file": "sentencepiece.model"}

_UpperCamelCase								=		{
    "vocab_file": {
        "google/rembert": "https://huggingface.co/google/rembert/resolve/main/sentencepiece.model",
    },
}

_UpperCamelCase								=		{
    "google/rembert": 2_56,
}
class 						__UpperCAmelCase    (__A     ):







			'''simple docstring'''
			_UpperCamelCase  :						Dict					     =				VOCAB_FILES_NAMES
			_UpperCamelCase  :						List[str]					     =				PRETRAINED_VOCAB_FILES_MAP
			_UpperCamelCase  :						Any					     =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES





			def __init__(			self   ,      snake_case_   ,      snake_case_=False   ,      snake_case_=True   ,      snake_case_=True   ,      snake_case_="[CLS]"   ,      snake_case_="[SEP]"   ,      snake_case_="[UNK]"   ,      snake_case_="[SEP]"   ,      snake_case_="[PAD]"   ,      snake_case_="[CLS]"   ,      snake_case_="[MASK]"   ,      **snake_case_   ,      ):







										'''simple docstring'''


										super().__init__(
										    do_lower_case=snake_case_   ,      remove_space=snake_case_   ,      keep_accents=snake_case_   ,      bos_token=snake_case_   ,      eos_token=snake_case_   ,      unk_token=snake_case_   ,      sep_token=snake_case_   ,      pad_token=snake_case_   ,      cls_token=snake_case_   ,      mask_token=snake_case_   ,      **snake_case_   ,      )

										A__       :     List[Any]								=			do_lower_case
										A__       :     Dict								=			remove_space
										A__       :     Optional[int]								=			keep_accents
										A__       :     Tuple								=			vocab_file

										A__       :     List[str]								=			spm.SentencePieceProcessor()
										self.sp_model.Load(snake_case_							)





			@property
			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


										return len(self.sp_model							)





			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


										A__       :     Optional[Any]								=			{self.convert_ids_to_tokens(snake_case_							): i for i in range(self.vocab_size							)}
										vocab.update(self.added_tokens_encoder							)
										return vocab





			def __getstate__(			self							):







										'''simple docstring'''


										A__       :     str								=			self.__dict__.copy()
										A__       :     Tuple								=			None
										return state





			def __setstate__(			self   ,      snake_case_							):







										'''simple docstring'''


										A__       :     Dict								=			d
										A__       :     int								=			spm.SentencePieceProcessor()
										self.sp_model.Load(self.vocab_file							)





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_=False							):







										'''simple docstring'''


										A__       :     Tuple								=			self.sp_model.EncodeAsPieces(snake_case_							)
										return pieces





			def 		lowerCamelCase					(			self   ,      snake_case_							):







										'''simple docstring'''


										return self.sp_model.PieceToId(snake_case_							)





			def 		lowerCamelCase					(			self   ,      snake_case_							):







										'''simple docstring'''


										return self.sp_model.IdToPiece(snake_case_							)





			def 		lowerCamelCase					(			self   ,      snake_case_							):







										'''simple docstring'''


										A__       :     str								=			self.sp_model.decode_pieces(snake_case_							)
										return out_string





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_ = None							):







										'''simple docstring'''


										A__       :     List[Any]								=			[self.sep_token_id]
										A__       :     str								=			[self.cls_token_id]
										if token_ids_a is None:
																	return cls + token_ids_a + sep
										return cls + token_ids_a + sep + token_ids_a + sep





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_ = None   ,      snake_case_ = False							):







										'''simple docstring'''


										if already_has_special_tokens:
																	if token_ids_a is not None:
																								raise ValueError(
																								    """You should not supply a second sequence if the provided sequence of """
																								    """ids is already formatted with special tokens for the model."""							)
																	return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

										if token_ids_a is not None:
																	return [1] + ([0] * len(snake_case_							)) + [1] + ([0] * len(snake_case_							)) + [1]
										return [1] + ([0] * len(snake_case_							)) + [1]





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_ = None							):







										'''simple docstring'''


										A__       :     int								=			[self.sep_token_id]
										A__       :     Any								=			[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							) * [0] + len(token_ids_a + sep							) * [1]





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_ = None							):







										'''simple docstring'''


										if not os.path.isdir(snake_case_							):
																	logger.error("""Vocabulary path ({}) should be a directory""".format(snake_case_							)							)
																	return
										A__       :     Any								=			os.path.join(
										    snake_case_   ,      (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]							)

										if os.path.abspath(self.vocab_file							) != os.path.abspath(snake_case_							):
																	copyfile(self.vocab_file   ,      snake_case_							)

										return (out_vocab_file,)





