




"""simple docstring"""






import argparse

import requests
import torch

# pip3 install salesforce-lavis
# I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis
from lavis.models import load_model_and_preprocess
from PIL import Image

from transformers import (
    AutoTokenizer,
    BlipaConfig,
    BlipaForConditionalGeneration,
    BlipaProcessor,
    BlipaVisionConfig,
    BlipImageProcessor,
    OPTConfig,
    TaConfig,
)
from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD







def 	_snake_case     (							):
				_lowerCamelCase	:     List[Any]       =       'https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png'
				_lowerCamelCase	:     List[str]       =       Image.open(requests.get(lowercase__				,       stream=lowercase__						).raw						).convert('RGB'						)

				return image







def 	_snake_case     (							lowercase__						):
				_lowerCamelCase	:     Tuple       =       []
				# fmt: off

				# vision encoder
				rename_keys.append(('visual_encoder.cls_token', 'vision_model.embeddings.class_embedding')						)
				rename_keys.append(('visual_encoder.pos_embed', 'vision_model.embeddings.position_embedding')						)
				rename_keys.append(('visual_encoder.patch_embed.proj.weight', 'vision_model.embeddings.patch_embedding.weight')						)
				rename_keys.append(('visual_encoder.patch_embed.proj.bias', 'vision_model.embeddings.patch_embedding.bias')						)
				rename_keys.append(('ln_vision.weight', 'vision_model.post_layernorm.weight')						)
				rename_keys.append(('ln_vision.bias', 'vision_model.post_layernorm.bias')						)

				for i in range(config.vision_config.num_hidden_layers						):
								rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.weight''', f'''vision_model.encoder.layers.{i}.layer_norm1.weight''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.bias''', f'''vision_model.encoder.layers.{i}.layer_norm1.bias''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.weight''', f'''vision_model.encoder.layers.{i}.layer_norm2.weight''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.bias''', f'''vision_model.encoder.layers.{i}.layer_norm2.bias''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.attn.qkv.weight''', f'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.weight''', f'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',)						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.bias''', f'''vision_model.encoder.layers.{i}.self_attn.projection.bias''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc1.weight''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc1.bias''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc2.weight''')						)
								rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc2.bias''')						)

				# QFormer
				rename_keys.append(('Qformer.bert.embeddings.LayerNorm.weight', 'qformer.layernorm.weight')						)
				rename_keys.append(('Qformer.bert.embeddings.LayerNorm.bias', 'qformer.layernorm.bias')						)

				# fmt: on
				return rename_keys







def 	_snake_case     (							lowercase__				,       lowercase__				,       lowercase__						):
				_lowerCamelCase	:     int       =       dct.pop(lowercase__						)
				_lowerCamelCase	:     Optional[Any]       =       val







def 	_snake_case     (							lowercase__				,       lowercase__						):
				for i in range(config.vision_config.num_hidden_layers						):
								# read in original q and v biases
								_lowerCamelCase	:     Any       =       state_dict.pop(f'''visual_encoder.blocks.{i}.attn.q_bias'''						)
								_lowerCamelCase	:     List[str]       =       state_dict.pop(f'''visual_encoder.blocks.{i}.attn.v_bias'''						)

								# next, set bias in the state dict
								_lowerCamelCase	:     Optional[Any]       =       torch.cat((q_bias, torch.zeros_like(lowercase__				,       requires_grad=lowercase__						), v_bias)						)
								_lowerCamelCase	:     Optional[int]       =       qkv_bias







def 	_snake_case     (							lowercase__				,       lowercase__						):
				_lowerCamelCase	:     Tuple       =       364 if 'coco' in model_name else 224
				_lowerCamelCase	:     Any       =       BlipaVisionConfig(image_size=lowercase__						).to_dict()

				# make sure the models have proper bos_token_id and eos_token_id set (important for generation)
				# seems like flan-T5 models don't have bos_token_id properly set?
				if "opt-2.7b" in model_name:
								_lowerCamelCase	:     str       =       OPTConfig.from_pretrained('facebook/opt-2.7b'				,       eos_token_id=lowercase__						).to_dict()
				elif "opt-6.7b" in model_name:
								_lowerCamelCase	:     Union[str, Any]       =       OPTConfig.from_pretrained('facebook/opt-6.7b'				,       eos_token_id=lowercase__						).to_dict()
				elif "t5-xl" in model_name:
								_lowerCamelCase	:     Any       =       TaConfig.from_pretrained('google/flan-t5-xl'				,       dense_act_fn='gelu'				,       bos_token_id=1						).to_dict()
				elif "t5-xxl" in model_name:
								_lowerCamelCase	:     Optional[int]       =       TaConfig.from_pretrained('google/flan-t5-xxl'				,       dense_act_fn='gelu'				,       bos_token_id=1						).to_dict()

				_lowerCamelCase	:     Optional[Any]       =       BlipaConfig(vision_config=lowercase__				,       text_config=lowercase__						)

				return config, image_size







@torch.no_grad()
def 	_snake_case     (							lowercase__				,       lowercase__=None				,       lowercase__=False						):
				_lowerCamelCase	:     Any       =       (
				    AutoTokenizer.from_pretrained('facebook/opt-2.7b'						)
				    if 'opt' in model_name
				    else AutoTokenizer.from_pretrained('google/flan-t5-xl'						)
				)
				_lowerCamelCase	:     int       =       tokenizer('\n'				,       add_special_tokens=lowercase__						).input_ids[0]
				_lowerCamelCase,					_lowerCamelCase	:     Tuple       =       get_blipa_config(lowercase__				,       eos_token_id=lowercase__						)

				_lowerCamelCase	:     int       =       BlipaForConditionalGeneration(lowercase__						).eval()

				_lowerCamelCase	:     Dict       =       {
				    'blip2-opt-2.7b': ('blip2_opt', 'pretrain_opt2.7b'),
				    'blip2-opt-6.7b': ('blip2_opt', 'pretrain_opt6.7b'),
				    'blip2-opt-2.7b-coco': ('blip2_opt', 'caption_coco_opt2.7b'),
				    'blip2-opt-6.7b-coco': ('blip2_opt', 'caption_coco_opt6.7b'),
				    'blip2-flan-t5-xl': ('blip2_t5', 'pretrain_flant5xl'),
				    'blip2-flan-t5-xl-coco': ('blip2_t5', 'caption_coco_flant5xl'),
				    'blip2-flan-t5-xxl': ('blip2_t5', 'pretrain_flant5xxl'),
				}

				_lowerCamelCase,					_lowerCamelCase	:     Dict       =       model_name_to_original[model_name]

				# load original model
				print('Loading original model...'						)
				_lowerCamelCase	:     Optional[Any]       =       'cuda' if torch.cuda.is_available() else 'cpu'
				_lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase	:     Any       =       load_model_and_preprocess(
				    name=lowercase__				,       model_type=lowercase__				,       is_eval=lowercase__				,       device=lowercase__						)
				original_model.eval()
				print('Done!'						)

				# update state dict keys
				_lowerCamelCase	:     Optional[int]       =       original_model.state_dict()
				_lowerCamelCase	:     str       =       create_rename_keys(lowercase__						)
				for src, dest in rename_keys:
								rename_key(lowercase__				,       lowercase__				,       lowercase__						)

				# some keys can be renamed efficiently
				for key, val in state_dict.copy().items():
								_lowerCamelCase	:     List[str]       =       state_dict.pop(lowercase__						)
								if key.startswith('Qformer.bert'						):
												_lowerCamelCase	:     Optional[int]       =       key.replace('Qformer.bert'				,       'qformer'						)
								if "attention.self" in key:
												_lowerCamelCase	:     List[Any]       =       key.replace('self'				,       'attention'						)
								if "opt_proj" in key:
												_lowerCamelCase	:     Optional[Any]       =       key.replace('opt_proj'				,       'language_projection'						)
								if "t5_proj" in key:
												_lowerCamelCase	:     str       =       key.replace('t5_proj'				,       'language_projection'						)
								if key.startswith('opt'						):
												_lowerCamelCase	:     Union[str, Any]       =       key.replace('opt'				,       'language'						)
								if key.startswith('t5'						):
												_lowerCamelCase	:     str       =       key.replace('t5'				,       'language'						)
								_lowerCamelCase	:     Dict       =       val

				# read in qv biases
				read_in_q_v_bias(lowercase__				,       lowercase__						)

				_lowerCamelCase,					_lowerCamelCase	:     Dict       =       hf_model.load_state_dict(lowercase__				,       strict=lowercase__						)
				assert len(lowercase__						) == 0
				assert unexpected_keys == ["qformer.embeddings.position_ids"]

				_lowerCamelCase	:     Optional[int]       =       load_demo_image()
				_lowerCamelCase	:     Union[str, Any]       =       vis_processors['eval'](lowercase__						).unsqueeze(0						).to(lowercase__						)
				_lowerCamelCase	:     str       =       tokenizer(['\n']				,       return_tensors='pt'						).input_ids.to(lowercase__						)

				# create processor
				_lowerCamelCase	:     Dict       =       BlipImageProcessor(
				    size={'height': image_size, 'width': image_size}				,       image_mean=lowercase__				,       image_std=lowercase__						)
				_lowerCamelCase	:     int       =       BlipaProcessor(image_processor=lowercase__				,       tokenizer=lowercase__						)
				_lowerCamelCase	:     Optional[Any]       =       processor(images=lowercase__				,       return_tensors='pt'						).pixel_values.to(lowercase__						)

				# make sure processor creates exact same pixel values
				assert torch.allclose(lowercase__				,       lowercase__						)

				original_model.to(lowercase__						)
				hf_model.to(lowercase__						)
				with torch.no_grad():
								if "opt" in model_name:
												_lowerCamelCase	:     Optional[Any]       =       original_model({'image': original_pixel_values, 'text_input': ['']}						).logits
												_lowerCamelCase	:     int       =       hf_model(lowercase__				,       lowercase__						).logits
								else:
												_lowerCamelCase	:     List[Any]       =       original_model(
												    {'image': original_pixel_values, 'text_input': ['\n'], 'text_output': ['\n']}						).logits
												_lowerCamelCase	:     Union[str, Any]       =       input_ids.masked_fill(input_ids == tokenizer.pad_token_id				,       -100						)
												_lowerCamelCase	:     Optional[int]       =       hf_model(lowercase__				,       lowercase__				,       labels=lowercase__						).logits

				assert original_logits.shape == logits.shape
				print('First values of original logits:'				,       original_logits[0, :3, :3]						)
				print('First values of HF logits:'				,       logits[0, :3, :3]						)

				# assert values
				if model_name == "blip2-flan-t5-xl":
								_lowerCamelCase	:     List[Any]       =       torch.tensor(
								    [[-4_1.5_8_5_0, -4.4_4_4_0, -8.9_9_2_2], [-4_7.4_3_2_2, -5.9_1_4_3, -1.7_3_4_0]]				,       device=lowercase__						)
								assert torch.allclose(logits[0, :3, :3]				,       lowercase__				,       atol=1E-4						)
				elif model_name == "blip2-flan-t5-xl-coco":
								_lowerCamelCase	:     List[str]       =       torch.tensor(
								    [[-5_7.0_1_0_9, -9.8_9_6_7, -1_2.6_2_8_0], [-6_8.6_5_7_8, -1_2.7_1_9_1, -1_0.5_0_6_5]]				,       device=lowercase__						)
				else:
								# cast to same type
								_lowerCamelCase	:     Any       =       logits.dtype
								assert torch.allclose(original_logits.to(lowercase__						)				,       lowercase__				,       atol=1E-2						)
				print('Looks ok!'						)

				print('Generating a caption...'						)
				_lowerCamelCase	:     int       =       ''
				_lowerCamelCase	:     Dict       =       tokenizer(lowercase__				,       return_tensors='pt'						).input_ids.to(lowercase__						)

				_lowerCamelCase	:     Dict       =       original_model.generate({'image': original_pixel_values}						)
				_lowerCamelCase	:     List[Any]       =       hf_model.generate(
				    lowercase__				,       lowercase__				,       do_sample=lowercase__				,       num_beams=5				,       max_length=30				,       min_length=1				,       top_p=0.9				,       repetition_penalty=1.0				,       length_penalty=1.0				,       temperature=1				,       )
				print('Original generation:'				,       lowercase__						)
				_lowerCamelCase	:     Any       =       input_ids.shape[1]
				_lowerCamelCase	:     Optional[int]       =       processor.batch_decode(outputs[:, prompt_length:]				,       skip_special_tokens=lowercase__						)
				_lowerCamelCase	:     Optional[Any]       =       [text.strip() for text in output_text]
				print('HF generation:'				,       lowercase__						)

				if pytorch_dump_folder_path is not None:
								processor.save_pretrained(lowercase__						)
								hf_model.save_pretrained(lowercase__						)

				if push_to_hub:
								processor.push_to_hub(f'''nielsr/{model_name}'''						)
								hf_model.push_to_hub(f'''nielsr/{model_name}'''						)


if __name__ == "__main__":
			lowercase__			=		argparse.ArgumentParser()
			lowercase__			=		[
			    """blip2-opt-2.7b""",
			    """blip2-opt-6.7b""",
			    """blip2-opt-2.7b-coco""",
			    """blip2-opt-6.7b-coco""",
			    """blip2-flan-t5-xl""",
			    """blip2-flan-t5-xl-coco""",
			    """blip2-flan-t5-xxl""",
			]
			parser.add_argument(
			    """--model_name""",
			    default="""blip2-opt-2.7b""",
			    choices=choices,
			    type=str,
			    help="""Path to hf config.json of model to convert""",
			)
			parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
			parser.add_argument(
			    """--push_to_hub""",
			    action="""store_true""",
			    help="""Whether to push the model and processor to the hub after converting""",
			)

			lowercase__			=		parser.parse_args()

			convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





"""simple docstring"""






import os
import unittest

from transformers import MobileBertTokenizer, MobileBertTokenizerFast
from transformers.models.bert.tokenization_bert import (
    VOCAB_FILES_NAMES,
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english






@require_tokenizers
class lowerCAmelCase__      (	lowercase,      unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__ =     MobileBertTokenizer
			lowerCamelCase__ =     MobileBertTokenizerFast
			lowerCamelCase__ =     True
			lowerCamelCase__ =     True
			lowerCamelCase__ =     filter_non_english
			lowerCamelCase__ =     """google/mobilebert-uncased"""
			def    A_       (    self    ):
							super().setUp()

							_lowerCamelCase	:     Optional[int]       =       [
							    '[UNK]',
							    '[CLS]',
							    '[SEP]',
							    '[PAD]',
							    '[MASK]',
							    'want',
							    '##want',
							    '##ed',
							    'wa',
							    'un',
							    'runn',
							    '##ing',
							    ',',
							    'low',
							    'lowest',
							]
							_lowerCamelCase	:     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]    )    )

							_lowerCamelCase	:     Any       =       [
							    (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2])  # else the 'google/' prefix is stripped
							    for tokenizer_def in self.tokenizers_list
							]
			def    A_       (    self    , lowercase    ):
							_lowerCamelCase	:     Union[str, Any]       =       'UNwant\u00E9d,running'
							_lowerCamelCase	:     List[Any]       =       'unwanted, running'
							return input_text, output_text
			def    A_       (    self    ):
							_lowerCamelCase	:     Dict       =       self.tokenizer_class(self.vocab_file    )

							_lowerCamelCase	:     Union[str, Any]       =       tokenizer.tokenize('UNwant\u00E9d,running'    )
							self.assertListEqual(lowercase    , ['un', '##want', '##ed', ',', 'runn', '##ing']    )
							self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase    )    , [9, 6, 7, 12, 10, 11]    )
			def    A_       (    self    ):
							if not self.test_rust_tokenizer:
											return

							_lowerCamelCase	:     Any       =       self.get_tokenizer()
							_lowerCamelCase	:     Any       =       self.get_rust_tokenizer()

							_lowerCamelCase	:     int       =       'UNwant\u00E9d,running'

							_lowerCamelCase	:     Union[str, Any]       =       tokenizer.tokenize(lowercase    )
							_lowerCamelCase	:     List[Any]       =       rust_tokenizer.tokenize(lowercase    )
							self.assertListEqual(lowercase    , lowercase    )

							_lowerCamelCase	:     Dict       =       tokenizer.encode(lowercase    , add_special_tokens=lowercase    )
							_lowerCamelCase	:     Dict       =       rust_tokenizer.encode(lowercase    , add_special_tokens=lowercase    )
							self.assertListEqual(lowercase    , lowercase    )

							_lowerCamelCase	:     Optional[Any]       =       self.get_rust_tokenizer()
							_lowerCamelCase	:     Optional[int]       =       tokenizer.encode(lowercase    )
							_lowerCamelCase	:     List[str]       =       rust_tokenizer.encode(lowercase    )
							self.assertListEqual(lowercase    , lowercase    )

							# With lower casing
							_lowerCamelCase	:     List[Any]       =       self.get_tokenizer(do_lower_case=lowercase    )
							_lowerCamelCase	:     int       =       self.get_rust_tokenizer(do_lower_case=lowercase    )

							_lowerCamelCase	:     Optional[Any]       =       'UNwant\u00E9d,running'

							_lowerCamelCase	:     Dict       =       tokenizer.tokenize(lowercase    )
							_lowerCamelCase	:     int       =       rust_tokenizer.tokenize(lowercase    )
							self.assertListEqual(lowercase    , lowercase    )

							_lowerCamelCase	:     Dict       =       tokenizer.encode(lowercase    , add_special_tokens=lowercase    )
							_lowerCamelCase	:     Dict       =       rust_tokenizer.encode(lowercase    , add_special_tokens=lowercase    )
							self.assertListEqual(lowercase    , lowercase    )

							_lowerCamelCase	:     Any       =       self.get_rust_tokenizer()
							_lowerCamelCase	:     Union[str, Any]       =       tokenizer.encode(lowercase    )
							_lowerCamelCase	:     Dict       =       rust_tokenizer.encode(lowercase    )
							self.assertListEqual(lowercase    , lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Dict       =       BasicTokenizer()

							self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz'    )    , ['ah', '\u535A', '\u63A8', 'zz']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       BasicTokenizer(do_lower_case=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHeLLo!how  \n Are yoU?  '    )    , ['hello', '!', 'how', 'are', 'you', '?']    )
							self.assertListEqual(tokenizer.tokenize('H\u00E9llo'    )    , ['hello']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[str]       =       BasicTokenizer(do_lower_case=lowercase    , strip_accents=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHäLLo!how  \n Are yoU?  '    )    , ['hällo', '!', 'how', 'are', 'you', '?']    )
							self.assertListEqual(tokenizer.tokenize('H\u00E9llo'    )    , ['h\u00E9llo']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       BasicTokenizer(do_lower_case=lowercase    , strip_accents=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHäLLo!how  \n Are yoU?  '    )    , ['hallo', '!', 'how', 'are', 'you', '?']    )
							self.assertListEqual(tokenizer.tokenize('H\u00E9llo'    )    , ['hello']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     int       =       BasicTokenizer(do_lower_case=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHäLLo!how  \n Are yoU?  '    )    , ['hallo', '!', 'how', 'are', 'you', '?']    )
							self.assertListEqual(tokenizer.tokenize('H\u00E9llo'    )    , ['hello']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[str]       =       BasicTokenizer(do_lower_case=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHeLLo!how  \n Are yoU?  '    )    , ['HeLLo', '!', 'how', 'Are', 'yoU', '?']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       BasicTokenizer(do_lower_case=lowercase    , strip_accents=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHäLLo!how  \n Are yoU?  '    )    , ['HäLLo', '!', 'how', 'Are', 'yoU', '?']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       BasicTokenizer(do_lower_case=lowercase    , strip_accents=lowercase    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHäLLo!how  \n Are yoU?  '    )    , ['HaLLo', '!', 'how', 'Are', 'yoU', '?']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     int       =       BasicTokenizer(do_lower_case=lowercase    , never_split=['[UNK]']    )

							self.assertListEqual(
							    tokenizer.tokenize(' \tHeLLo!how  \n Are yoU? [UNK]'    )    , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]']    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing']

							_lowerCamelCase	:     Tuple       =       {}
							for i, token in enumerate(lowercase    ):
											_lowerCamelCase	:     Union[str, Any]       =       i
							_lowerCamelCase	:     str       =       WordpieceTokenizer(vocab=lowercase    , unk_token='[UNK]'    )

							self.assertListEqual(tokenizer.tokenize(''    )    , []    )

							self.assertListEqual(tokenizer.tokenize('unwanted running'    )    , ['un', '##want', '##ed', 'runn', '##ing']    )

							self.assertListEqual(tokenizer.tokenize('unwantedX running'    )    , ['[UNK]', 'runn', '##ing']    )
			def    A_       (    self    ):
							self.assertTrue(_is_whitespace(' '    )    )
							self.assertTrue(_is_whitespace('\t'    )    )
							self.assertTrue(_is_whitespace('\r'    )    )
							self.assertTrue(_is_whitespace('\n'    )    )
							self.assertTrue(_is_whitespace('\u00A0'    )    )

							self.assertFalse(_is_whitespace('A'    )    )
							self.assertFalse(_is_whitespace('-'    )    )
			def    A_       (    self    ):
							self.assertTrue(_is_control('\u0005'    )    )

							self.assertFalse(_is_control('A'    )    )
							self.assertFalse(_is_control(' '    )    )
							self.assertFalse(_is_control('\t'    )    )
							self.assertFalse(_is_control('\r'    )    )
			def    A_       (    self    ):
							self.assertTrue(_is_punctuation('-'    )    )
							self.assertTrue(_is_punctuation('$'    )    )
							self.assertTrue(_is_punctuation('`'    )    )
							self.assertTrue(_is_punctuation('.'    )    )

							self.assertFalse(_is_punctuation('A'    )    )
							self.assertFalse(_is_punctuation(' '    )    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       self.get_tokenizer()
							_lowerCamelCase	:     Union[str, Any]       =       self.get_rust_tokenizer()

							# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
							self.assertListEqual([tokenizer.tokenize(lowercase    ) for t in ['Test', '\xad', 'test']]    , [['[UNK]'], [], ['[UNK]']]    )

							self.assertListEqual(
							    [rust_tokenizer.tokenize(lowercase    ) for t in ['Test', '\xad', 'test']]    , [['[UNK]'], [], ['[UNK]']]    )
			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       self.tokenizer_class.from_pretrained('google/mobilebert-uncased'    )

							_lowerCamelCase	:     List[str]       =       tokenizer.encode('sequence builders'    , add_special_tokens=lowercase    )
							_lowerCamelCase	:     Dict       =       tokenizer.encode('multi-sequence build'    , add_special_tokens=lowercase    )

							_lowerCamelCase	:     Optional[int]       =       tokenizer.build_inputs_with_special_tokens(lowercase    )
							_lowerCamelCase	:     List[Any]       =       tokenizer.build_inputs_with_special_tokens(lowercase    , lowercase    )

							assert encoded_sentence == [101] + text + [102]
							assert encoded_pair == [101] + text + [102] + text_a + [102]
			def    A_       (    self    ):
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
											with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''    ):
															_lowerCamelCase	:     int       =       self.rust_tokenizer_class.from_pretrained(lowercase    , **lowercase    )

															_lowerCamelCase	:     int       =       F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
															_lowerCamelCase	:     int       =       tokenizer_r.encode_plus(
															    lowercase    , return_attention_mask=lowercase    , return_token_type_ids=lowercase    , return_offsets_mapping=lowercase    , add_special_tokens=lowercase    , )

															_lowerCamelCase	:     Tuple       =       tokenizer_r.do_lower_case if hasattr(lowercase    , 'do_lower_case'    ) else False
															_lowerCamelCase	:     Dict       =       (
															    [
															        ((0, 0), tokenizer_r.cls_token),
															        ((0, 1), 'A'),
															        ((1, 2), ','),
															        ((3, 5), 'na'),
															        ((5, 6), '##ï'),
															        ((6, 8), '##ve'),
															        ((9, 15), tokenizer_r.mask_token),
															        ((16, 21), 'Allen'),
															        ((21, 23), '##NL'),
															        ((23, 24), '##P'),
															        ((25, 33), 'sentence'),
															        ((33, 34), '.'),
															        ((0, 0), tokenizer_r.sep_token),
															    ]
															    if not do_lower_case
															    else [
															        ((0, 0), tokenizer_r.cls_token),
															        ((0, 1), 'a'),
															        ((1, 2), ','),
															        ((3, 8), 'naive'),
															        ((9, 15), tokenizer_r.mask_token),
															        ((16, 21), 'allen'),
															        ((21, 23), '##nl'),
															        ((23, 24), '##p'),
															        ((25, 33), 'sentence'),
															        ((33, 34), '.'),
															        ((0, 0), tokenizer_r.sep_token),
															    ]
															)

															self.assertEqual(
															    [e[1] for e in expected_results]    , tokenizer_r.convert_ids_to_tokens(tokens['input_ids']    )    )
															self.assertEqual([e[0] for e in expected_results]    , tokens['offset_mapping']    )






			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       ['的', '人', '有']
							_lowerCamelCase	:     Optional[Any]       =       ''.join(lowercase    )
							for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
											with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''    ):
															_lowerCamelCase	:     int       =       True
															_lowerCamelCase	:     Any       =       self.tokenizer_class.from_pretrained(lowercase    , **lowercase    )
															_lowerCamelCase	:     Dict       =       self.rust_tokenizer_class.from_pretrained(lowercase    , **lowercase    )

															_lowerCamelCase	:     List[str]       =       tokenizer_p.encode(lowercase    , add_special_tokens=lowercase    )
															_lowerCamelCase	:     List[Any]       =       tokenizer_r.encode(lowercase    , add_special_tokens=lowercase    )

															_lowerCamelCase	:     Any       =       tokenizer_r.convert_ids_to_tokens(lowercase    )
															_lowerCamelCase	:     Dict       =       tokenizer_p.convert_ids_to_tokens(lowercase    )

															# it is expected that each Chinese character is not preceded by "##"
															self.assertListEqual(lowercase    , lowercase    )
															self.assertListEqual(lowercase    , lowercase    )

															_lowerCamelCase	:     Optional[Any]       =       False
															_lowerCamelCase	:     Dict       =       self.rust_tokenizer_class.from_pretrained(lowercase    , **lowercase    )
															_lowerCamelCase	:     Optional[int]       =       self.tokenizer_class.from_pretrained(lowercase    , **lowercase    )

															_lowerCamelCase	:     Optional[Any]       =       tokenizer_r.encode(lowercase    , add_special_tokens=lowercase    )
															_lowerCamelCase	:     str       =       tokenizer_p.encode(lowercase    , add_special_tokens=lowercase    )

															_lowerCamelCase	:     List[Any]       =       tokenizer_r.convert_ids_to_tokens(lowercase    )
															_lowerCamelCase	:     Dict       =       tokenizer_p.convert_ids_to_tokens(lowercase    )

															# it is expected that only the first Chinese character is not preceded by "##".
															_lowerCamelCase	:     List[str]       =       [
															    F'''##{token}''' if idx != 0 else token for idx, token in enumerate(lowercase    )
															]
															self.assertListEqual(lowercase    , lowercase    )
															self.assertListEqual(lowercase    , lowercase    )