




'''simple docstring'''

import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple

import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging


logging.set_verbosity_info()
a       :						Optional[Any]								=		logging.get_logger()



@dataclass
class 		SCREAMING_SNAKE_CASE__  :
			__SCREAMING_SNAKE_CASE    =			42
			__SCREAMING_SNAKE_CASE    =			field(default_factory=UpperCAmelCase__	)
			__SCREAMING_SNAKE_CASE    =			field(default_factory=UpperCAmelCase__	)





			def 							A (      self						:    List[str]      ,		a_						:    List[str]      ,		a_						:    Optional[Any]      ,		a_						:    int							):



						"""simple docstring"""




						__snake_case			=		len(list(m.modules()							)							) == 1 or isinstance(_UpperCAmelCase      ,		nn.Convad							) or isinstance(_UpperCAmelCase      ,		nn.BatchNormad							)
						if has_not_submodules:
									self.traced.append(_UpperCAmelCase							)





			def __call__(      self						:    Tuple      ,		a_						:    Tuple							):



						"""simple docstring"""




						for m in self.module.modules():
									self.handles.append(m.register_forward_hook(self._forward_hook							)							)
						self.module(_UpperCAmelCase							)
						[x.remove() for x in self.handles]
						return self






			@property
			def 							A (      self						:    List[Any]							):



						"""simple docstring"""




						return list(filter(lambda a_							: len(list(x.state_dict().keys()							)							) > 0      ,		self.traced							)							)







@dataclass
class 		SCREAMING_SNAKE_CASE__  :
			__SCREAMING_SNAKE_CASE    =			42
			__SCREAMING_SNAKE_CASE    =			42
			__SCREAMING_SNAKE_CASE    =			1
			__SCREAMING_SNAKE_CASE    =			field(default_factory=UpperCAmelCase__	)
			__SCREAMING_SNAKE_CASE    =			field(default_factory=UpperCAmelCase__	)
			__SCREAMING_SNAKE_CASE    =			True





			def __call__(      self						:    str      ,		a_						:    Any							):



						"""simple docstring"""




						__snake_case			=		Tracker(self.dest							)(_UpperCAmelCase							).parametrized
						__snake_case			=		Tracker(self.src							)(_UpperCAmelCase							).parametrized

						__snake_case			=		list(filter(lambda a_							: type(_UpperCAmelCase							) not in self.src_skip      ,		_UpperCAmelCase							)							)
						__snake_case			=		list(filter(lambda a_							: type(_UpperCAmelCase							) not in self.dest_skip      ,		_UpperCAmelCase							)							)

						if len(_UpperCAmelCase							) != len(_UpperCAmelCase							) and self.raise_if_mismatch:
									raise Exception(
									    f'''Numbers of operations are different. Source module has {len(_UpperCAmelCase							)} operations while'''
									    f''' destination module has {len(_UpperCAmelCase							)}.'''							)

						for dest_m, src_m in zip(_UpperCAmelCase      ,		_UpperCAmelCase							):
									dest_m.load_state_dict(src_m.state_dict()							)
									if self.verbose == 1:
												print(f'''Transfered from={src_m} to={dest_m}'''							)







class 		SCREAMING_SNAKE_CASE__  (			nn.Module	):





			def __init__(      self						:    List[Any]      ,		a_						:    List[Any]							):



						"""simple docstring"""




						super().__init__()

						__snake_case			=		[]
						# - get the stem
						feature_blocks.append(("conv1", model.stem)							)
						# - get all the feature blocks
						for k, v in model.trunk_output.named_children():
									assert k.startswith("block"							), f'''Unexpected layer name {k}'''
									__snake_case			=		len(_UpperCAmelCase							) + 1
									feature_blocks.append((f'''res{block_index}''', v)							)

						__snake_case			=		nn.ModuleDict(_UpperCAmelCase							)






			def 							A (      self						:    Any      ,		a_						:    int							):



						"""simple docstring"""




						return get_trunk_forward_outputs(
						    _UpperCAmelCase      ,		out_feat_keys=_UpperCAmelCase      ,		feature_blocks=self._feature_blocks      ,		)







class 		SCREAMING_SNAKE_CASE__  (			UpperCAmelCase__	):





			def 							A (      self						:    Optional[Any]      ,		a_						:    Tuple							):



						"""simple docstring"""




						__snake_case			=		x.split("-"							)
						return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]							)






			def __getitem__(      self						:    Union[str, Any]      ,		a_						:    Tuple							):



						"""simple docstring"""




						if x not in self:
									__snake_case			=		self.convert_name_to_timm(_UpperCAmelCase							)
									__snake_case			=		partial(lambda: (timm.create_model(_UpperCAmelCase      ,		pretrained=_UpperCAmelCase							).eval(), None)							)

						else:
									__snake_case			=		super().__getitem__(_UpperCAmelCase							)

						return val







class 		SCREAMING_SNAKE_CASE__  (			UpperCAmelCase__	):





			def __getitem__(      self						:    Tuple      ,		a_						:    str							):



						"""simple docstring"""




						if "seer" in x and "in1k" not in x:
									__snake_case			=		RegNetModel
						else:
									__snake_case			=		RegNetForImageClassification
						return val







def __UpperCAmelCase	(   _UpperCAmelCase		:   List[Any]		,				_UpperCAmelCase		:   Tuple		,				_UpperCAmelCase		:   Optional[Any]						)      ->      Any:
			for from_key, to_key in keys:
						__snake_case			=		from_state_dict[from_key].clone()
						print(F'''Copied key={from_key} to={to_key}'''						)
			return to_state_dict


def __UpperCAmelCase	(   _UpperCAmelCase		:   Any		,				_UpperCAmelCase		:   int		,				_UpperCAmelCase		:   Optional[int]		,				_UpperCAmelCase		:   List[str]		,				_UpperCAmelCase		:   Optional[int]		,				_UpperCAmelCase		:   int = True		,				)      ->      List[str]:
			print(F'''Converting {name}...'''						)
			with torch.no_grad():
						__snake_case		,     __snake_case			=		from_model_func()
						__snake_case			=		our_model_func(__lowercase						).eval()
						__snake_case			=		ModuleTransfer(src=__lowercase		,				dest=__lowercase		,				raise_if_mismatch=__lowercase						)
						__snake_case			=		torch.randn((1, 3, 2_24, 2_24)						)
						module_transfer(__lowercase						)

			if from_state_dict is not None:
						__snake_case			=		[]
						# for seer - in1k finetuned we have to manually copy the head
						if "seer" in name and "in1k" in name:
									__snake_case			=		[("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")]
						__snake_case			=		manually_copy_vissl_head(__lowercase		,				our_model.state_dict()		,				__lowercase						)
						our_model.load_state_dict(__lowercase						)

			__snake_case			=		our_model(__lowercase		,				output_hidden_states=__lowercase						)
			__snake_case			=		(
			    our_outputs.logits if isinstance(__lowercase		,				__lowercase						) else our_outputs.last_hidden_state
			)

			__snake_case			=		from_model(__lowercase						)
			__snake_case			=		from_output[-1] if type(__lowercase						) is list else from_output

			# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
			if "seer" in name and "in1k" in name:
						__snake_case			=		our_outputs.hidden_states[-1]

			assert torch.allclose(__lowercase		,				__lowercase						), "The model logits don't match the original one."

			if push_to_hub:
						our_model.push_to_hub(
						    repo_path_or_name=save_directory / name		,				commit_message="Add model"		,				use_temp_dir=__lowercase		,				)

						__snake_case			=		2_24 if "seer" not in name else 3_84
						# we can use the convnext one
						__snake_case			=		AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k"		,				size=__lowercase						)
						image_processor.push_to_hub(
						    repo_path_or_name=save_directory / name		,				commit_message="Add image processor"		,				use_temp_dir=__lowercase		,				)

						print(F'''Pushed {name}'''						)


def __UpperCAmelCase	(   _UpperCAmelCase		:   Union[str, Any]		,				_UpperCAmelCase		:   Any = None		,				_UpperCAmelCase		:   int = True						)      ->      List[Any]:
			__snake_case			=		"imagenet-1k-id2label.json"
			__snake_case			=		10_00
			__snake_case			=		(1, num_labels)

			__snake_case			=		"huggingface/label-files"
			__snake_case			=		num_labels
			__snake_case			=		json.load(open(cached_download(hf_hub_url(__lowercase		,				__lowercase		,				repo_type="dataset"						)						)		,				"r"						)						)
			__snake_case			=		{int(__lowercase						): v for k, v in idalabel.items()}

			__snake_case			=		idalabel
			__snake_case			=		{v: k for k, v in idalabel.items()}

			__snake_case			=		partial(__lowercase		,				num_labels=__lowercase		,				idalabel=__lowercase		,				labelaid=__lowercase						)

			__snake_case			=		{
			    "regnet-x-002": ImageNetPreTrainedConfig(
			        depths=[1, 1, 4, 7]		,				hidden_sizes=[24, 56, 1_52, 3_68]		,				groups_width=8		,				layer_type="x"						),
			    "regnet-x-004": ImageNetPreTrainedConfig(
			        depths=[1, 2, 7, 12]		,				hidden_sizes=[32, 64, 1_60, 3_84]		,				groups_width=16		,				layer_type="x"						),
			    "regnet-x-006": ImageNetPreTrainedConfig(
			        depths=[1, 3, 5, 7]		,				hidden_sizes=[48, 96, 2_40, 5_28]		,				groups_width=24		,				layer_type="x"						),
			    "regnet-x-008": ImageNetPreTrainedConfig(
			        depths=[1, 3, 7, 5]		,				hidden_sizes=[64, 1_28, 2_88, 6_72]		,				groups_width=16		,				layer_type="x"						),
			    "regnet-x-016": ImageNetPreTrainedConfig(
			        depths=[2, 4, 10, 2]		,				hidden_sizes=[72, 1_68, 4_08, 9_12]		,				groups_width=24		,				layer_type="x"						),
			    "regnet-x-032": ImageNetPreTrainedConfig(
			        depths=[2, 6, 15, 2]		,				hidden_sizes=[96, 1_92, 4_32, 10_08]		,				groups_width=48		,				layer_type="x"						),
			    "regnet-x-040": ImageNetPreTrainedConfig(
			        depths=[2, 5, 14, 2]		,				hidden_sizes=[80, 2_40, 5_60, 13_60]		,				groups_width=40		,				layer_type="x"						),
			    "regnet-x-064": ImageNetPreTrainedConfig(
			        depths=[2, 4, 10, 1]		,				hidden_sizes=[1_68, 3_92, 7_84, 16_24]		,				groups_width=56		,				layer_type="x"						),
			    "regnet-x-080": ImageNetPreTrainedConfig(
			        depths=[2, 5, 15, 1]		,				hidden_sizes=[80, 2_40, 7_20, 19_20]		,				groups_width=1_20		,				layer_type="x"						),
			    "regnet-x-120": ImageNetPreTrainedConfig(
			        depths=[2, 5, 11, 1]		,				hidden_sizes=[2_24, 4_48, 8_96, 22_40]		,				groups_width=1_12		,				layer_type="x"						),
			    "regnet-x-160": ImageNetPreTrainedConfig(
			        depths=[2, 6, 13, 1]		,				hidden_sizes=[2_56, 5_12, 8_96, 20_48]		,				groups_width=1_28		,				layer_type="x"						),
			    "regnet-x-320": ImageNetPreTrainedConfig(
			        depths=[2, 7, 13, 1]		,				hidden_sizes=[3_36, 6_72, 13_44, 25_20]		,				groups_width=1_68		,				layer_type="x"						),
			    # y variant
			    "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7]		,				hidden_sizes=[24, 56, 1_52, 3_68]		,				groups_width=8						),
			    "regnet-y-004": ImageNetPreTrainedConfig(
			        depths=[1, 3, 6, 6]		,				hidden_sizes=[48, 1_04, 2_08, 4_40]		,				groups_width=8						),
			    "regnet-y-006": ImageNetPreTrainedConfig(
			        depths=[1, 3, 7, 4]		,				hidden_sizes=[48, 1_12, 2_56, 6_08]		,				groups_width=16						),
			    "regnet-y-008": ImageNetPreTrainedConfig(
			        depths=[1, 3, 8, 2]		,				hidden_sizes=[64, 1_28, 3_20, 7_68]		,				groups_width=16						),
			    "regnet-y-016": ImageNetPreTrainedConfig(
			        depths=[2, 6, 17, 2]		,				hidden_sizes=[48, 1_20, 3_36, 8_88]		,				groups_width=24						),
			    "regnet-y-032": ImageNetPreTrainedConfig(
			        depths=[2, 5, 13, 1]		,				hidden_sizes=[72, 2_16, 5_76, 15_12]		,				groups_width=24						),
			    "regnet-y-040": ImageNetPreTrainedConfig(
			        depths=[2, 6, 12, 2]		,				hidden_sizes=[1_28, 1_92, 5_12, 10_88]		,				groups_width=64						),
			    "regnet-y-064": ImageNetPreTrainedConfig(
			        depths=[2, 7, 14, 2]		,				hidden_sizes=[1_44, 2_88, 5_76, 12_96]		,				groups_width=72						),
			    "regnet-y-080": ImageNetPreTrainedConfig(
			        depths=[2, 4, 10, 1]		,				hidden_sizes=[1_68, 4_48, 8_96, 20_16]		,				groups_width=56						),
			    "regnet-y-120": ImageNetPreTrainedConfig(
			        depths=[2, 5, 11, 1]		,				hidden_sizes=[2_24, 4_48, 8_96, 22_40]		,				groups_width=1_12						),
			    "regnet-y-160": ImageNetPreTrainedConfig(
			        depths=[2, 4, 11, 1]		,				hidden_sizes=[2_24, 4_48, 12_32, 30_24]		,				groups_width=1_12						),
			    "regnet-y-320": ImageNetPreTrainedConfig(
			        depths=[2, 5, 12, 1]		,				hidden_sizes=[2_32, 6_96, 13_92, 37_12]		,				groups_width=2_32						),
			    # models created by SEER -> https://arxiv.org/abs/2202.08360
			    "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1]		,				hidden_sizes=[2_32, 6_96, 13_92, 37_12]		,				groups_width=2_32						),
			    "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1]		,				hidden_sizes=[3_28, 9_84, 19_68, 49_20]		,				groups_width=3_28						),
			    "regnet-y-1280-seer": RegNetConfig(
			        depths=[2, 7, 17, 1]		,				hidden_sizes=[5_28, 10_56, 29_04, 73_92]		,				groups_width=2_64						),
			    "regnet-y-2560-seer": RegNetConfig(
			        depths=[3, 7, 16, 1]		,				hidden_sizes=[6_40, 16_96, 25_44, 50_88]		,				groups_width=6_40						),
			    "regnet-y-10b-seer": ImageNetPreTrainedConfig(
			        depths=[2, 7, 17, 1]		,				hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80]		,				groups_width=10_10						),
			    # finetuned on imagenet
			    "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig(
			        depths=[2, 5, 12, 1]		,				hidden_sizes=[2_32, 6_96, 13_92, 37_12]		,				groups_width=2_32						),
			    "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig(
			        depths=[2, 5, 12, 1]		,				hidden_sizes=[3_28, 9_84, 19_68, 49_20]		,				groups_width=3_28						),
			    "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig(
			        depths=[2, 7, 17, 1]		,				hidden_sizes=[5_28, 10_56, 29_04, 73_92]		,				groups_width=2_64						),
			    "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig(
			        depths=[3, 7, 16, 1]		,				hidden_sizes=[6_40, 16_96, 25_44, 50_88]		,				groups_width=6_40						),
			    "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig(
			        depths=[2, 7, 17, 1]		,				hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80]		,				groups_width=10_10						),
			}

			__snake_case			=		NameToOurModelFuncMap()
			__snake_case			=		NameToFromModelFuncMap()
			# add seer weights logic

			def load_using_classy_vision(_UpperCAmelCase		:   str		,				_UpperCAmelCase		:   Tuple						) -> Tuple[nn.Module, Dict]:
						__snake_case			=		torch.hub.load_state_dict_from_url(__lowercase		,				model_dir=str(__lowercase						)		,				map_location="cpu"						)
						__snake_case			=		model_func()
						# check if we have a head, if yes add it
						__snake_case			=		files["classy_state_dict"]["base_model"]["model"]
						__snake_case			=		model_state_dict["trunk"]
						model.load_state_dict(__lowercase						)
						return model.eval(), model_state_dict["heads"]

			# pretrained
			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch"		,				lambda: FakeRegNetVisslWrapper(
			        RegNet(RegNetParams(depth=27		,				group_width=10_10		,				w_a=17_44		,				w_a=620.83		,				w_m=2.52						)						)						)		,				)

			# IN1K finetuned
			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch"		,				lambda: FakeRegNetVisslWrapper(RegNetYaaagf()						)		,				)

			__snake_case			=		partial(
			    __lowercase		,				"https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch"		,				lambda: FakeRegNetVisslWrapper(
			        RegNet(RegNetParams(depth=27		,				group_width=10_10		,				w_a=17_44		,				w_a=620.83		,				w_m=2.52						)						)						)		,				)

			if model_name:
						convert_weight_and_push(
						    __lowercase		,				names_to_from_model_map[model_name]		,				names_to_ours_model_map[model_name]		,				names_to_config[model_name]		,				__lowercase		,				__lowercase		,				)
			else:
						for model_name, config in names_to_config.items():
									convert_weight_and_push(
									    __lowercase		,				names_to_from_model_map[model_name]		,				names_to_ours_model_map[model_name]		,				__lowercase		,				__lowercase		,				__lowercase		,				)
			return config, expected_shape


if __name__ == "__main__":
						a       :						List[Any]								=		argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--model_name''',
						    default=None,
						    type=str,
						    help=(
						        '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,'''
						        ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'''
						    ),
						)
						parser.add_argument(
						    '''--pytorch_dump_folder_path''',
						    default=None,
						    type=Path,
						    required=True,
						    help='''Path to the output PyTorch model directory.''',
						)
						parser.add_argument(
						    '''--push_to_hub''',
						    default=True,
						    type=bool,
						    required=False,
						    help='''If True, push model and image processor to the hub.''',
						)

						a       :						Dict								=		parser.parse_args()

						a       :						Path								=		args.pytorch_dump_folder_path
						pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
						convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)













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     _a							(	unittest.TestCase     ):






  """simple docstring"""





  A_						       = MODEL_FOR_MASKED_LM_MAPPING
  A_						       = TF_MODEL_FOR_MASKED_LM_MAPPING




  def  _UpperCAmelCase  (  self			)      ->			List[str]:
     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			)      ->			str:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		top_k=2		,		framework='tf'			)
     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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'},
         ]		,		)

     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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',
             },
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		top_k=2		,		framework='pt'			)

     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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'},
         ]		,		)

     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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'},
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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'},
         ]		,		)

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

     self.assertEqual(
         nested_simplify(_UpperCAmelCase		,		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			)      ->			Optional[Any]:
     UpperCamelCase_						=  pipeline('fill-mask'		,		model='hf-internal-testing/tiny-random-distilbert'		,		device=0		,		framework='pt'			)

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

     UpperCamelCase_						=  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(_UpperCAmelCase		,		_UpperCAmelCase			)




  @slow
  @require_torch
  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='distilroberta-base'		,		top_k=2		,		framework='pt'			)
     self.run_large_test(_UpperCAmelCase			)




  @slow
  @require_tf
  def  _UpperCAmelCase  (  self			)      ->			Union[str, Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='distilroberta-base'		,		top_k=2		,		framework='tf'			)
     self.run_large_test(_UpperCAmelCase			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase			)      ->			Tuple:
     UpperCamelCase_						=  unmasker('My name is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {'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'},
         ]		,		)
     UpperCamelCase_						=  unmasker('The largest city in France is <mask>'			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {
                 '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',
             },
         ]		,		)

     UpperCamelCase_						=  unmasker('My name is <mask>'		,		targets=[' Patrick', ' Clara', ' Teven']		,		top_k=3			)
     self.assertEqual(
         nested_simplify(_UpperCAmelCase			)		,		[
             {'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			)      ->			List[Any]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		framework='pt'			)
     UpperCamelCase_						=  None
     UpperCamelCase_						=  None
     self.run_pipeline_test(_UpperCAmelCase		,		[]			)




  @require_tf
  def  _UpperCAmelCase  (  self			)      ->			Optional[int]:
     UpperCamelCase_						=  pipeline(task='fill-mask'		,		model='sshleifer/tiny-distilroberta-base'		,		framework='tf'			)
     UpperCamelCase_						=  None
     UpperCamelCase_						=  None
     self.run_pipeline_test(_UpperCAmelCase		,		[]			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[Any]:
     if tokenizer is None or tokenizer.mask_token_id is None:
        self.skipTest('The provided tokenizer has no mask token, (probably reformer or wav2vec2)'			)

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




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Union[str, Any]:
     UpperCamelCase_						=  fill_masker.tokenizer
     UpperCamelCase_						=  fill_masker.model

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

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

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

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

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




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

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

     # Score equivalence
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase			)
     UpperCamelCase_						=  [top_mask['token_str'] for top_mask in outputs]
     UpperCamelCase_						=  [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(_UpperCAmelCase			) == set(_UpperCAmelCase			):
        UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase			)
        UpperCamelCase_						=  [top_mask['score'] for top_mask in unmasked_targets]
        self.assertEqual(nested_simplify(_UpperCAmelCase			)		,		nested_simplify(_UpperCAmelCase			)			)

     # Raises with invalid
     with self.assertRaises(_UpperCAmelCase			):
        UpperCamelCase_						=  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(_UpperCAmelCase			):
           UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=['']			)
        with self.assertRaises(_UpperCAmelCase			):
           UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""		,		targets=''			)




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Tuple:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase		,		top_k=2			)
     UpperCamelCase_						=  fill_masker(f"""This is a {tokenizer.mask_token}"""			)
     self.assertEqual(
         _UpperCAmelCase		,		[
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
             {'sequence': ANY(_UpperCAmelCase			), 'score': ANY(_UpperCAmelCase			), 'token': ANY(_UpperCAmelCase			), 'token_str': ANY(_UpperCAmelCase			)},
         ]		,		)

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




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[Any]:
     UpperCamelCase_						=  tokenizer.get_vocab()
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)

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

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




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			Optional[int]:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)
     UpperCamelCase_						=  tokenizer.get_vocab()
     # String duplicates + id duplicates
     UpperCamelCase_						=  sorted(vocab.keys()			)[:3]
     UpperCamelCase_						=  [targets[0], targets[1], targets[0], targets[2], targets[1]]
     UpperCamelCase_						=  fill_masker(f"""My name is {tokenizer.mask_token}"""		,		targets=_UpperCAmelCase		,		top_k=10			)

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




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase			)      ->			List[str]:
     UpperCamelCase_						=  FillMaskPipeline(model=_UpperCAmelCase		,		tokenizer=_UpperCAmelCase			)

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





