



import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
			from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileViTImageProcessor



class     _UpperCAmelCase			(       _lowerCAmelCase     ):




					def 		snake_case_		(				self):
									A__		 =					self.config_class(**self.inputs_dict)
									self.parent.assertTrue(hasattr(_lowerCAmelCase ,						'''hidden_sizes'''))
									self.parent.assertTrue(hasattr(_lowerCAmelCase ,						'''neck_hidden_sizes'''))
									self.parent.assertTrue(hasattr(_lowerCAmelCase ,						'''num_attention_heads'''))







class     _UpperCAmelCase			:




					def __init__(				self ,						a__ ,						a__=1_3 ,						a__=3_2 ,						a__=2 ,						a__=3 ,						a__=6_4_0 ,						a__=4 ,						a__="silu" ,						a__=3 ,						a__=3_2 ,						a__=0.1 ,						a__=0.1 ,						a__=0.1 ,						a__=0.0_2 ,						a__=True ,						a__=True ,						a__=1_0 ,						a__=None ,						):
									A__		 =					parent
									A__		 =					batch_size
									A__		 =					image_size
									A__		 =					patch_size
									A__		 =					num_channels
									A__		 =					last_hidden_size
									A__		 =					num_attention_heads
									A__		 =					hidden_act
									A__		 =					conv_kernel_size
									A__		 =					output_stride
									A__		 =					hidden_dropout_prob
									A__		 =					attention_probs_dropout_prob
									A__		 =					classifier_dropout_prob
									A__		 =					use_labels
									A__		 =					is_training
									A__		 =					num_labels
									A__		 =					initializer_range
									A__		 =					scope




					def 		snake_case_		(				self):
									A__		 =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

									A__		 =					self.get_config()

									return config, pixel_values, labels, pixel_labels




					def 		snake_case_		(				self):
									return MobileViTConfig(
									    image_size=self.image_size ,						patch_size=self.patch_size ,						num_channels=self.num_channels ,						num_attention_heads=self.num_attention_heads ,						hidden_act=self.hidden_act ,						conv_kernel_size=self.conv_kernel_size ,						output_stride=self.output_stride ,						hidden_dropout_prob=self.hidden_dropout_prob ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob ,						classifier_dropout_prob=self.classifier_dropout_prob ,						initializer_range=self.initializer_range ,						)




					def 		snake_case_		(				self ,						a__ ,						a__ ,						a__ ,						a__):
									A__		 =					MobileViTModel(config=_lowerCAmelCase)
									model.to(_lowerCAmelCase)
									model.eval()
									A__		 =					model(_lowerCAmelCase)
									self.parent.assertEqual(
									    result.last_hidden_state.shape ,						(
									        self.batch_size,
									        self.last_hidden_size,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    ) ,						)




					def 		snake_case_		(				self ,						a__ ,						a__ ,						a__ ,						a__):
									A__		 =					self.num_labels
									A__		 =					MobileViTForImageClassification(_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 ,						a__ ,						a__ ,						a__ ,						a__):
									A__		 =					self.num_labels
									A__		 =					MobileViTForSemanticSegmentation(_lowerCAmelCase)
									model.to(_lowerCAmelCase)
									model.eval()
									A__		 =					model(_lowerCAmelCase)
									self.parent.assertEqual(
									    result.logits.shape ,						(
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    ) ,						)
									A__		 =					model(_lowerCAmelCase ,						labels=_lowerCAmelCase)
									self.parent.assertEqual(
									    result.logits.shape ,						(
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    ) ,						)




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







@require_torch
class     _UpperCAmelCase			(       _lowerCAmelCase			,      _lowerCAmelCase			,      unittest.TestCase     ):
					UpperCamelCase__		    =				(
					    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)
					UpperCamelCase__		    =				(
					    {
					        'feature-extraction': MobileViTModel,
					        'image-classification': MobileViTForImageClassification,
					        'image-segmentation': MobileViTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					UpperCamelCase__		    =				False
					UpperCamelCase__		    =				False
					UpperCamelCase__		    =				False
					UpperCamelCase__		    =				False




					def 		snake_case_		(				self):
									A__		 =					MobileViTModelTester(self)
									A__		 =					MobileViTConfigTester(self ,						config_class=_lowerCAmelCase ,						has_text_modality=_lowerCAmelCase)




					def 		snake_case_		(				self):
									self.config_tester.run_common_tests()




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




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




					@unittest.skip(reason='''MobileViT does not output attentions''')
					def 		snake_case_		(				self):
									pass




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




					@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
					def 		snake_case_		(				self):
									pass




					def 		snake_case_		(				self):
									A__		 =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowerCAmelCase)




					def 		snake_case_		(				self):







									def check_hidden_states_output(a__ ,						a__ ,						a__):
													A__		 =					model_class(_lowerCAmelCase)
													model.to(_lowerCAmelCase)
													model.eval()

													with torch.no_grad():
																	A__		 =					model(**self._prepare_for_class(_lowerCAmelCase ,						_lowerCAmelCase))

													A__		 =					outputs.hidden_states

													A__		 =					5
													self.assertEqual(len(_lowerCAmelCase) ,						_lowerCAmelCase)

													# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
													# with the width and height being successively divided by 2.
													A__		 =					2
													for i in range(len(_lowerCAmelCase)):
																	self.assertListEqual(
																	    list(hidden_states[i].shape[-2:]) ,						[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] ,						)
																	divisor *= 2

													self.assertEqual(self.model_tester.output_stride ,						divisor // 2)

									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):
									A__		 =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase)




					def 		snake_case_		(				self):
									A__		 =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCAmelCase)




					@slow
					def 		snake_case_		(				self):







									for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													A__		 =					MobileViTModel.from_pretrained(_lowerCAmelCase)
													self.assertIsNotNone(_lowerCAmelCase)







def 		lowerCAmelCase__    (					)->  Union[str, Any]:
				A__		 =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
				return image



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




					@cached_property
					def 		snake_case_		(				self):
									return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small''') if is_vision_available() else None




					@slow
					def 		snake_case_		(				self):
									A__		 =					MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small''').to(_lowerCAmelCase)

									A__		 =					self.default_image_processor
									A__		 =					prepare_img()
									A__		 =					image_processor(images=_lowerCAmelCase ,						return_tensors='''pt''').to(_lowerCAmelCase)

									# forward pass
									with torch.no_grad():
													A__		 =					model(**_lowerCAmelCase)

									# verify the logits
									A__		 =					torch.Size((1, 1_0_0_0))
									self.assertEqual(outputs.logits.shape ,						_lowerCAmelCase)

									A__		 =					torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]).to(_lowerCAmelCase)

									self.assertTrue(torch.allclose(outputs.logits[0, :3] ,						_lowerCAmelCase ,						atol=1e-4))




					@slow
					def 		snake_case_		(				self):
									A__		 =					MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''')
									A__		 =					model.to(_lowerCAmelCase)

									A__		 =					MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''')

									A__		 =					prepare_img()
									A__		 =					image_processor(images=_lowerCAmelCase ,						return_tensors='''pt''').to(_lowerCAmelCase)

									# forward pass
									with torch.no_grad():
													A__		 =					model(**_lowerCAmelCase)
									A__		 =					outputs.logits

									# verify the logits
									A__		 =					torch.Size((1, 2_1, 3_2, 3_2))
									self.assertEqual(logits.shape ,						_lowerCAmelCase)

									A__		 =					torch.tensor(
									    [
									        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
									        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
									        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
									    ] ,						device=_lowerCAmelCase ,						)

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




					@slow
					def 		snake_case_		(				self):
									A__		 =					MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''')
									A__		 =					model.to(_lowerCAmelCase)

									A__		 =					MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small''')

									A__		 =					prepare_img()
									A__		 =					image_processor(images=_lowerCAmelCase ,						return_tensors='''pt''').to(_lowerCAmelCase)

									# forward pass
									with torch.no_grad():
													A__		 =					model(**_lowerCAmelCase)

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

									A__		 =					image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase ,						target_sizes=[(5_0, 6_0)])
									A__		 =					torch.Size((5_0, 6_0))
									self.assertEqual(segmentation[0].shape ,						_lowerCAmelCase)

									A__		 =					image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase)
									A__		 =					torch.Size((3_2, 3_2))
									self.assertEqual(segmentation[0].shape ,						_lowerCAmelCase)





import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


_lowercase						  =		logging.get_logger(__name__)

_lowercase						  =		"▁"

_lowercase						  =		{"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"}

_lowercase						  =		{
    "sentencepiece_model_file": "sentencepiece.bpe.model",
    "vocab_file": "vocab.txt",
}

_lowercase						  =		{
    "vocab_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt",
    },
    "sentencepiece_model_file": {
        "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
        "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model",
    },
}

_lowercase						  =		{
    "ernie-m-base": 514,
    "ernie-m-large": 514,
}

_lowercase						  =		{
    "ernie-m-base": {"do_lower_case": False},
    "ernie-m-large": {"do_lower_case": False},
}



class     _UpperCAmelCase			(       A__     ):
     UpperCamelCase__		    =				["input_ids"]

     UpperCamelCase__		    =				VOCAB_FILES_NAMES
     UpperCamelCase__		    =				PRETRAINED_INIT_CONFIGURATION
     UpperCamelCase__		    =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     UpperCamelCase__		    =				PRETRAINED_VOCAB_FILES_MAP
     UpperCamelCase__		    =				RESOURCE_FILES_NAMES




     def __init__(				self ,						a__ ,						a__=None ,						a__=False ,						a__="utf8" ,						a__="[UNK]" ,						a__="[SEP]" ,						a__="[PAD]" ,						a__="[CLS]" ,						a__="[MASK]" ,						a__ = None ,						**a__ ,						):
         # Mask token behave like a normal word, i.e. include the space before it and
         # is included in the raw text, there should be a match in a non-normalized sentence.

         A__		 =					{} if sp_model_kwargs is None else sp_model_kwargs
         super().__init__(
             do_lower_case=a__ ,						unk_token=a__ ,						sep_token=a__ ,						pad_token=a__ ,						cls_token=a__ ,						mask_token=a__ ,						vocab_file=a__ ,						encoding=a__ ,						sp_model_kwargs=self.sp_model_kwargs ,						**a__ ,						)
         A__		 =					do_lower_case
         A__		 =					sentencepiece_model_ckpt
         A__		 =					spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(a__)

         # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
         if vocab_file is not None:
             A__		 =					self.load_vocab(filepath=a__)
         else:
             A__		 =					{self.sp_model.id_to_piece(a__): id for id in range(self.sp_model.get_piece_size())}
         A__		 =					{v: k for k, v in self.vocab.items()}




     def 		snake_case_		(				self ,						a__):
         if text is None:
             return None

         A__		 =					self.tokenize(a__)
         A__ ,	A__		 =					'''''', []

         for i, ch in enumerate(a__):
             if ch in self.SP_CHAR_MAPPING:
                 A__		 =					self.SP_CHAR_MAPPING.get(a__)
             else:
                 A__		 =					unicodedata.normalize('''NFKC''' ,						a__)
             if self.is_whitespace(a__):
                 continue
             normalized_text += ch
             char_mapping.extend([i] * len(a__))

         A__ ,	A__ ,	A__		 =					normalized_text, [], 0

         if self.do_lower_case:
             A__		 =					text.lower()

         for token in split_tokens:
             if token[:1] == "▁":
                 A__		 =					token[1:]
             A__		 =					text[offset:].index(a__) + offset
             A__		 =					start + len(a__)

             token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
             A__		 =					end
         return token_mapping




     @property
     def 		snake_case_		(				self):
         return len(self.vocab)




     def 		snake_case_		(				self):
         return dict(self.vocab ,						**self.added_tokens_encoder)




     def __getstate__(				self):
         A__		 =					self.__dict__.copy()
         A__		 =					None
         return state




     def __setstate__(				self ,						a__):
         A__		 =					d

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

         A__		 =					spm.SentencePieceProcessor(**self.sp_model_kwargs)
         self.sp_model.Load(self.sentencepiece_model_ckpt)




     def 		snake_case_		(				self ,						a__):
         return "".join((self.SP_CHAR_MAPPING.get(a__ ,						a__) for c in text))




     def 		snake_case_		(				self ,						a__ ,						a__=False ,						a__=6_4 ,						a__=0.1):

         if self.sp_model_kwargs.get('''enable_sampling''') is True:
             A__		 =					True
         if self.sp_model_kwargs.get('''alpha''') is not None:
             A__		 =					self.sp_model_kwargs.get('''alpha''')
         if self.sp_model_kwargs.get('''nbest_size''') is not None:
             A__		 =					self.sp_model_kwargs.get('''nbest_size''')

         if not enable_sampling:
             A__		 =					self.sp_model.EncodeAsPieces(a__)
         else:
             A__		 =					self.sp_model.SampleEncodeAsPieces(a__ ,						a__ ,						a__)
         A__		 =					[]
         for pi, piece in enumerate(a__):
             if piece == SPIECE_UNDERLINE:
                 if not pieces[pi + 1].startswith(a__) and pi != 0:
                     new_pieces.append(a__)
                     continue
                 else:
                     continue
             A__		 =					0
             for i, chunk in enumerate(a__):
                 if chunk == SPIECE_UNDERLINE:
                     continue
                 if self.is_ch_char(a__) or self.is_punct(a__):
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                         new_pieces.append(piece[lst_i:i])
                     new_pieces.append(a__)
                     A__		 =					i + 1
                 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                         new_pieces.append(piece[lst_i:i])
                     A__		 =					i
                 elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                     if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                         new_pieces.append(piece[lst_i:i])
                     A__		 =					i
             if len(a__) > lst_i:
                 new_pieces.append(piece[lst_i:])
         return new_pieces




     def 		snake_case_		(				self ,						a__):
         A__		 =					''''''.join(a__).replace(a__ ,						''' ''').strip()
         return out_string




     def 		snake_case_		(				self ,						a__):
         A__		 =					self.convert_ids_to_tokens(a__)
         A__		 =					''''''.join(a__).replace(a__ ,						''' ''').strip()
         return out_string




     def 		snake_case_		(				self ,						a__):
         return self.vocab.get(a__ ,						self.vocab.get(self.unk_token))




     def 		snake_case_		(				self ,						a__):
         return self.reverse_vocab.get(a__ ,						self.unk_token)




     def 		snake_case_		(				self ,						a__ ,						a__=None):
         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 ,						a__ ,						a__=None):
         if offset_mapping_a is None:
             return [(0, 0)] + offset_mapping_a + [(0, 0)]

         return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]




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

         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(a__)) + [1, 1] + ([0] * len(a__)) + [1]
         return [1] + ([0] * len(a__)) + [1]




     def 		snake_case_		(				self ,						a__ ,						a__ = None):
         # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
         if token_ids_a is None:
             # [CLS] X [SEP]
             return (len(a__) + 2) * [0]

         # [CLS] A [SEP] [SEP] B [SEP]
         return [0] * (len(a__) + 1) + [1] * (len(a__) + 3)




     def 		snake_case_		(				self ,						a__):
         if "\u4e00" <= char <= "\u9fff":
             return True
         return False




     def 		snake_case_		(				self ,						a__):
         if ("a" <= char <= "z") or ("A" <= char <= "Z"):
             return True
         return False




     def 		snake_case_		(				self ,						a__):
         if char in ",;:.?!~，；：。？！《》【】":
             return True
         return False




     def 		snake_case_		(				self ,						a__):
         if char == " " or char == "\t" or char == "\n" or char == "\r":
             return True
         if len(a__) == 1:
             A__		 =					unicodedata.category(a__)
             if cat == "Zs":
                 return True
         return False




     def 		snake_case_		(				self ,						a__):
         A__		 =					{}
         with io.open(a__ ,						'''r''' ,						encoding='''utf-8''') as f:
             for index, line in enumerate(a__):
                 A__		 =					line.rstrip('''\n''')
                 A__		 =					int(a__)

         return token_to_idx




     def 		snake_case_		(				self ,						a__ ,						a__ = None):
         A__		 =					0
         if os.path.isdir(a__):
             A__		 =					os.path.join(
                 a__ ,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
         else:
             A__		 =					(filename_prefix + '''-''' if filename_prefix else '''''') + save_directory
         with open(a__ ,						'''w''' ,						encoding='''utf-8''') as writer:
             for token, token_index in sorted(self.vocab.items() ,						key=lambda a__: kv[1]):
                 if index != token_index:
                     logger.warning(
                         F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
                         ''' Please check that the vocabulary is not corrupted!''')
                     A__		 =					token_index
                 writer.write(token + '''\n''')
                 index += 1

         A__		 =					os.path.join(a__ ,						'''sentencepiece.bpe.model''')
         with open(a__ ,						'''wb''') as fi:
             A__		 =					self.sp_model.serialized_model_proto()
             fi.write(a__)

         return (vocab_file,)
