



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


A    =			logging.getLogger(__name__)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = None				,      lowerCamelCase__ = False				,      ) ->							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(__UpperCamelCase				,      __UpperCamelCase			) 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(__UpperCamelCase			)

							# add cpu modules to skip modules only for 4-bit modules
							if load_in_abit:
														bnb_quantization_config.skip_modules.extend(__UpperCamelCase			)
							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(__UpperCamelCase			)

							# compatibility with peft
							A         =					load_in_abit
							A         =					load_in_abit

							A         =					get_parameter_device(__UpperCamelCase			)
							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(__UpperCamelCase				,      __UpperCamelCase				,      modules_to_not_convert=__UpperCamelCase			)
														# 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(__UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase			)
																																			if param is not None:
																																										param.to(torch.floataa			)
																					elif torch.is_floating_point(__UpperCamelCase			):
																												param.to(__UpperCamelCase			)
														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(
																					    __UpperCamelCase				,      __UpperCamelCase				,      modules_to_not_convert=__UpperCamelCase			)

														A         =					get_quantized_model_device_map(
														    __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase				,      max_memory=__UpperCamelCase				,      no_split_module_classes=__UpperCamelCase				,      )
														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(
														    __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase				,      dtype=bnb_quantization_config.torch_dtype				,      offload_folder=__UpperCamelCase				,      offload_state_dict=__UpperCamelCase				,      keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules				,      offload_abit_bnb=load_in_abit and offload				,      )
														return dispatch_model(__UpperCamelCase				,      device_map=__UpperCamelCase				,      offload_dir=__UpperCamelCase			)

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=None				,      lowerCamelCase__=None				,      lowerCamelCase__=None			) ->							Union[str, Any]:
							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(__UpperCamelCase				,      __UpperCamelCase			):
														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(
																					    __UpperCamelCase				,      low_zero=(device_map == 'balanced_low_0')				,      max_memory=__UpperCamelCase				,      **__UpperCamelCase				,      )

														A         =					max_memory
														A         =					infer_auto_device_map(__UpperCamelCase				,      **__UpperCamelCase			)

							if isinstance(__UpperCamelCase				,      __UpperCamelCase			):
														# 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__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=None				,      lowerCamelCase__=None			) ->							List[Any]:

							if modules_to_not_convert is None:
														A         =					[]

							A      ,  A         =					_replace_with_bnb_layers(
							    __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase			)
							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__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=None				,      lowerCamelCase__=None				,      ) ->							int:
							A         =					False
							for name, module in model.named_children():
														if current_key_name is None:
																					A         =					[]
														current_key_name.append(__UpperCamelCase			)
														if isinstance(__UpperCamelCase				,      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(__UpperCamelCase			)
																					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=__UpperCamelCase				,      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_(__UpperCamelCase			)
																												setattr(__UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase			)
																												A         =					True
														if len(list(module.children()			)			) > 0:
																					A      ,  A         =					_replace_with_bnb_layers(
																					    __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase			)
																					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__			(     lowerCamelCase__			) ->							Union[str, Any]:
							# Create a copy of the model
							with init_empty_weights():
														A         =					deepcopy(__UpperCamelCase			)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

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

							# Check if it is a base model
							A         =					False
							if hasattr(__UpperCamelCase				,      'base_model_prefix'			):
														A         =					not hasattr(__UpperCamelCase				,      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(__UpperCamelCase			) - set(__UpperCamelCase			)
							A         =					list(set(__UpperCamelCase			)			) + list(__UpperCamelCase			)

							# 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(__UpperCamelCase				,      ''			)
														filtered_module_names.append(__UpperCamelCase			)

							return filtered_module_names

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							str:
							for m in model.modules():
														if isinstance(__UpperCamelCase				,      bnb.nn.Linearabit			):
																					return True
							return False

def   lowerCAmelCase__			(     lowerCamelCase__			) ->							Optional[int]:
							return next(parameter.parameters()			).device

def   lowerCAmelCase__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__			) ->							Union[str, Any]:
							# 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(__UpperCamelCase				,      __UpperCamelCase				,      0				,      dtype=__UpperCamelCase				,      value=__UpperCamelCase			)
														A         =					param_name
														A         =					model
														if "." in tensor_name:
																					A         =					tensor_name.split('.'			)
																					for split in splits[:-1]:
																												A         =					getattr(__UpperCamelCase				,      __UpperCamelCase			)
																												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]				,      __UpperCamelCase				,      __UpperCamelCase				,      index=__UpperCamelCase			)
														if hasattr(module._parameters[tensor_name]				,      'SCB'			):
																					offload_weight(
																					    module._parameters[tensor_name].SCB				,      param_name.replace('weight'				,      'SCB'			)				,      __UpperCamelCase				,      index=__UpperCamelCase				,      )
							else:
														offload_weight(__UpperCamelCase				,      __UpperCamelCase				,      __UpperCamelCase				,      index=__UpperCamelCase			)
														offload_weight(__UpperCamelCase				,      param_name.replace('weight'				,      'SCB'			)				,      __UpperCamelCase				,      index=__UpperCamelCase			)

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








"""simple docstring"""







import gc
import unittest

from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_gpu,
    slow,
)

from .test_pipelines_common import ANY






@is_pipeline_test
class      UpperCAmelCase__		(      unittest.TestCase     ):
		lowerCAmelCase_       :	int 							=     MODEL_FOR_MASKED_LM_MAPPING
		lowerCAmelCase_       :	Tuple 							=     TF_MODEL_FOR_MASKED_LM_MAPPING



		def 					A_		( self  :    Tuple				)			->						int:






									'''simple docstring'''

									super().tearDown()
									# clean-up as much as possible GPU memory occupied by PyTorch
									gc.collect()
									if is_torch_available():
																import torch

																torch.cuda.empty_cache()



		@require_tf
		def 					A_		( self  :    int				)			->						Optional[int]:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='sshleifer/tiny-distilroberta-base'      ,							top_k=2      ,							framework='tf'				)
									A         =					unmasker('My name is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {'sequence': 'My name is grouped', 'score': 2.1E-0_5, 'token': 38_015, 'token_str': ' grouped'},
									        {'sequence': 'My name is accuser', 'score': 2.1E-0_5, 'token': 25_506, 'token_str': ' accuser'},
									    ]      ,							)

									A         =					unmasker('The largest city in France is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {
									            'sequence': 'The largest city in France is grouped',
									            'score': 2.1E-0_5,
									            'token': 38_015,
									            'token_str': ' grouped',
									        },
									        {
									            'sequence': 'The largest city in France is accuser',
									            'score': 2.1E-0_5,
									            'token': 25_506,
									            'token_str': ' accuser',
									        },
									    ]      ,							)

									A         =					unmasker('My name is <mask>'      ,							targets=[' Patrick', ' Clara', ' Teven']      ,							top_k=3				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {'sequence': 'My name is Clara', 'score': 2E-0_5, 'token': 13_606, 'token_str': ' Clara'},
									        {'sequence': 'My name is Patrick', 'score': 2E-0_5, 'token': 3_499, 'token_str': ' Patrick'},
									        {'sequence': 'My name is Te', 'score': 1.9E-0_5, 'token': 2_941, 'token_str': ' Te'},
									    ]      ,							)



		@require_torch
		def 					A_		( self  :    str				)			->						int:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='sshleifer/tiny-distilroberta-base'      ,							top_k=2      ,							framework='pt'				)

									A         =					unmasker('My name is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {'sequence': 'My name is Maul', 'score': 2.2E-0_5, 'token': 35_676, 'token_str': ' Maul'},
									        {'sequence': 'My name isELS', 'score': 2.2E-0_5, 'token': 16_416, 'token_str': 'ELS'},
									    ]      ,							)

									A         =					unmasker('The largest city in France is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {
									            'sequence': 'The largest city in France is Maul',
									            'score': 2.2E-0_5,
									            'token': 35_676,
									            'token_str': ' Maul',
									        },
									        {'sequence': 'The largest city in France isELS', 'score': 2.2E-0_5, 'token': 16_416, 'token_str': 'ELS'},
									    ]      ,							)

									A         =					unmasker('My name is <mask>'      ,							targets=[' Patrick', ' Clara', ' Teven']      ,							top_k=3				)
									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        {'sequence': 'My name is Patrick', 'score': 2.1E-0_5, 'token': 3_499, 'token_str': ' Patrick'},
									        {'sequence': 'My name is Te', 'score': 2E-0_5, 'token': 2_941, 'token_str': ' Te'},
									        {'sequence': 'My name is Clara', 'score': 2E-0_5, 'token': 13_606, 'token_str': ' Clara'},
									    ]      ,							)

									A         =					unmasker('My name is <mask> <mask>'      ,							top_k=2				)

									self.assertEqual(
									    nested_simplify(snake_case      ,							decimals=6				)      ,							[
									        [
									            {
									                'score': 2.2E-0_5,
									                'token': 35_676,
									                'token_str': ' Maul',
									                'sequence': '<s>My name is Maul<mask></s>',
									            },
									            {'score': 2.2E-0_5, 'token': 16_416, 'token_str': 'ELS', 'sequence': '<s>My name isELS<mask></s>'},
									        ],
									        [
									            {
									                'score': 2.2E-0_5,
									                'token': 35_676,
									                'token_str': ' Maul',
									                'sequence': '<s>My name is<mask> Maul</s>',
									            },
									            {'score': 2.2E-0_5, 'token': 16_416, 'token_str': 'ELS', 'sequence': '<s>My name is<mask>ELS</s>'},
									        ],
									    ]      ,							)



		@require_torch_gpu
		def 					A_		( self  :    Tuple				)			->						List[str]:






									'''simple docstring'''

									A         =					pipeline('fill-mask'      ,							model='hf-internal-testing/tiny-random-distilbert'      ,							device=0      ,							framework='pt'				)

									# convert model to fp16
									pipe.model.half()

									A         =					pipe('Paris is the [MASK] of France.'				)
									# We actually don't care about the result, we just want to make sure
									# it works, meaning the float16 tensor got casted back to float32
									# for postprocessing.
									self.assertIsInstance(snake_case      ,							snake_case				)



		@slow
		@require_torch
		def 					A_		( self  :    List[Any]				)			->						int:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='distilroberta-base'      ,							top_k=2      ,							framework='pt'				)
									self.run_large_test(snake_case				)



		@slow
		@require_tf
		def 					A_		( self  :    Tuple				)			->						Optional[int]:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='distilroberta-base'      ,							top_k=2      ,							framework='tf'				)
									self.run_large_test(snake_case				)



		def 					A_		( self  :    Dict      ,							snake_case  :    List[Any]				)			->						Optional[int]:






									'''simple docstring'''

									A         =					unmasker('My name is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case				)      ,							[
									        {'sequence': 'My name is John', 'score': 0.008, 'token': 610, 'token_str': ' John'},
									        {'sequence': 'My name is Chris', 'score': 0.007, 'token': 1_573, 'token_str': ' Chris'},
									    ]      ,							)
									A         =					unmasker('The largest city in France is <mask>'				)
									self.assertEqual(
									    nested_simplify(snake_case				)      ,							[
									        {
									            'sequence': 'The largest city in France is Paris',
									            'score': 0.251,
									            'token': 2_201,
									            'token_str': ' Paris',
									        },
									        {
									            'sequence': 'The largest city in France is Lyon',
									            'score': 0.214,
									            'token': 12_790,
									            'token_str': ' Lyon',
									        },
									    ]      ,							)

									A         =					unmasker('My name is <mask>'      ,							targets=[' Patrick', ' Clara', ' Teven']      ,							top_k=3				)
									self.assertEqual(
									    nested_simplify(snake_case				)      ,							[
									        {'sequence': 'My name is Patrick', 'score': 0.005, 'token': 3_499, 'token_str': ' Patrick'},
									        {'sequence': 'My name is Clara', 'score': 0.000, 'token': 13_606, 'token_str': ' Clara'},
									        {'sequence': 'My name is Te', 'score': 0.000, 'token': 2_941, 'token_str': ' Te'},
									    ]      ,							)



		@require_torch
		def 					A_		( self  :    List[str]				)			->						Any:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='sshleifer/tiny-distilroberta-base'      ,							framework='pt'				)
									A         =					None
									A         =					None
									self.run_pipeline_test(snake_case      ,							[]				)



		@require_tf
		def 					A_		( self  :    Tuple				)			->						Dict:






									'''simple docstring'''

									A         =					pipeline(task='fill-mask'      ,							model='sshleifer/tiny-distilroberta-base'      ,							framework='tf'				)
									A         =					None
									A         =					None
									self.run_pipeline_test(snake_case      ,							[]				)



		def 					A_		( self  :    str      ,							snake_case  :    Union[str, Any]      ,							snake_case  :    Optional[int]      ,							snake_case  :    Optional[Any]				)			->						Union[str, Any]:






									'''simple docstring'''

									if tokenizer is None or tokenizer.mask_token_id is None:
																self.skipTest('The provided tokenizer has no mask token, (probably reformer or wav2vec2)'				)

									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)
									A         =					[
									    f"""This is another {tokenizer.mask_token} test""",
									]
									return fill_masker, examples



		def 					A_		( self  :    Any      ,							snake_case  :    Any      ,							snake_case  :    Optional[Any]				)			->						Optional[int]:






									'''simple docstring'''

									A         =					fill_masker.tokenizer
									A         =					fill_masker.model

									A         =					fill_masker(
									    f"""This is a {tokenizer.mask_token}"""      ,							)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)

									A         =					fill_masker([f"""This is a {tokenizer.mask_token}"""]				)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)

									A         =					fill_masker([f"""This is a {tokenizer.mask_token}""", f"""Another {tokenizer.mask_token} great test."""]				)
									self.assertEqual(
									    snake_case      ,							[
									        [
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        ],
									        [
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        ],
									    ]      ,							)

									with self.assertRaises(snake_case				):
																fill_masker([None]				)
									# No mask_token is not supported
									with self.assertRaises(snake_case				):
																fill_masker('This is'				)

									self.run_test_top_k(snake_case      ,							snake_case				)
									self.run_test_targets(snake_case      ,							snake_case				)
									self.run_test_top_k_targets(snake_case      ,							snake_case				)
									self.fill_mask_with_duplicate_targets_and_top_k(snake_case      ,							snake_case				)
									self.fill_mask_with_multiple_masks(snake_case      ,							snake_case				)



		def 					A_		( self  :    str      ,							snake_case  :    Any      ,							snake_case  :    Optional[int]				)			->						str:






									'''simple docstring'''

									A         =					tokenizer.get_vocab()
									A         =					sorted(vocab.keys()				)[:2]
									# Pipeline argument
									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case      ,							targets=snake_case				)
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""				)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)
									A         =					{vocab[el] for el in targets}
									self.assertEqual({el['token'] for el in outputs}      ,							snake_case				)
									A         =					[tokenizer.decode([x]				) for x in target_ids]
									self.assertEqual({el['token_str'] for el in outputs}      ,							set(snake_case				)				)

									# Call argument
									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=snake_case				)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)
									A         =					{vocab[el] for el in targets}
									self.assertEqual({el['token'] for el in outputs}      ,							snake_case				)
									A         =					[tokenizer.decode([x]				) for x in target_ids]
									self.assertEqual({el['token_str'] for el in outputs}      ,							set(snake_case				)				)

									# Score equivalence
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=snake_case				)
									A         =					[top_mask['token_str'] for top_mask in outputs]
									A         =					[top_mask['score'] for top_mask in outputs]

									# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
									if set(snake_case				) == set(snake_case				):
																A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=snake_case				)
																A         =					[top_mask['score'] for top_mask in unmasked_targets]
																self.assertEqual(nested_simplify(snake_case				)      ,							nested_simplify(snake_case				)				)

									# Raises with invalid
									with self.assertRaises(snake_case				):
																A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=[]				)
									# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
									if "" not in tokenizer.get_vocab():
																with self.assertRaises(snake_case				):
																							A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=['']				)
																with self.assertRaises(snake_case				):
																							A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							targets=''				)



		def 					A_		( self  :    Any      ,							snake_case  :    Optional[Any]      ,							snake_case  :    int				)			->						List[Any]:






									'''simple docstring'''

									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case      ,							top_k=2				)
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""				)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)

									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							top_k=2				)
									self.assertEqual(
									    snake_case      ,							[
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									    ]      ,							)
									self.assertEqual(nested_simplify(snake_case				)      ,							nested_simplify(snake_case				)				)



		def 					A_		( self  :    str      ,							snake_case  :    List[str]      ,							snake_case  :    Dict				)			->						Tuple:






									'''simple docstring'''

									A         =					tokenizer.get_vocab()
									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)

									# top_k=2, ntargets=3
									A         =					sorted(vocab.keys()				)[:3]
									A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							top_k=2      ,							targets=snake_case				)

									# If we use the most probably targets, and filter differently, we should still
									# have the same results
									A         =					[el['token_str'] for el in sorted(snake_case      ,							key=lambda snake_case				: x["score"]      ,							reverse=snake_case				)]
									# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
									if set(snake_case				).issubset(snake_case				):
																A         =					fill_masker(f"""This is a {tokenizer.mask_token}"""      ,							top_k=3      ,							targets=snake_case				)
																# They should yield exactly the same result
																self.assertEqual(nested_simplify(snake_case				)      ,							nested_simplify(snake_case				)				)



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    Union[str, Any]      ,							snake_case  :    Dict				)			->						int:






									'''simple docstring'''

									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)
									A         =					tokenizer.get_vocab()
									# String duplicates + id duplicates
									A         =					sorted(vocab.keys()				)[:3]
									A         =					[targets[0], targets[1], targets[0], targets[2], targets[1]]
									A         =					fill_masker(f"""My name is {tokenizer.mask_token}"""      ,							targets=snake_case      ,							top_k=10				)

									# The target list contains duplicates, so we can't output more
									# than them
									self.assertEqual(len(snake_case				)      ,							3				)



		def 					A_		( self  :    str      ,							snake_case  :    List[Any]      ,							snake_case  :    Union[str, Any]				)			->						Union[str, Any]:






									'''simple docstring'''

									A         =					FillMaskPipeline(model=snake_case      ,							tokenizer=snake_case				)

									A         =					fill_masker(
									    f"""This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}"""      ,							top_k=2				)
									self.assertEqual(
									    snake_case      ,							[
									        [
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        ],
									        [
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        ],
									        [
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									            {'sequence': ANY(snake_case				), 'score': ANY(snake_case				), 'token': ANY(snake_case				), 'token_str': ANY(snake_case				)},
									        ],
									    ]      ,							)



