


"""simple docstring"""






import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
					import bitsandbytes as bnb

from copy import deepcopy


UpperCamelCase__				:Dict			   =	logging.getLogger(__name__)





def 				A_       ( snake_case__       ,					snake_case__       ,					snake_case__ = None       ,					snake_case__ = None       ,					snake_case__ = None       ,					snake_case__ = None       ,					snake_case__ = None       ,					snake_case__ = False       ,					)					->  Tuple:
			_UpperCamelCase					:Optional[int]					     =	bnb_quantization_config.load_in_abit
			_UpperCamelCase					:Any					     =	bnb_quantization_config.load_in_abit

			if load_in_abit and not is_abit_bnb_available():
						raise ImportError(
						    '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'''
						    ''' make sure you have the latest version of `bitsandbytes` installed.'''		)
			if load_in_abit and not is_abit_bnb_available():
						raise ValueError(
						    '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'''
						    '''make sure you have the latest version of `bitsandbytes` installed.'''		)

			_UpperCamelCase					:Optional[Any]					     =	[]
			# custom device map
			if isinstance(snake_case__       ,					snake_case__		) and len(device_map.keys()		) > 1:
						_UpperCamelCase					:Any					     =	[key for key, value in device_map.items() if value in ["disk", "cpu"]]

			# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
			if bnb_quantization_config.skip_modules is None:
						_UpperCamelCase					:Tuple					     =	get_keys_to_not_convert(snake_case__		)

			# add cpu modules to skip modules only for 4-bit modules
			if load_in_abit:
						bnb_quantization_config.skip_modules.extend(snake_case__		)
			_UpperCamelCase					:str					     =	bnb_quantization_config.skip_modules

			# We add the modules we want to keep in full precision
			if bnb_quantization_config.keep_in_fpaa_modules is None:
						_UpperCamelCase					:Union[str, Any]					     =	[]
			_UpperCamelCase					:Dict					     =	bnb_quantization_config.keep_in_fpaa_modules
			modules_to_not_convert.extend(snake_case__		)

			# compatibility with peft
			_UpperCamelCase					:List[str]					     =	load_in_abit
			_UpperCamelCase					:Optional[Any]					     =	load_in_abit

			_UpperCamelCase					:List[Any]					     =	get_parameter_device(snake_case__		)
			if model_device.type != "meta":
						# quantization of an already loaded model
						logger.warning(
						    '''It is not recommended to quantize a loaded model. '''
						    '''The model should be instantiated under the `init_empty_weights` context manager.'''		)
						_UpperCamelCase					:List[Any]					     =	replace_with_bnb_layers(snake_case__       ,					snake_case__       ,					modules_to_not_convert=snake_case__		)
						# convert param to the right dtype
						_UpperCamelCase					:List[str]					     =	bnb_quantization_config.torch_dtype
						for name, param in model.state_dict().items():
									if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules		):
												param.to(torch.floataa		)
												if param.dtype != torch.floataa:
															_UpperCamelCase					:Union[str, Any]					     =	name.replace('''.weight'''       ,					''''''		).replace('''.bias'''       ,					''''''		)
															_UpperCamelCase					:List[Any]					     =	getattr(snake_case__       ,					snake_case__       ,					snake_case__		)
															if param is not None:
																		param.to(torch.floataa		)
									elif torch.is_floating_point(snake_case__		):
												param.to(snake_case__		)
						if model_device.type == "cuda":
									# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
									model.cuda(torch.cuda.current_device()		)
									torch.cuda.empty_cache()
						elif torch.cuda.is_available():
									model.to(torch.cuda.current_device()		)
						else:
									raise RuntimeError('''No GPU found. A GPU is needed for quantization.'''		)
						logger.info(
						    f"The model device type is {model_device.type}. However, cuda is needed for quantization."
						    '''We move the model to cuda.'''		)
						return model

			elif weights_location is None:
						raise RuntimeError(
						    f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} "		)

			else:
						with init_empty_weights():
									_UpperCamelCase					:Tuple					     =	replace_with_bnb_layers(
									    snake_case__       ,					snake_case__       ,					modules_to_not_convert=snake_case__		)

						_UpperCamelCase					:int					     =	get_quantized_model_device_map(
						    snake_case__       ,					snake_case__       ,					snake_case__       ,					max_memory=snake_case__       ,					no_split_module_classes=snake_case__       ,					)
						if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
									_UpperCamelCase					:List[Any]					     =	True

						_UpperCamelCase					:List[Any]					     =	any(x in list(device_map.values()		) for x in ['''cpu''', '''disk''']		)

						load_checkpoint_in_model(
						    snake_case__       ,					snake_case__       ,					snake_case__       ,					dtype=bnb_quantization_config.torch_dtype       ,					offload_folder=snake_case__       ,					offload_state_dict=snake_case__       ,					keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules       ,					offload_abit_bnb=load_in_abit and offload       ,					)
						return dispatch_model(snake_case__       ,					device_map=snake_case__       ,					offload_dir=snake_case__		)





def 				A_       ( snake_case__       ,					snake_case__       ,					snake_case__=None       ,					snake_case__=None       ,					snake_case__=None		)					->  Any:





			if device_map is None:
						if torch.cuda.is_available():
									_UpperCamelCase					:Dict					     =	{"": torch.cuda.current_device()}
						else:
									raise RuntimeError('''No GPU found. A GPU is needed for quantization.'''		)
						logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.'''		)

			if isinstance(snake_case__       ,					snake_case__		):
						if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
									raise ValueError(
									    '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '''
									    '''\'sequential\'.'''		)

						_UpperCamelCase					:Tuple					     =	{}
						special_dtypes.update(
						    {
						        name: bnb_quantization_config.torch_dtype
						        for name, _ in model.named_parameters()
						        if any(m in name for m in bnb_quantization_config.skip_modules		)
						    }		)
						special_dtypes.update(
						    {
						        name: torch.floataa
						        for name, _ in model.named_parameters()
						        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules		)
						    }		)

						_UpperCamelCase					:Optional[Any]					     =	{}
						_UpperCamelCase					:Optional[Any]					     =	special_dtypes
						_UpperCamelCase					:Tuple					     =	no_split_module_classes
						_UpperCamelCase					:Optional[int]					     =	bnb_quantization_config.target_dtype

						# get max_memory for each device.
						if device_map != "sequential":
									_UpperCamelCase					:Union[str, Any]					     =	get_balanced_memory(
									    snake_case__       ,					low_zero=(device_map == '''balanced_low_0''')       ,					max_memory=snake_case__       ,					**snake_case__       ,					)

						_UpperCamelCase					:Optional[Any]					     =	max_memory
						_UpperCamelCase					:Optional[Any]					     =	infer_auto_device_map(snake_case__       ,					**snake_case__		)

			if isinstance(snake_case__       ,					snake_case__		):
						# check if don't have any quantized module on the cpu
						_UpperCamelCase					:Optional[Any]					     =	bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

						_UpperCamelCase					:Tuple					     =	{
						    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
						}
						for device in ["cpu", "disk"]:
									if device in device_map_without_some_modules.values():
												if bnb_quantization_config.load_in_abit:
															raise ValueError(
															    '''\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '''		)
												else:
															logger.info(
															    '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'''		)
						del device_map_without_some_modules
			return device_map





def 				A_       ( snake_case__       ,					snake_case__       ,					snake_case__=None       ,					snake_case__=None		)					->  Optional[int]:





			if modules_to_not_convert is None:
						_UpperCamelCase					:int					     =	[]

			_UpperCamelCase					:Optional[Any]					     =	_replace_with_bnb_layers(
			    snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__		)
			if not has_been_replaced:
						logger.warning(
						    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
						    ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'''
						    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
						    ''' a bug.'''		)
			return model





def 				A_       ( snake_case__       ,					snake_case__       ,					snake_case__=None       ,					snake_case__=None       ,					)					->  Optional[int]:
			_UpperCamelCase					:Optional[int]					     =	False
			for name, module in model.named_children():
						if current_key_name is None:
									_UpperCamelCase					:List[str]					     =	[]
						current_key_name.append(snake_case__		)
						if isinstance(snake_case__       ,					nn.Linear		) and name not in modules_to_not_convert:
									# Check if the current key is not in the `modules_to_not_convert`
									_UpperCamelCase					:Union[str, Any]					     =	".".join(snake_case__		)
									_UpperCamelCase					:Optional[int]					     =	True
									for key in modules_to_not_convert:
												if (
												    (key in current_key_name_str) and (key + "." in current_key_name_str)
												) or key == current_key_name_str:
															_UpperCamelCase					:List[Any]					     =	False
															break
									if proceed:
												# Load bnb module with empty weight and replace ``nn.Linear` module
												if bnb_quantization_config.load_in_abit:
															_UpperCamelCase					:int					     =	bnb.nn.LinearabitLt(
															    module.in_features       ,					module.out_features       ,					module.bias is not None       ,					has_fpaa_weights=snake_case__       ,					threshold=bnb_quantization_config.llm_inta_threshold       ,					)
												elif bnb_quantization_config.load_in_abit:
															_UpperCamelCase					:List[Any]					     =	bnb.nn.Linearabit(
															    module.in_features       ,					module.out_features       ,					module.bias is not None       ,					bnb_quantization_config.bnb_abit_compute_dtype       ,					compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant       ,					quant_type=bnb_quantization_config.bnb_abit_quant_type       ,					)
												else:
															raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False'''		)
												_UpperCamelCase					:Optional[int]					     =	module.weight.data
												if module.bias is not None:
															_UpperCamelCase					:Tuple					     =	module.bias.data
												bnb_module.requires_grad_(snake_case__		)
												setattr(snake_case__       ,					snake_case__       ,					snake_case__		)
												_UpperCamelCase					:Union[str, Any]					     =	True
						if len(list(module.children()		)		) > 0:
									_UpperCamelCase					:List[Any]					     =	_replace_with_bnb_layers(
									    snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__		)
									_UpperCamelCase					:List[Any]					     =	has_been_replaced | _has_been_replaced
						# Remove the last key for recursion
						current_key_name.pop(-1		)
			return model, has_been_replaced





def 				A_       ( snake_case__		)					->  Optional[Any]:





			with init_empty_weights():
						_UpperCamelCase					:List[Any]					     =	deepcopy(snake_case__		)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

			_UpperCamelCase					:str					     =	find_tied_parameters(snake_case__		)
			# For compatibility with Accelerate < 0.18
			if isinstance(snake_case__       ,					snake_case__		):
						_UpperCamelCase					:List[Any]					     =	sum(list(tied_params.values()		)       ,					[]		) + list(tied_params.keys()		)
			else:
						_UpperCamelCase					:Dict					     =	sum(snake_case__       ,					[]		)
			_UpperCamelCase					:List[str]					     =	len(snake_case__		) > 0

			# Check if it is a base model
			_UpperCamelCase					:int					     =	False
			if hasattr(snake_case__       ,					'''base_model_prefix'''		):
						_UpperCamelCase					:int					     =	not hasattr(snake_case__       ,					model.base_model_prefix		)

			# Ignore this for base models (BertModel, GPT2Model, etc.)
			if (not has_tied_params) and is_base_model:
						return []

			# otherwise they have an attached head
			_UpperCamelCase					:Tuple					     =	list(model.named_children()		)
			_UpperCamelCase					:Union[str, Any]					     =	[list_modules[-1][0]]

			# add last module together with tied weights
			_UpperCamelCase					:Optional[Any]					     =	set(snake_case__		) - set(snake_case__		)
			_UpperCamelCase					:Any					     =	list(set(snake_case__		)		) + list(snake_case__		)

			# remove ".weight" from the keys
			_UpperCamelCase					:List[Any]					     =	[".weight", ".bias"]
			_UpperCamelCase					:Optional[Any]					     =	[]
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												_UpperCamelCase					:Tuple					     =	name.replace(snake_case__       ,					''''''		)
						filtered_module_names.append(snake_case__		)

			return filtered_module_names





def 				A_       ( snake_case__		)					->  int:





			for m in model.modules():
						if isinstance(snake_case__       ,					bnb.nn.Linearabit		):
									return True
			return False





def 				A_       ( snake_case__		)					->  List[str]:
			return next(parameter.parameters()		).device





def 				A_       ( snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__       ,					snake_case__		)					->  int:





			if fpaa_statistics is None:
						set_module_tensor_to_device(snake_case__       ,					snake_case__       ,					0       ,					dtype=snake_case__       ,					value=snake_case__		)
						_UpperCamelCase					:Any					     =	param_name
						_UpperCamelCase					:List[Any]					     =	model
						if "." in tensor_name:
									_UpperCamelCase					:str					     =	tensor_name.split('''.'''		)
									for split in splits[:-1]:
												_UpperCamelCase					:Tuple					     =	getattr(snake_case__       ,					snake_case__		)
												if new_module is None:
															raise ValueError(f"{module} has no attribute {split}."		)
												_UpperCamelCase					:int					     =	new_module
									_UpperCamelCase					:Tuple					     =	splits[-1]
						# offload weights
						_UpperCamelCase					:str					     =	False
						offload_weight(module._parameters[tensor_name]       ,					snake_case__       ,					snake_case__       ,					index=snake_case__		)
						if hasattr(module._parameters[tensor_name]       ,					'''SCB'''		):
									offload_weight(
									    module._parameters[tensor_name].SCB       ,					param_name.replace('''weight'''       ,					'''SCB'''		)       ,					snake_case__       ,					index=snake_case__       ,					)
			else:
						offload_weight(snake_case__       ,					snake_case__       ,					snake_case__       ,					index=snake_case__		)
						offload_weight(snake_case__       ,					param_name.replace('''weight'''       ,					'''SCB'''		)       ,					snake_case__       ,					index=snake_case__		)

			set_module_tensor_to_device(snake_case__       ,					snake_case__       ,					'''meta'''       ,					dtype=snake_case__       ,					value=torch.empty(*param.size()		)		)





"""simple docstring"""



import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / """utils"""))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
  from test_module.custom_tokenization_fast import CustomTokenizerFast







class _lowerCAmelCase							( unittest.TestCase      ):







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       snake_case       : List[str]    =       mock.Mock()
       snake_case       : Any    =       500
       snake_case       : int    =       {}
       snake_case       : int    =       HTTPError
       snake_case       : Dict    =       {}

       # Download this model to make sure it's in the cache.
       snake_case       : Dict    =       BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"		)

       # Under the mock environment we get a 500 error when trying to reach the tokenizer.
       with mock.patch("requests.Session.request"		,      return_value=UpperCamelCase__		) as mock_head:
           snake_case       : str    =       BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert"		)
           # This check we did call the fake head request
           mock_head.assert_called()







   @require_tokenizers
   def 					lowerCamelCase						(      self		)      ->						int:

       '''simple docstring'''




       snake_case       : Union[str, Any]    =       mock.Mock()
       snake_case       : int    =       500
       snake_case       : Optional[int]    =       {}
       snake_case       : int    =       HTTPError
       snake_case       : int    =       {}

       # Download this model to make sure it's in the cache.
       snake_case       : Any    =       GPTaTokenizerFast.from_pretrained("gpt2"		)

       # Under the mock environment we get a 500 error when trying to reach the tokenizer.
       with mock.patch("requests.Session.request"		,      return_value=UpperCamelCase__		) as mock_head:
           snake_case       : Tuple    =       GPTaTokenizerFast.from_pretrained("gpt2"		)
           # This check we did call the fake head request
           mock_head.assert_called()







   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       try:
           snake_case       : Tuple    =       tempfile.mktemp()
           with open(UpperCamelCase__		,      "wb"		) as f:
               http_get("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"		,      UpperCamelCase__		)

           snake_case       : List[str]    =       AlbertTokenizer.from_pretrained(UpperCamelCase__		)
       finally:
           os.remove(UpperCamelCase__		)

       # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
       # the current folder and have the right name.
       if os.path.isfile("tokenizer.json"		):
           # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
           return
       try:
           with open("tokenizer.json"		,      "wb"		) as f:
               http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json"		,      UpperCamelCase__		)
           snake_case       : Dict    =       AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2"		)
           # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
           self.assertEqual(tokenizer.vocab_size		,      1000		)
           # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

       finally:
           os.remove("tokenizer.json"		)







   def 					lowerCamelCase						(      self		)      ->						Optional[Any]:

       '''simple docstring'''




       snake_case       : int    =       AlbertTokenizer.from_pretrained("https://huggingface.co/albert-base-v1/resolve/main/spiece.model"		)







@is_staging_test
class _lowerCAmelCase							( unittest.TestCase      ):
   __UpperCAmelCase					:			Dict				    =    ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']







   @classmethod
   def 					lowerCamelCase						(      cls		)      ->						Optional[int]:

       '''simple docstring'''




       snake_case       : List[str]    =       TOKEN
       HfFolder.save_token(UpperCamelCase__		)







   @classmethod
   def 					lowerCamelCase						(      cls		)      ->						Union[str, Any]:

       '''simple docstring'''




       try:
           delete_repo(token=cls._token		,      repo_id="test-tokenizer"		)
       except HTTPError:
           pass

       try:
           delete_repo(token=cls._token		,      repo_id="valid_org/test-tokenizer-org"		)
       except HTTPError:
           pass

       try:
           delete_repo(token=cls._token		,      repo_id="test-dynamic-tokenizer"		)
       except HTTPError:
           pass







   def 					lowerCamelCase						(      self		)      ->						Dict:

       '''simple docstring'''




       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case       : Any    =       os.path.join(UpperCamelCase__		,      "vocab.txt"		)
           with open(UpperCamelCase__		,      "w"		,      encoding="utf-8"		) as vocab_writer:
               vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]		)		)
           snake_case       : List[str]    =       BertTokenizer(UpperCamelCase__		)

       tokenizer.push_to_hub("test-tokenizer"		,      use_auth_token=self._token		)
       snake_case       : Dict    =       BertTokenizer.from_pretrained(F'{USER}/test-tokenizer'		)
       self.assertDictEqual(new_tokenizer.vocab		,      tokenizer.vocab		)

       # Reset repo
       delete_repo(token=self._token		,      repo_id="test-tokenizer"		)

       # Push to hub via save_pretrained
       with tempfile.TemporaryDirectory() as tmp_dir:
           tokenizer.save_pretrained(UpperCamelCase__		,      repo_id="test-tokenizer"		,      push_to_hub=UpperCamelCase__		,      use_auth_token=self._token		)

       snake_case       : Dict    =       BertTokenizer.from_pretrained(F'{USER}/test-tokenizer'		)
       self.assertDictEqual(new_tokenizer.vocab		,      tokenizer.vocab		)







   def 					lowerCamelCase						(      self		)      ->						Any:

       '''simple docstring'''




       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case       : Dict    =       os.path.join(UpperCamelCase__		,      "vocab.txt"		)
           with open(UpperCamelCase__		,      "w"		,      encoding="utf-8"		) as vocab_writer:
               vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]		)		)
           snake_case       : Optional[int]    =       BertTokenizer(UpperCamelCase__		)

       tokenizer.push_to_hub("valid_org/test-tokenizer-org"		,      use_auth_token=self._token		)
       snake_case       : Dict    =       BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"		)
       self.assertDictEqual(new_tokenizer.vocab		,      tokenizer.vocab		)

       # Reset repo
       delete_repo(token=self._token		,      repo_id="valid_org/test-tokenizer-org"		)

       # Push to hub via save_pretrained
       with tempfile.TemporaryDirectory() as tmp_dir:
           tokenizer.save_pretrained(
               UpperCamelCase__		,      repo_id="valid_org/test-tokenizer-org"		,      push_to_hub=UpperCamelCase__		,      use_auth_token=self._token		)

       snake_case       : Optional[int]    =       BertTokenizer.from_pretrained("valid_org/test-tokenizer-org"		)
       self.assertDictEqual(new_tokenizer.vocab		,      tokenizer.vocab		)







   @require_tokenizers
   def 					lowerCamelCase						(      self		)      ->						Union[str, Any]:

       '''simple docstring'''




       CustomTokenizer.register_for_auto_class()
       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case       : Tuple    =       os.path.join(UpperCamelCase__		,      "vocab.txt"		)
           with open(UpperCamelCase__		,      "w"		,      encoding="utf-8"		) as vocab_writer:
               vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]		)		)
           snake_case       : Any    =       CustomTokenizer(UpperCamelCase__		)

       # No fast custom tokenizer
       tokenizer.push_to_hub("test-dynamic-tokenizer"		,      use_auth_token=self._token		)

       snake_case       : Union[str, Any]    =       AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer'		,      trust_remote_code=UpperCamelCase__		)
       # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
       self.assertEqual(tokenizer.__class__.__name__		,      "CustomTokenizer"		)

       # Fast and slow custom tokenizer
       CustomTokenizerFast.register_for_auto_class()
       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case       : int    =       os.path.join(UpperCamelCase__		,      "vocab.txt"		)
           with open(UpperCamelCase__		,      "w"		,      encoding="utf-8"		) as vocab_writer:
               vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]		)		)

           snake_case       : Optional[Any]    =       BertTokenizerFast.from_pretrained(UpperCamelCase__		)
           bert_tokenizer.save_pretrained(UpperCamelCase__		)
           snake_case       : List[Any]    =       CustomTokenizerFast.from_pretrained(UpperCamelCase__		)

       tokenizer.push_to_hub("test-dynamic-tokenizer"		,      use_auth_token=self._token		)

       snake_case       : Union[str, Any]    =       AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer'		,      trust_remote_code=UpperCamelCase__		)
       # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
       self.assertEqual(tokenizer.__class__.__name__		,      "CustomTokenizerFast"		)
       snake_case       : Optional[Any]    =       AutoTokenizer.from_pretrained(
           F'{USER}/test-dynamic-tokenizer'		,      use_fast=UpperCamelCase__		,      trust_remote_code=UpperCamelCase__		)
       # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
       self.assertEqual(tokenizer.__class__.__name__		,      "CustomTokenizer"		)







class _lowerCAmelCase							( unittest.TestCase      ):







   def 					lowerCamelCase						(      self		)      ->						str:

       '''simple docstring'''




       snake_case       : Any    =       Trie()
       trie.add("Hello 友達"		)
       self.assertEqual(trie.data		,      {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}		)
       trie.add("Hello"		)
       trie.data
       self.assertEqual(trie.data		,      {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}		)







   def 					lowerCamelCase						(      self		)      ->						Any:

       '''simple docstring'''




       snake_case       : Tuple    =       Trie()
       self.assertEqual(trie.split("[CLS] This is a extra_id_100"		)		,      ["[CLS] This is a extra_id_100"]		)
       trie.add("[CLS]"		)
       trie.add("extra_id_1"		)
       trie.add("extra_id_100"		)
       self.assertEqual(trie.split("[CLS] This is a extra_id_100"		)		,      ["[CLS]", " This is a ", "extra_id_100"]		)







   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       snake_case       : str    =       Trie()
       trie.add("A"		)
       self.assertEqual(trie.split("ABC"		)		,      ["A", "BC"]		)
       self.assertEqual(trie.split("BCA"		)		,      ["BC", "A"]		)







   def 					lowerCamelCase						(      self		)      ->						int:

       '''simple docstring'''




       snake_case       : Union[str, Any]    =       Trie()
       trie.add("TOKEN]"		)
       trie.add("[SPECIAL_TOKEN]"		)
       self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"		)		,      ["This is something ", "[SPECIAL_TOKEN]"]		)







   def 					lowerCamelCase						(      self		)      ->						Tuple:

       '''simple docstring'''




       snake_case       : Optional[int]    =       Trie()
       trie.add("A"		)
       trie.add("P"		)
       trie.add("[SPECIAL_TOKEN]"		)
       self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"		)		,      ["This is something ", "[SPECIAL_TOKEN]"]		)







   def 					lowerCamelCase						(      self		)      ->						List[str]:

       '''simple docstring'''




       snake_case       : List[Any]    =       Trie()
       trie.add("AB"		)
       trie.add("B"		)
       trie.add("C"		)
       self.assertEqual(trie.split("ABC"		)		,      ["AB", "C"]		)







   def 					lowerCamelCase						(      self		)      ->						Dict:

       '''simple docstring'''




       snake_case       : str    =       Trie()
       trie.add("ABC"		)
       trie.add("B"		)
       trie.add("CD"		)
       self.assertEqual(trie.split("ABCD"		)		,      ["ABC", "D"]		)







   def 					lowerCamelCase						(      self		)      ->						Optional[Any]:

       '''simple docstring'''




       snake_case       : Optional[int]    =       Trie()
       snake_case       : Union[str, Any]    =       trie.cut_text("ABC"		,      [0, 0, 2, 1, 2, 3]		)
       self.assertEqual(UpperCamelCase__		,      ["AB", "C"]		)





