




'''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


_SCREAMING_SNAKE_CASE			=						logging.getLogger(__name__)





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_ = None       ,SCREAMING_SNAKE_CASE_ = None       ,SCREAMING_SNAKE_CASE_ = None       ,SCREAMING_SNAKE_CASE_ = None       ,SCREAMING_SNAKE_CASE_ = None       ,SCREAMING_SNAKE_CASE_ = False       ,)		->		List[str]:
			A_									= bnb_quantization_config.load_in_abit
			A_									= 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.'     )

			A_									= []
			# custom device map
			if isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ) and len(device_map.keys()     ) > 1:
						A_									= [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:
						A_									= get_keys_to_not_convert(SCREAMING_SNAKE_CASE_     )

			# add cpu modules to skip modules only for 4-bit modules
			if load_in_abit:
						bnb_quantization_config.skip_modules.extend(SCREAMING_SNAKE_CASE_     )
			A_									= 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:
						A_									= []
			A_									= bnb_quantization_config.keep_in_fpaa_modules
			modules_to_not_convert.extend(SCREAMING_SNAKE_CASE_     )

			# compatibility with peft
			A_									= load_in_abit
			A_									= load_in_abit

			A_									= get_parameter_device(SCREAMING_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.'     )
						A_									= replace_with_bnb_layers(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,modules_to_not_convert=SCREAMING_SNAKE_CASE_     )
						# convert param to the right dtype
						A_									= 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:
															A_									= name.replace('.weight'       ,''     ).replace('.bias'       ,''     )
															A_									= getattr(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )
															if param is not None:
																		param.to(torch.floataa     )
									elif torch.is_floating_point(SCREAMING_SNAKE_CASE_     ):
												param.to(SCREAMING_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():
									A_									= replace_with_bnb_layers(
									    SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,modules_to_not_convert=SCREAMING_SNAKE_CASE_     )

						A_									= get_quantized_model_device_map(
						    SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,max_memory=SCREAMING_SNAKE_CASE_       ,no_split_module_classes=SCREAMING_SNAKE_CASE_       ,)
						if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
									A_									= True

						A_									= any(x in list(device_map.values()     ) for x in ['cpu', 'disk']     )

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





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_=None       ,SCREAMING_SNAKE_CASE_=None       ,SCREAMING_SNAKE_CASE_=None     )		->		str:
			if device_map is None:
						if torch.cuda.is_available():
									A_									= {'': 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(SCREAMING_SNAKE_CASE_       ,SCREAMING_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\'.'     )

						A_									= {}
						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     )
						    }     )

						A_									= {}
						A_									= special_dtypes
						A_									= no_split_module_classes
						A_									= bnb_quantization_config.target_dtype

						# get max_memory for each device.
						if device_map != "sequential":
									A_									= get_balanced_memory(
									    SCREAMING_SNAKE_CASE_       ,low_zero=(device_map == 'balanced_low_0')       ,max_memory=SCREAMING_SNAKE_CASE_       ,**SCREAMING_SNAKE_CASE_       ,)

						A_									= max_memory
						A_									= infer_auto_device_map(SCREAMING_SNAKE_CASE_       ,**SCREAMING_SNAKE_CASE_     )

			if isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ):
						# check if don't have any quantized module on the cpu
						A_									= bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

						A_									= {
						    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 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_=None       ,SCREAMING_SNAKE_CASE_=None     )		->		Optional[Any]:

			if modules_to_not_convert is None:
						A_									= []

			A_		, A_									= _replace_with_bnb_layers(
			    SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_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 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_=None       ,SCREAMING_SNAKE_CASE_=None       ,)		->		Tuple:
			A_									= False
			for name, module in model.named_children():
						if current_key_name is None:
									A_									= []
						current_key_name.append(SCREAMING_SNAKE_CASE_     )
						if isinstance(SCREAMING_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`
									A_									= '.'.join(SCREAMING_SNAKE_CASE_     )
									A_									= 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:
															A_									= False
															break
									if proceed:
												# Load bnb module with empty weight and replace ``nn.Linear` module
												if bnb_quantization_config.load_in_abit:
															A_									= bnb.nn.LinearabitLt(
															    module.in_features       ,module.out_features       ,module.bias is not None       ,has_fpaa_weights=SCREAMING_SNAKE_CASE_       ,threshold=bnb_quantization_config.llm_inta_threshold       ,)
												elif bnb_quantization_config.load_in_abit:
															A_									= 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'     )
												A_									= module.weight.data
												if module.bias is not None:
															A_									= module.bias.data
												bnb_module.requires_grad_(SCREAMING_SNAKE_CASE_     )
												setattr(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )
												A_									= True
						if len(list(module.children()     )     ) > 0:
									A_		, A_									= _replace_with_bnb_layers(
									    SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )
									A_									= has_been_replaced | _has_been_replaced
						# Remove the last key for recursion
						current_key_name.pop(-1     )
			return model, has_been_replaced





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Dict:
			# Create a copy of the model
			with init_empty_weights():
						A_									= deepcopy(SCREAMING_SNAKE_CASE_     )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

			A_									= find_tied_parameters(SCREAMING_SNAKE_CASE_     )
			# For compatibility with Accelerate < 0.18
			if isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ):
						A_									= sum(list(tied_params.values()     )       ,[]     ) + list(tied_params.keys()     )
			else:
						A_									= sum(SCREAMING_SNAKE_CASE_       ,[]     )
			A_									= len(SCREAMING_SNAKE_CASE_     ) > 0

			# Check if it is a base model
			A_									= False
			if hasattr(SCREAMING_SNAKE_CASE_       ,'base_model_prefix'     ):
						A_									= not hasattr(SCREAMING_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
			A_									= list(model.named_children()     )
			A_									= [list_modules[-1][0]]

			# add last module together with tied weights
			A_									= set(SCREAMING_SNAKE_CASE_     ) - set(SCREAMING_SNAKE_CASE_     )
			A_									= list(set(SCREAMING_SNAKE_CASE_     )     ) + list(SCREAMING_SNAKE_CASE_     )

			# remove ".weight" from the keys
			A_									= ['.weight', '.bias']
			A_									= []
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												A_									= name.replace(SCREAMING_SNAKE_CASE_       ,''     )
						filtered_module_names.append(SCREAMING_SNAKE_CASE_     )

			return filtered_module_names





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Any:
			for m in model.modules():
						if isinstance(SCREAMING_SNAKE_CASE_       ,bnb.nn.Linearabit     ):
									return True
			return False





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		Optional[Any]:
			return next(parameter.parameters()     ).device






def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )		->		Dict:
			# if it is not quantized, we quantize and offload the quantized weights and the SCB stats
			if fpaa_statistics is None:
						set_module_tensor_to_device(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,0       ,dtype=SCREAMING_SNAKE_CASE_       ,value=SCREAMING_SNAKE_CASE_     )
						A_									= param_name
						A_									= model
						if "." in tensor_name:
									A_									= tensor_name.split('.'     )
									for split in splits[:-1]:
												A_									= getattr(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     )
												if new_module is None:
															raise ValueError(F'{module} has no attribute {split}.'     )
												A_									= new_module
									A_									= splits[-1]
						# offload weights
						A_									= False
						offload_weight(module._parameters[tensor_name]       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,index=SCREAMING_SNAKE_CASE_     )
						if hasattr(module._parameters[tensor_name]       ,'SCB'     ):
									offload_weight(
									    module._parameters[tensor_name].SCB       ,param_name.replace('weight'       ,'SCB'     )       ,SCREAMING_SNAKE_CASE_       ,index=SCREAMING_SNAKE_CASE_       ,)
			else:
						offload_weight(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,index=SCREAMING_SNAKE_CASE_     )
						offload_weight(SCREAMING_SNAKE_CASE_       ,param_name.replace('weight'       ,'SCB'     )       ,SCREAMING_SNAKE_CASE_       ,index=SCREAMING_SNAKE_CASE_     )

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










'''simple docstring'''
import unittest

from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_SCREAMING_SNAKE_CASE			=						get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
@require_tokenizers
class   __UpperCAmelCase				(     lowerCAmelCase			,unittest.TestCase				):



					'''simple docstring'''





					_UpperCamelCase							=		ReformerTokenizer
					_UpperCamelCase							=		ReformerTokenizerFast
					_UpperCamelCase							=		True
					_UpperCamelCase							=		False
					_UpperCamelCase							=		True



					def     __snake_case						(	self     :						Optional[int])    ->							int:
								super().setUp()

								A_									= ReformerTokenizer(_lowercase      ,       keep_accents=_lowercase)
								tokenizer.save_pretrained(self.tmpdirname)



					def     __snake_case						(	self     :						List[Any])    ->							str:
								A_									= '<s>'
								A_									= 1

								self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowercase)      ,       _lowercase)
								self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowercase)      ,       _lowercase)



					def     __snake_case						(	self     :						Any)    ->							Optional[Any]:
								A_									= list(self.get_tokenizer().get_vocab().keys())

								self.assertEqual(vocab_keys[0]      ,       '<unk>')
								self.assertEqual(vocab_keys[1]      ,       '<s>')
								self.assertEqual(vocab_keys[-1]      ,       'j')
								self.assertEqual(len(_lowercase)      ,       1_000)



					def     __snake_case						(	self     :						int)    ->							Optional[int]:
								self.assertEqual(self.get_tokenizer().vocab_size      ,       1_000)



					def     __snake_case						(	self     :						List[Any])    ->							Any:
								if not self.test_rust_tokenizer:
											return

								A_									= self.get_tokenizer()
								A_									= self.get_rust_tokenizer()

								A_									= 'I was born in 92000, and this is falsé.'

								A_									= tokenizer.tokenize(_lowercase)
								A_									= rust_tokenizer.tokenize(_lowercase)
								self.assertListEqual(_lowercase      ,       _lowercase)

								A_									= tokenizer.encode(_lowercase      ,       add_special_tokens=_lowercase)
								A_									= rust_tokenizer.encode(_lowercase      ,       add_special_tokens=_lowercase)
								self.assertListEqual(_lowercase      ,       _lowercase)

								A_									= self.get_rust_tokenizer()
								A_									= tokenizer.encode(_lowercase)
								A_									= rust_tokenizer.encode(_lowercase)
								self.assertListEqual(_lowercase      ,       _lowercase)



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						Optional[int]=15)    ->							str:
								for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
											with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'):
														A_									= self.rust_tokenizer_class.from_pretrained(_lowercase      ,       **_lowercase)

														# Simple input
														A_									= 'This is a simple input'
														A_									= ['This is a simple input 1', 'This is a simple input 2']
														A_									= ('This is a simple input', 'This is a pair')
														A_									= [
														    ('This is a simple input 1', 'This is a simple input 2'),
														    ('This is a simple pair 1', 'This is a simple pair 2'),
														]

														# Simple input tests
														self.assertRaises(_lowercase      ,       tokenizer_r.encode      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length')

														# Simple input
														self.assertRaises(_lowercase      ,       tokenizer_r.encode_plus      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length')

														# Simple input
														self.assertRaises(
														    _lowercase      ,       tokenizer_r.batch_encode_plus      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length'      ,       )

														# Pair input
														self.assertRaises(_lowercase      ,       tokenizer_r.encode      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length')

														# Pair input
														self.assertRaises(_lowercase      ,       tokenizer_r.encode_plus      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length')

														# Pair input
														self.assertRaises(
														    _lowercase      ,       tokenizer_r.batch_encode_plus      ,       _lowercase      ,       max_length=_lowercase      ,       padding='max_length'      ,       )



					def     __snake_case						(	self     :						Optional[int])    ->							Optional[int]:
								pass



					def     __snake_case						(	self     :						Tuple)    ->							Optional[Any]:
								A_									= ReformerTokenizer(_lowercase      ,       keep_accents=_lowercase)

								A_									= tokenizer.tokenize('This is a test')
								self.assertListEqual(_lowercase      ,       ['▁This', '▁is', '▁a', '▁t', 'est'])

								self.assertListEqual(
								    tokenizer.convert_tokens_to_ids(_lowercase)      ,       [285, 46, 10, 170, 382]      ,       )

								A_									= tokenizer.tokenize('I was born in 92000, and this is falsé.')
								self.assertListEqual(
								    _lowercase      ,       [
								        SPIECE_UNDERLINE + 'I',
								        SPIECE_UNDERLINE + 'was',
								        SPIECE_UNDERLINE + 'b',
								        'or',
								        'n',
								        SPIECE_UNDERLINE + 'in',
								        SPIECE_UNDERLINE + '',
								        '9',
								        '2',
								        '0',
								        '0',
								        '0',
								        ',',
								        SPIECE_UNDERLINE + 'and',
								        SPIECE_UNDERLINE + 'this',
								        SPIECE_UNDERLINE + 'is',
								        SPIECE_UNDERLINE + 'f',
								        'al',
								        's',
								        'é',
								        '.',
								    ]      ,       )
								A_									= tokenizer.convert_tokens_to_ids(_lowercase)
								self.assertListEqual(
								    _lowercase      ,       [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4]      ,       )

								A_									= tokenizer.convert_ids_to_tokens(_lowercase)
								self.assertListEqual(
								    _lowercase      ,       [
								        SPIECE_UNDERLINE + 'I',
								        SPIECE_UNDERLINE + 'was',
								        SPIECE_UNDERLINE + 'b',
								        'or',
								        'n',
								        SPIECE_UNDERLINE + 'in',
								        SPIECE_UNDERLINE + '',
								        '<unk>',
								        '2',
								        '0',
								        '0',
								        '0',
								        ',',
								        SPIECE_UNDERLINE + 'and',
								        SPIECE_UNDERLINE + 'this',
								        SPIECE_UNDERLINE + 'is',
								        SPIECE_UNDERLINE + 'f',
								        'al',
								        's',
								        '<unk>',
								        '.',
								    ]      ,       )



					@cached_property
					def     __snake_case						(	self     :						str)    ->							Any:
								return ReformerTokenizer.from_pretrained('google/reformer-crime-and-punishment')



					@slow
					def     __snake_case						(	self     :						Tuple)    ->							Union[str, Any]:
								A_									= 'Hello World!'
								A_									= [126, 32, 262, 152, 38, 72, 287]

								self.assertListEqual(_lowercase      ,       self.big_tokenizer.encode(_lowercase))



					@slow
					def     __snake_case						(	self     :						Optional[int])    ->							int:
								A_									= (
								    'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
								    ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'
								)
								A_									= [
								    108,
								    265,
								    24,
								    111,
								    4,
								    258,
								    156,
								    35,
								    28,
								    275,
								    3,
								    259,
								    297,
								    260,
								    84,
								    4,
								    35,
								    110,
								    44,
								    8,
								    259,
								    91,
								    268,
								    21,
								    11,
								    209,
								    274,
								    109,
								    266,
								    277,
								    117,
								    86,
								    93,
								    315,
								    258,
								    278,
								    258,
								    277,
								    258,
								    0,
								    258,
								    288,
								    258,
								    319,
								    258,
								    0,
								    258,
								    0,
								    258,
								    0,
								    258,
								    0,
								    258,
								    287,
								    258,
								    315,
								    258,
								    289,
								    258,
								    278,
								    99,
								    269,
								    266,
								    262,
								    8,
								    259,
								    241,
								    4,
								    217,
								    230,
								    268,
								    266,
								    55,
								    168,
								    106,
								    75,
								    193,
								    266,
								    223,
								    27,
								    49,
								    26,
								    282,
								    25,
								    264,
								    299,
								    19,
								    26,
								    0,
								    258,
								    277,
								    117,
								    86,
								    93,
								    176,
								    183,
								    270,
								    11,
								    262,
								    42,
								    61,
								    265,
								]

								self.assertListEqual(_lowercase      ,       self.big_tokenizer.encode(_lowercase))



					@require_torch
					@slow
					def     __snake_case						(	self     :						List[str])    ->							Tuple:
								import torch

								from transformers import ReformerConfig, ReformerModel

								# Build sequence
								A_									= list(self.big_tokenizer.get_vocab().keys())[:10]
								A_									= ' '.join(_lowercase)
								A_									= self.big_tokenizer.encode_plus(_lowercase      ,       return_tensors='pt')
								A_									= self.big_tokenizer.batch_encode_plus([sequence, sequence]      ,       return_tensors='pt')

								A_									= ReformerConfig()
								# The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
								A_									= encoded_sequence['input_ids'].shape
								A_									= ReformerModel(_lowercase)

								# Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
								assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size

								with torch.no_grad():
											model(**_lowercase)
											model(**_lowercase)



					@slow
					def     __snake_case						(	self     :						str)    ->							Union[str, Any]:
								# fmt: off
								A_									= {'input_ids': [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
								# fmt: on

								# This tokenizer does not know some characters like ")".
								# That is the reason why we use very simple texts here.
								# Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
								A_									= [
								    'This is a very simple sentence.',
								    'The quick brown fox jumps over the lazy dog.',
								]

								self.tokenizer_integration_test_util(
								    expected_encoding=_lowercase      ,       model_name='google/reformer-crime-and-punishment'      ,       revision='0e6c3decb8211d49bf881013425dc8b0448b3f5a'      ,       padding=_lowercase      ,       sequences=_lowercase      ,       )




