





import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("""0.12.2"""):
						raise Exception("""requires fairseq >= 0.12.2""")
if version.parse(fairseq.__version__) > version.parse("""2"""):
						raise Exception("""requires fairseq < v2""")

logging.set_verbosity_info()
_SCREAMING_SNAKE_CASE      	=		logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE      	=		"""Hello, World!"""
_SCREAMING_SNAKE_CASE      	=		"""en_XX"""


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	snake_case_		:			Tuple											=	Path('data_bin'   )
	snake_case_		:			List[str]											=	FairseqXmodModel.from_pretrained(
	    model_name_or_path=str(Path(__a   ).parent   )   , checkpoint_file=Path(__a   ).name   , _name='xmod_base'   , arch='xmod_base'   , task='multilingual_masked_lm'   , data_name_or_path=str(__a   )   , bpe='sentencepiece'   , sentencepiece_model=str(Path(__a   ).parent / 'sentencepiece.bpe.model'   )   , src_dict=str(data_dir / 'dict.txt'   )   , )
	xmod.eval()  # disable dropout
	print(__a   )

	snake_case_		:			Dict											=	xmod.model.encoder.sentence_encoder
	snake_case_		:			List[Any]											=	XmodConfig(
	    vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings   , hidden_size=xmod.cfg.model.encoder_embed_dim   , num_hidden_layers=xmod.cfg.model.encoder_layers   , num_attention_heads=xmod.cfg.model.encoder_attention_heads   , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim   , max_position_embeddings=5_14   , type_vocab_size=1   , layer_norm_eps=1E-5   , pre_norm=xmod.cfg.model.encoder_normalize_before   , adapter_reduction_factor=getattr(xmod.cfg.model   , 'bottleneck'   , 2   )   , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm   , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm   , ln_before_adapter=xmod.cfg.model.ln_before_adapter   , languages=xmod.cfg.model.languages   , )
	if classification_head:
		snake_case_		:			Union[str, Any]											=	xmod.model.classification_heads['mnli'].out_proj.weight.shape[0]

	print('Our X-MOD config:'   , __a   )

	snake_case_		:			Any											=	XmodForSequenceClassification(__a   ) if classification_head else XmodForMaskedLM(__a   )
	model.eval()

	# Now let's copy all the weights.
	# Embeddings
	snake_case_		:			Any											=	xmod_sent_encoder.embed_tokens.weight
	snake_case_		:			Tuple											=	xmod_sent_encoder.embed_positions.weight
	snake_case_		:			List[Any]											=	torch.zeros_like(
	    model.roberta.embeddings.token_type_embeddings.weight   )  # just zero them out b/c xmod doesn't use them.

	snake_case_		:			List[str]											=	xmod_sent_encoder.layernorm_embedding.weight
	snake_case_		:			int											=	xmod_sent_encoder.layernorm_embedding.bias

	for i in range(config.num_hidden_layers   ):
		# Encoder: start of layer
		snake_case_		:			Any											=	model.roberta.encoder.layer[i]
		snake_case_		:			Union[str, Any]											=	xmod_sent_encoder.layers[i]

		# self attention
		snake_case_		:			List[Any]											=	layer.attention.self
		if not (
		    xmod_layer.self_attn.k_proj.weight.data.shape
		    == xmod_layer.self_attn.q_proj.weight.data.shape
		    == xmod_layer.self_attn.v_proj.weight.data.shape
		    == torch.Size((config.hidden_size, config.hidden_size)   )
		):
			raise AssertionError('Dimensions of self-attention weights do not match.'   )

		snake_case_		:			Optional[int]											=	xmod_layer.self_attn.q_proj.weight
		snake_case_		:			Optional[Any]											=	xmod_layer.self_attn.q_proj.bias
		snake_case_		:			Tuple											=	xmod_layer.self_attn.k_proj.weight
		snake_case_		:			int											=	xmod_layer.self_attn.k_proj.bias
		snake_case_		:			List[str]											=	xmod_layer.self_attn.v_proj.weight
		snake_case_		:			Optional[int]											=	xmod_layer.self_attn.v_proj.bias

		# self-attention output
		snake_case_		:			Tuple											=	layer.attention.output
		if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
			raise AssertionError('Dimensions of self-attention output weights do not match.'   )
		snake_case_		:			int											=	xmod_layer.self_attn.out_proj.weight
		snake_case_		:			Dict											=	xmod_layer.self_attn.out_proj.bias
		snake_case_		:			Tuple											=	xmod_layer.self_attn_layer_norm.weight
		snake_case_		:			Tuple											=	xmod_layer.self_attn_layer_norm.bias

		# intermediate
		snake_case_		:			Optional[Any]											=	layer.intermediate
		if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
			raise AssertionError('Dimensions of intermediate weights do not match.'   )
		snake_case_		:			str											=	xmod_layer.fca.weight
		snake_case_		:			str											=	xmod_layer.fca.bias

		# output
		snake_case_		:			Tuple											=	layer.output
		if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
			raise AssertionError('Dimensions of feed-forward weights do not match.'   )
		snake_case_		:			Dict											=	xmod_layer.fca.weight
		snake_case_		:			List[str]											=	xmod_layer.fca.bias
		snake_case_		:			List[Any]											=	xmod_layer.final_layer_norm.weight
		snake_case_		:			Union[str, Any]											=	xmod_layer.final_layer_norm.bias
		if bert_output.adapter_layer_norm is not None:
			snake_case_		:			str											=	xmod_layer.adapter_layer_norm.weight
			snake_case_		:			Optional[Any]											=	xmod_layer.adapter_layer_norm.bias

		if sorted(bert_output.adapter_modules.keys()   ) != sorted(xmod_layer.adapter_modules.keys()   ):
			raise AssertionError('Lists of language adapters do not match.'   )
		for lang_code, adapter in xmod_layer.adapter_modules.items():
			snake_case_		:			Any											=	bert_output.adapter_modules[lang_code]
			snake_case_		:			int											=	xmod_layer.adapter_modules[lang_code]
			snake_case_		:			Any											=	from_adapter.fca.weight
			snake_case_		:			str											=	from_adapter.fca.bias
			snake_case_		:			List[str]											=	from_adapter.fca.weight
			snake_case_		:			Tuple											=	from_adapter.fca.bias

		# end of layer

	if xmod_sent_encoder.layer_norm is not None:
		snake_case_		:			int											=	xmod_sent_encoder.layer_norm.weight
		snake_case_		:			Optional[int]											=	xmod_sent_encoder.layer_norm.bias

	if classification_head:
		snake_case_		:			Dict											=	xmod.model.classification_heads['mnli'].dense.weight
		snake_case_		:			Optional[int]											=	xmod.model.classification_heads['mnli'].dense.bias
		snake_case_		:			str											=	xmod.model.classification_heads['mnli'].out_proj.weight
		snake_case_		:			List[Any]											=	xmod.model.classification_heads['mnli'].out_proj.bias
	else:
		# LM Head
		snake_case_		:			Union[str, Any]											=	xmod.model.encoder.lm_head.dense.weight
		snake_case_		:			Union[str, Any]											=	xmod.model.encoder.lm_head.dense.bias
		snake_case_		:			Optional[int]											=	xmod.model.encoder.lm_head.layer_norm.weight
		snake_case_		:			List[Any]											=	xmod.model.encoder.lm_head.layer_norm.bias
		snake_case_		:			Any											=	xmod.model.encoder.lm_head.weight
		snake_case_		:			Any											=	xmod.model.encoder.lm_head.bias

	# Let's check that we get the same results.
	snake_case_		:			List[str]											=	xmod.encode(__a   ).unsqueeze(0   )  # batch of size 1
	model.roberta.set_default_language(__a   )

	snake_case_		:			str											=	model(__a   )[0]
	if classification_head:
		snake_case_		:			Tuple											=	xmod.model.classification_heads['mnli'](xmod.extract_features(__a   )   )
	else:
		snake_case_		:			Optional[Any]											=	xmod.model(__a   , lang_id=[SAMPLE_LANGUAGE]   )[0]
	print(our_output.shape   , their_output.shape   )
	snake_case_		:			Dict											=	torch.max(torch.abs(our_output - their_output   )   ).item()
	print(f"""max_absolute_diff = {max_absolute_diff}"""   )  # ~ 1e-7
	snake_case_		:			str											=	torch.allclose(__a   , __a   , atol=1E-3   )
	print('Do both models output the same tensors?'   , '🔥' if success else '💩'   )
	if not success:
		raise Exception('Something went wRoNg'   )

	Path(__a   ).mkdir(parents=__a   , exist_ok=__a   )
	print(f"""Saving model to {pytorch_dump_folder_path}"""   )
	model.save_pretrained(__a   )


if __name__ == "__main__":
						_SCREAMING_SNAKE_CASE      	=		argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    """--xmod_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump."""
						)
						parser.add_argument(
						    """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
						)
						parser.add_argument(
						    """--classification_head""", action="""store_true""", help="""Whether to convert a final classification head."""
						)
						_SCREAMING_SNAKE_CASE      	=		parser.parse_args()
						convert_xmod_checkpoint_to_pytorch(
						    args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
						)








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 SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):
						__magic_name__:			Union[str, Any]       =       MODEL_FOR_MASKED_LM_MAPPING
						__magic_name__:			Optional[int]       =       TF_MODEL_FOR_MASKED_LM_MAPPING






						def UpperCAmelCase_				(      self      :      str	)							->    str:







							"""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 UpperCAmelCase_				(      self      :      Optional[int]	)							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			int											=	pipeline(task='fill-mask'		,   model='sshleifer/tiny-distilroberta-base'		,   top_k=2		,   framework='tf'	)
							snake_case_		:			Optional[Any]											=	unmasker('My name is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {'sequence': 'My name is grouped', 'score': 2.1E-05, 'token': 38015, 'token_str': ' grouped'},
							        {'sequence': 'My name is accuser', 'score': 2.1E-05, 'token': 25506, 'token_str': ' accuser'},
							    ]		,   )

							snake_case_		:			int											=	unmasker('The largest city in France is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {
							            'sequence': 'The largest city in France is grouped',
							            'score': 2.1E-05,
							            'token': 38015,
							            'token_str': ' grouped',
							        },
							        {
							            'sequence': 'The largest city in France is accuser',
							            'score': 2.1E-05,
							            'token': 25506,
							            'token_str': ' accuser',
							        },
							    ]		,   )

							snake_case_		:			Any											=	unmasker('My name is <mask>'		,   targets=[' Patrick', ' Clara', ' Teven']		,   top_k=3	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {'sequence': 'My name is Clara', 'score': 2E-05, 'token': 13606, 'token_str': ' Clara'},
							        {'sequence': 'My name is Patrick', 'score': 2E-05, 'token': 3499, 'token_str': ' Patrick'},
							        {'sequence': 'My name is Te', 'score': 1.9E-05, 'token': 2941, 'token_str': ' Te'},
							    ]		,   )






						@require_torch
						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Optional[Any]:







							"""simple docstring"""


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

							snake_case_		:			Tuple											=	unmasker('My name is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {'sequence': 'My name is Maul', 'score': 2.2E-05, 'token': 35676, 'token_str': ' Maul'},
							        {'sequence': 'My name isELS', 'score': 2.2E-05, 'token': 16416, 'token_str': 'ELS'},
							    ]		,   )

							snake_case_		:			int											=	unmasker('The largest city in France is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {
							            'sequence': 'The largest city in France is Maul',
							            'score': 2.2E-05,
							            'token': 35676,
							            'token_str': ' Maul',
							        },
							        {'sequence': 'The largest city in France isELS', 'score': 2.2E-05, 'token': 16416, 'token_str': 'ELS'},
							    ]		,   )

							snake_case_		:			Any											=	unmasker('My name is <mask>'		,   targets=[' Patrick', ' Clara', ' Teven']		,   top_k=3	)
							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        {'sequence': 'My name is Patrick', 'score': 2.1E-05, 'token': 3499, 'token_str': ' Patrick'},
							        {'sequence': 'My name is Te', 'score': 2E-05, 'token': 2941, 'token_str': ' Te'},
							        {'sequence': 'My name is Clara', 'score': 2E-05, 'token': 13606, 'token_str': ' Clara'},
							    ]		,   )

							snake_case_		:			List[Any]											=	unmasker('My name is <mask> <mask>'		,   top_k=2	)

							self.assertEqual(
							    nested_simplify(_A		,   decimals=6	)		,   [
							        [
							            {
							                'score': 2.2E-05,
							                'token': 35676,
							                'token_str': ' Maul',
							                'sequence': '<s>My name is Maul<mask></s>',
							            },
							            {'score': 2.2E-05, 'token': 16416, 'token_str': 'ELS', 'sequence': '<s>My name isELS<mask></s>'},
							        ],
							        [
							            {
							                'score': 2.2E-05,
							                'token': 35676,
							                'token_str': ' Maul',
							                'sequence': '<s>My name is<mask> Maul</s>',
							            },
							            {'score': 2.2E-05, 'token': 16416, 'token_str': 'ELS', 'sequence': '<s>My name is<mask>ELS</s>'},
							        ],
							    ]		,   )






						@require_torch_gpu
						def UpperCAmelCase_				(      self      :      str	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	pipeline('fill-mask'		,   model='hf-internal-testing/tiny-random-distilbert'		,   device=0		,   framework='pt'	)

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

							snake_case_		:			Tuple											=	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(_A		,   _A	)






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







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	pipeline(task='fill-mask'		,   model='distilroberta-base'		,   top_k=2		,   framework='pt'	)
							self.run_large_test(_A	)






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







							"""simple docstring"""


							snake_case_		:			Dict											=	pipeline(task='fill-mask'		,   model='distilroberta-base'		,   top_k=2		,   framework='tf'	)
							self.run_large_test(_A	)






						def UpperCAmelCase_				(      self      :      Dict		,   _A      :      List[Any]	)							->    Union[str, Any]:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	unmasker('My name is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A	)		,   [
							        {'sequence': 'My name is John', 'score': 0.0_0_8, 'token': 610, 'token_str': ' John'},
							        {'sequence': 'My name is Chris', 'score': 0.0_0_7, 'token': 1573, 'token_str': ' Chris'},
							    ]		,   )
							snake_case_		:			List[Any]											=	unmasker('The largest city in France is <mask>'	)
							self.assertEqual(
							    nested_simplify(_A	)		,   [
							        {
							            'sequence': 'The largest city in France is Paris',
							            'score': 0.2_5_1,
							            'token': 2201,
							            'token_str': ' Paris',
							        },
							        {
							            'sequence': 'The largest city in France is Lyon',
							            'score': 0.2_1_4,
							            'token': 12790,
							            'token_str': ' Lyon',
							        },
							    ]		,   )

							snake_case_		:			Tuple											=	unmasker('My name is <mask>'		,   targets=[' Patrick', ' Clara', ' Teven']		,   top_k=3	)
							self.assertEqual(
							    nested_simplify(_A	)		,   [
							        {'sequence': 'My name is Patrick', 'score': 0.0_0_5, 'token': 3499, 'token_str': ' Patrick'},
							        {'sequence': 'My name is Clara', 'score': 0.0_0_0, 'token': 13606, 'token_str': ' Clara'},
							        {'sequence': 'My name is Te', 'score': 0.0_0_0, 'token': 2941, 'token_str': ' Te'},
							    ]		,   )






						@require_torch
						def UpperCAmelCase_				(      self      :      Optional[int]	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	pipeline(task='fill-mask'		,   model='sshleifer/tiny-distilroberta-base'		,   framework='pt'	)
							snake_case_		:			Tuple											=	None
							snake_case_		:			str											=	None
							self.run_pipeline_test(_A		,   []	)






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







							"""simple docstring"""


							snake_case_		:			List[Any]											=	pipeline(task='fill-mask'		,   model='sshleifer/tiny-distilroberta-base'		,   framework='tf'	)
							snake_case_		:			List[str]											=	None
							snake_case_		:			List[str]											=	None
							self.run_pipeline_test(_A		,   []	)






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      List[Any]		,   _A      :      Tuple		,   _A      :      Optional[int]	)							->    Optional[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)'	)

							snake_case_		:			Dict											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)
							snake_case_		:			Optional[Any]											=	[
							    F"""This is another {tokenizer.mask_token} test""",
							]
							return fill_masker, examples






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      str		,   _A      :      List[Any]	)							->    int:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	fill_masker.tokenizer
							snake_case_		:			List[Any]											=	fill_masker.model

							snake_case_		:			int											=	fill_masker(
							    F"""This is a {tokenizer.mask_token}"""		,   )
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )

							snake_case_		:			Dict											=	fill_masker([F"""This is a {tokenizer.mask_token}"""]	)
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )

							snake_case_		:			Optional[int]											=	fill_masker([F"""This is a {tokenizer.mask_token}""", F"""Another {tokenizer.mask_token} great test."""]	)
							self.assertEqual(
							    _A		,   [
							        [
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        ],
							        [
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        ],
							    ]		,   )

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

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






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Any		,   _A      :      Optional[int]	)							->    Any:







							"""simple docstring"""


							snake_case_		:			Dict											=	tokenizer.get_vocab()
							snake_case_		:			List[Any]											=	sorted(vocab.keys()	)[:2]
							# Pipeline argument
							snake_case_		:			Dict											=	FillMaskPipeline(model=_A		,   tokenizer=_A		,   targets=_A	)
							snake_case_		:			Optional[int]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""	)
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )
							snake_case_		:			List[str]											=	{vocab[el] for el in targets}
							self.assertEqual({el['token'] for el in outputs}		,   _A	)
							snake_case_		:			int											=	[tokenizer.decode([x]	) for x in target_ids]
							self.assertEqual({el['token_str'] for el in outputs}		,   set(_A	)	)

							# Call argument
							snake_case_		:			Dict											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)
							snake_case_		:			Optional[int]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   targets=_A	)
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )
							snake_case_		:			Any											=	{vocab[el] for el in targets}
							self.assertEqual({el['token'] for el in outputs}		,   _A	)
							snake_case_		:			Tuple											=	[tokenizer.decode([x]	) for x in target_ids]
							self.assertEqual({el['token_str'] for el in outputs}		,   set(_A	)	)

							# Score equivalence
							snake_case_		:			Union[str, Any]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   targets=_A	)
							snake_case_		:			Any											=	[top_mask['token_str'] for top_mask in outputs]
							snake_case_		:			Optional[Any]											=	[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(_A	) == set(_A	):
								snake_case_		:			int											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   targets=_A	)
								snake_case_		:			Union[str, Any]											=	[top_mask['score'] for top_mask in unmasked_targets]
								self.assertEqual(nested_simplify(_A	)		,   nested_simplify(_A	)	)

							# Raises with invalid
							with self.assertRaises(_A	):
								snake_case_		:			Dict											=	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(_A	):
									snake_case_		:			Tuple											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   targets=['']	)
								with self.assertRaises(_A	):
									snake_case_		:			Union[str, Any]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   targets=''	)






						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      Any		,   _A      :      Optional[Any]	)							->    Any:







							"""simple docstring"""


							snake_case_		:			str											=	FillMaskPipeline(model=_A		,   tokenizer=_A		,   top_k=2	)
							snake_case_		:			List[str]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""	)
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )

							snake_case_		:			Any											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)
							snake_case_		:			int											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   top_k=2	)
							self.assertEqual(
							    _A		,   [
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							    ]		,   )
							self.assertEqual(nested_simplify(_A	)		,   nested_simplify(_A	)	)






						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      Any		,   _A      :      Dict	)							->    str:







							"""simple docstring"""


							snake_case_		:			str											=	tokenizer.get_vocab()
							snake_case_		:			Tuple											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)

							# top_k=2, ntargets=3
							snake_case_		:			str											=	sorted(vocab.keys()	)[:3]
							snake_case_		:			Union[str, Any]											=	fill_masker(F"""This is a {tokenizer.mask_token}"""		,   top_k=2		,   targets=_A	)

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






						def UpperCAmelCase_				(      self      :      str		,   _A      :      Dict		,   _A      :      Tuple	)							->    Dict:







							"""simple docstring"""


							snake_case_		:			Tuple											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)
							snake_case_		:			List[Any]											=	tokenizer.get_vocab()
							# String duplicates + id duplicates
							snake_case_		:			str											=	sorted(vocab.keys()	)[:3]
							snake_case_		:			Tuple											=	[targets[0], targets[1], targets[0], targets[2], targets[1]]
							snake_case_		:			str											=	fill_masker(F"""My name is {tokenizer.mask_token}"""		,   targets=_A		,   top_k=10	)

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






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      str		,   _A      :      Union[str, Any]	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Union[str, Any]											=	FillMaskPipeline(model=_A		,   tokenizer=_A	)

							snake_case_		:			List[str]											=	fill_masker(
							    F"""This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}"""		,   top_k=2	)
							self.assertEqual(
							    _A		,   [
							        [
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        ],
							        [
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        ],
							        [
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							            {'sequence': ANY(_A	), 'score': ANY(_A	), 'token': ANY(_A	), 'token_str': ANY(_A	)},
							        ],
							    ]		,   )

