






from typing import Optional, Union

import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig


A__	:			Union[str, Any]			   = logging.get_logger(__name__)


# General docstring
A__	:			Optional[int]			   = 'MobileNetV1Config'

# Base docstring
A__	:			Any			   = 'google/mobilenet_v1_1.0_224'
A__	:			List[str]			   = [1, 10_24, 7, 7]

# Image classification docstring
A__	:			List[str]			   = 'google/mobilenet_v1_1.0_224'
A__	:			List[str]			   = 'tabby, tabby cat'


A__	:			Tuple			   = [
    'google/mobilenet_v1_1.0_224',
    'google/mobilenet_v1_0.75_192',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]






def   a			(						lowerCamelCase_		,   lowerCamelCase_		,   lowerCamelCase_=None				):






				'''simple docstring'''
				lowercase__    =			{}

				if isinstance(lowerCamelCase_		,   lowerCamelCase_				):
								lowercase__    =			model.mobilenet_va
				else:
								lowercase__    =			model

				lowercase__    =			'''MobilenetV1/Conv2d_0/'''
				lowercase__    =			backbone.conv_stem.convolution.weight
				lowercase__    =			backbone.conv_stem.normalization.bias
				lowercase__    =			backbone.conv_stem.normalization.weight
				lowercase__    =			backbone.conv_stem.normalization.running_mean
				lowercase__    =			backbone.conv_stem.normalization.running_var

				for i in range(13				):
								lowercase__    =			i + 1
								lowercase__    =			i * 2

								lowercase__    =			backbone.layer[pt_index]
								lowercase__    =			F"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
								lowercase__    =			pointer.convolution.weight
								lowercase__    =			pointer.normalization.bias
								lowercase__    =			pointer.normalization.weight
								lowercase__    =			pointer.normalization.running_mean
								lowercase__    =			pointer.normalization.running_var

								lowercase__    =			backbone.layer[pt_index + 1]
								lowercase__    =			F"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
								lowercase__    =			pointer.convolution.weight
								lowercase__    =			pointer.normalization.bias
								lowercase__    =			pointer.normalization.weight
								lowercase__    =			pointer.normalization.running_mean
								lowercase__    =			pointer.normalization.running_var

				if isinstance(lowerCamelCase_		,   lowerCamelCase_				):
								lowercase__    =			'''MobilenetV1/Logits/Conv2d_1c_1x1/'''
								lowercase__    =			model.classifier.weight
								lowercase__    =			model.classifier.bias

				return tf_to_pt_map






def   a			(						lowerCamelCase_		,   lowerCamelCase_		,   lowerCamelCase_				):






				'''simple docstring'''
				try:
								import numpy as np
								import tensorflow as tf
				except ImportError:
								logger.error(
								    '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
								    '''https://www.tensorflow.org/install/ for installation instructions.'''				)
								raise

				# Load weights from TF model
				lowercase__    =			tf.train.list_variables(lowerCamelCase_				)
				lowercase__    =			{}
				for name, shape in init_vars:
								logger.info(F"""Loading TF weight {name} with shape {shape}"""				)
								lowercase__    =			tf.train.load_variable(lowerCamelCase_		,   lowerCamelCase_				)
								lowercase__    =			array

				# Build TF to PyTorch weights loading map
				lowercase__    =			_build_tf_to_pytorch_map(lowerCamelCase_		,   lowerCamelCase_		,   lowerCamelCase_				)

				for name, pointer in tf_to_pt_map.items():
								logger.info(F"""Importing {name}"""				)
								if name not in tf_weights:
												logger.info(F"""{name} not in tf pre-trained weights, skipping"""				)
												continue

								lowercase__    =			tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('''Transposing depthwise'''				)
												lowercase__    =			np.transpose(lowerCamelCase_		,   (2, 3, 0, 1)				)
								elif "weights" in name:
												logger.info('''Transposing'''				)
												if len(pointer.shape				) == 2:  # copying into linear layer
																lowercase__    =			array.squeeze().transpose()
												else:
																lowercase__    =			np.transpose(lowerCamelCase_		,   (3, 2, 0, 1)				)

								if pointer.shape != array.shape:
												raise ValueError(F"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched"""				)

								logger.info(F"""Initialize PyTorch weight {name} {array.shape}"""				)
								lowercase__    =			torch.from_numpy(lowerCamelCase_				)

								tf_weights.pop(lowerCamelCase_		,   lowerCamelCase_				)
								tf_weights.pop(name + '''/RMSProp'''		,   lowerCamelCase_				)
								tf_weights.pop(name + '''/RMSProp_1'''		,   lowerCamelCase_				)
								tf_weights.pop(name + '''/ExponentialMovingAverage'''		,   lowerCamelCase_				)

				logger.info(F"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys()				)}"""				)
				return model






def   a			(						lowerCamelCase_		,   lowerCamelCase_				):






				'''simple docstring'''
				lowercase__ ,						lowercase__    =			features.shape[-2:]
				lowercase__ ,						lowercase__    =			conv_layer.stride
				lowercase__ ,						lowercase__    =			conv_layer.kernel_size

				if in_height % stride_height == 0:
								lowercase__    =			max(kernel_height - stride_height		,   0				)
				else:
								lowercase__    =			max(kernel_height - (in_height % stride_height)		,   0				)

				if in_width % stride_width == 0:
								lowercase__    =			max(kernel_width - stride_width		,   0				)
				else:
								lowercase__    =			max(kernel_width - (in_width % stride_width)		,   0				)

				lowercase__    =			pad_along_width // 2
				lowercase__    =			pad_along_width - pad_left
				lowercase__    =			pad_along_height // 2
				lowercase__    =			pad_along_height - pad_top

				lowercase__    =			(pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowerCamelCase_		,   lowerCamelCase_		,   '''constant'''		,   0.0				)
class       _UpperCAmelCase					(       nn.Module	):

				"""simple docstring"""




				def __init__(     self						:    List[str],  lowerCamelCase						:    MobileNetVaConfig,  lowerCamelCase						:    int,  lowerCamelCase						:    int,  lowerCamelCase						:    int,  lowerCamelCase						:    Optional[int] = 1,  lowerCamelCase						:    Optional[int] = 1,  lowerCamelCase						:    bool = False,  lowerCamelCase						:    Optional[bool] = True,  lowerCamelCase						:    Optional[bool or str] = True,  ):

								'''simple docstring'''
								super().__init__()
								lowercase__    =			config

								if in_channels % groups != 0:
												raise ValueError(F"""Input channels ({in_channels}) are not divisible by {groups} groups."""  )
								if out_channels % groups != 0:
												raise ValueError(F"""Output channels ({out_channels}) are not divisible by {groups} groups."""  )

								lowercase__    =			0 if config.tf_padding else int((kernel_size - 1) / 2  )

								lowercase__    =			nn.Convad(
								    in_channels=lowerCamelCase,  out_channels=lowerCamelCase,  kernel_size=lowerCamelCase,  stride=lowerCamelCase,  padding=lowerCamelCase,  groups=lowerCamelCase,  bias=lowerCamelCase,  padding_mode='''zeros''',  )

								if use_normalization:
												lowercase__    =			nn.BatchNormad(
												    num_features=lowerCamelCase,  eps=config.layer_norm_eps,  momentum=0.9997,  affine=lowerCamelCase,  track_running_stats=lowerCamelCase,  )
								else:
												lowercase__    =			None

								if use_activation:
												if isinstance(lowerCamelCase,  lowerCamelCase  ):
																lowercase__    =			ACTaFN[use_activation]
												elif isinstance(config.hidden_act,  lowerCamelCase  ):
																lowercase__    =			ACTaFN[config.hidden_act]
												else:
																lowercase__    =			config.hidden_act
								else:
												lowercase__    =			None




				def 				lowercase__   (     self						:    str,  lowerCamelCase						:    torch.Tensor  ):

								'''simple docstring'''
								if self.config.tf_padding:
												lowercase__    =			apply_tf_padding(lowerCamelCase,  self.convolution  )
								lowercase__    =			self.convolution(lowerCamelCase  )
								if self.normalization is not None:
												lowercase__    =			self.normalization(lowerCamelCase  )
								if self.activation is not None:
												lowercase__    =			self.activation(lowerCamelCase  )
								return features



class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				lowercase__											=       MobileNetVaConfig
				lowercase__											=       load_tf_weights_in_mobilenet_va
				lowercase__											=       """mobilenet_v1"""
				lowercase__											=       """pixel_values"""
				lowercase__											=       False




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    Union[nn.Linear, nn.Convad]  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  (nn.Linear, nn.Convad)  ):
												module.weight.data.normal_(mean=0.0,  std=self.config.initializer_range  )
												if module.bias is not None:
																module.bias.data.zero_()
								elif isinstance(lowerCamelCase,  nn.BatchNormad  ):
												module.bias.data.zero_()
												module.weight.data.fill_(1.0  )



A__	:			Optional[Any]			   = r'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

A__	:			Optional[Any]			   = r'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`MobileNetV1ImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'
@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."""		,A__		,)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def __init__(     self						:    List[Any],  lowerCamelCase						:    MobileNetVaConfig,  lowerCamelCase						:    bool = True  ):

								'''simple docstring'''
								super().__init__(lowerCamelCase  )
								lowercase__    =			config

								lowercase__    =			32
								lowercase__    =			max(int(depth * config.depth_multiplier  ),  config.min_depth  )

								lowercase__    =			MobileNetVaConvLayer(
								    lowerCamelCase,  in_channels=config.num_channels,  out_channels=lowerCamelCase,  kernel_size=3,  stride=2,  )

								lowercase__    =			[1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

								lowercase__    =			nn.ModuleList()
								for i in range(13  ):
												lowercase__    =			out_channels

												if strides[i] == 2 or i == 0:
																depth *= 2
																lowercase__    =			max(int(depth * config.depth_multiplier  ),  config.min_depth  )

												self.layer.append(
												    MobileNetVaConvLayer(
												        lowerCamelCase,  in_channels=lowerCamelCase,  out_channels=lowerCamelCase,  kernel_size=3,  stride=strides[i],  groups=lowerCamelCase,  )  )

												self.layer.append(
												    MobileNetVaConvLayer(
												        lowerCamelCase,  in_channels=lowerCamelCase,  out_channels=lowerCamelCase,  kernel_size=1,  )  )

								lowercase__    =			nn.AdaptiveAvgPoolad((1, 1)  ) if add_pooling_layer else None

								# Initialize weights and apply final processing
								self.post_init()




				def 				lowercase__   (     self						:    Dict,  lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								raise NotImplementedError




				@add_start_docstrings_to_model_forward(lowerCamelCase  )
				@add_code_sample_docstrings(
				    checkpoint=_CHECKPOINT_FOR_DOC,  output_type=lowerCamelCase,  config_class=_CONFIG_FOR_DOC,  modality='''vision''',  expected_output=_EXPECTED_OUTPUT_SHAPE,  )
				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Optional[torch.Tensor] = None,  lowerCamelCase						:    Optional[bool] = None,  lowerCamelCase						:    Optional[bool] = None,  ):

								'''simple docstring'''
								lowercase__    =			(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								lowercase__    =			return_dict if return_dict is not None else self.config.use_return_dict

								if pixel_values is None:
												raise ValueError('''You have to specify pixel_values'''  )

								lowercase__    =			self.conv_stem(lowerCamelCase  )

								lowercase__    =			() if output_hidden_states else None

								for i, layer_module in enumerate(self.layer  ):
												lowercase__    =			layer_module(lowerCamelCase  )

												if output_hidden_states:
																lowercase__    =			all_hidden_states + (hidden_states,)

								lowercase__    =			hidden_states

								if self.pooler is not None:
												lowercase__    =			torch.flatten(self.pooler(lowerCamelCase  ),  start_dim=1  )
								else:
												lowercase__    =			None

								if not return_dict:
												return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None  )

								return BaseModelOutputWithPoolingAndNoAttention(
								    last_hidden_state=lowerCamelCase,  pooler_output=lowerCamelCase,  hidden_states=lowerCamelCase,  )



@add_start_docstrings(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """		,A__		,)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def __init__(     self						:    Tuple,  lowerCamelCase						:    MobileNetVaConfig  ):

								'''simple docstring'''
								super().__init__(lowerCamelCase  )

								lowercase__    =			config.num_labels
								lowercase__    =			MobileNetVaModel(lowerCamelCase  )

								lowercase__    =			self.mobilenet_va.layer[-1].convolution.out_channels

								# Classifier head
								lowercase__    =			nn.Dropout(config.classifier_dropout_prob,  inplace=lowerCamelCase  )
								lowercase__    =			nn.Linear(lowerCamelCase,  config.num_labels  ) if config.num_labels > 0 else nn.Identity()

								# Initialize weights and apply final processing
								self.post_init()




				@add_start_docstrings_to_model_forward(lowerCamelCase  )
				@add_code_sample_docstrings(
				    checkpoint=_IMAGE_CLASS_CHECKPOINT,  output_type=lowerCamelCase,  config_class=_CONFIG_FOR_DOC,  expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,  )
				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[torch.Tensor] = None,  lowerCamelCase						:    Optional[bool] = None,  lowerCamelCase						:    Optional[torch.Tensor] = None,  lowerCamelCase						:    Optional[bool] = None,  ):

								'''simple docstring'''
								lowercase__    =			return_dict if return_dict is not None else self.config.use_return_dict

								lowercase__    =			self.mobilenet_va(lowerCamelCase,  output_hidden_states=lowerCamelCase,  return_dict=lowerCamelCase  )

								lowercase__    =			outputs.pooler_output if return_dict else outputs[1]

								lowercase__    =			self.classifier(self.dropout(lowerCamelCase  )  )

								lowercase__    =			None
								if labels is not None:
												if self.config.problem_type is None:
																if self.num_labels == 1:
																				lowercase__    =			'''regression'''
																elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																				lowercase__    =			'''single_label_classification'''
																else:
																				lowercase__    =			'''multi_label_classification'''

												if self.config.problem_type == "regression":
																lowercase__    =			MSELoss()
																if self.num_labels == 1:
																				lowercase__    =			loss_fct(logits.squeeze(),  labels.squeeze()  )
																else:
																				lowercase__    =			loss_fct(lowerCamelCase,  lowerCamelCase  )
												elif self.config.problem_type == "single_label_classification":
																lowercase__    =			CrossEntropyLoss()
																lowercase__    =			loss_fct(logits.view(-1,  self.num_labels  ),  labels.view(-1  )  )
												elif self.config.problem_type == "multi_label_classification":
																lowercase__    =			BCEWithLogitsLoss()
																lowercase__    =			loss_fct(lowerCamelCase,  lowerCamelCase  )

								if not return_dict:
												lowercase__    =			(logits,) + outputs[2:]
												return ((loss,) + output) if loss is not None else output

								return ImageClassifierOutputWithNoAttention(
								    loss=lowerCamelCase,  logits=lowerCamelCase,  hidden_states=outputs.hidden_states,  )












from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


A__	:			Dict			   = logging.get_logger(__name__)
@add_end_docstrings(
    A__		,r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """		,)
class       _UpperCAmelCase					(       A__	):

				"""simple docstring"""




				def 				lowercase__   (     self						:    Optional[int],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()
								elif self.framework == "pt":
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  )
								else:
												raise ValueError('''Unsupported framework'''  )
								return masked_index




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								lowercase__    =			self.get_masked_index(lowerCamelCase  )
								lowercase__    =			np.prod(masked_index.shape  )
								if numel < 1:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  F"""No mask_token ({self.tokenizer.mask_token}) found on the input""",  )




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    GenericTensor  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												for model_input in model_inputs:
																self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]  )
								else:
												for input_ids in model_inputs["input_ids"]:
																self._ensure_exactly_one_mask_token(lowerCamelCase  )




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    Union[str, Any],  lowerCamelCase						:    Optional[int]=None,  **lowerCamelCase						:    Dict  ):

								'''simple docstring'''
								if return_tensors is None:
												lowercase__    =			self.framework
								lowercase__    =			self.tokenizer(lowerCamelCase,  return_tensors=lowerCamelCase  )
								self.ensure_exactly_one_mask_token(lowerCamelCase  )
								return model_inputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    int  ):

								'''simple docstring'''
								lowercase__    =			self.model(**lowerCamelCase  )
								lowercase__    =			model_inputs['''input_ids''']
								return model_outputs




				def 				lowercase__   (     self						:    Optional[Any],  lowerCamelCase						:    List[str],  lowerCamelCase						:    Tuple=5,  lowerCamelCase						:    List[Any]=None  ):

								'''simple docstring'''
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
												lowercase__    =			target_ids.shape[0]
								lowercase__    =			model_outputs['''input_ids'''][0]
								lowercase__    =			model_outputs['''logits''']

								if self.framework == "tf":
												lowercase__    =			tf.where(input_ids == self.tokenizer.mask_token_id  ).numpy()[:, 0]

												lowercase__    =			outputs.numpy()

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			stable_softmax(lowerCamelCase,  axis=-1  )
												if target_ids is not None:
																lowercase__    =			tf.gather_nd(tf.squeeze(lowerCamelCase,  0  ),  target_ids.reshape(-1,  1  )  )
																lowercase__    =			tf.expand_dims(lowerCamelCase,  0  )

												lowercase__    =			tf.math.top_k(lowerCamelCase,  k=lowerCamelCase  )
												lowercase__ ,						lowercase__    =			topk.values.numpy(), topk.indices.numpy()
								else:
												lowercase__    =			torch.nonzero(input_ids == self.tokenizer.mask_token_id,  as_tuple=lowerCamelCase  ).squeeze(-1  )
												# Fill mask pipeline supports only one ${mask_token} per sample

												lowercase__    =			outputs[0, masked_index, :]
												lowercase__    =			logits.softmax(dim=-1  )
												if target_ids is not None:
																lowercase__    =			probs[..., target_ids]

												lowercase__ ,						lowercase__    =			probs.topk(lowerCamelCase  )

								lowercase__    =			[]
								lowercase__    =			values.shape[0] == 1
								for i, (_values, _predictions) in enumerate(zip(values.tolist(),  predictions.tolist()  )  ):
												lowercase__    =			[]
												for v, p in zip(_values,  _predictions  ):
																# Copy is important since we're going to modify this array in place
																lowercase__    =			input_ids.numpy().copy()
																if target_ids is not None:
																				lowercase__    =			target_ids[p].tolist()

																lowercase__    =			p
																# Filter padding out:
																lowercase__    =			tokens[np.where(tokens != self.tokenizer.pad_token_id  )]
																# Originally we skip special tokens to give readable output.
																# For multi masks though, the other [MASK] would be removed otherwise
																# making the output look odd, so we add them back
																lowercase__    =			self.tokenizer.decode(lowerCamelCase,  skip_special_tokens=lowerCamelCase  )
																lowercase__    =			{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]  ), '''sequence''': sequence}
																row.append(lowerCamelCase  )
												result.append(lowerCamelCase  )
								if single_mask:
												return result[0]
								return result




				def 				lowercase__   (     self						:    int,  lowerCamelCase						:    Optional[int],  lowerCamelCase						:    Dict=None  ):

								'''simple docstring'''
								if isinstance(lowerCamelCase,  lowerCamelCase  ):
												lowercase__    =			[targets]
								try:
												lowercase__    =			self.tokenizer.get_vocab()
								except Exception:
												lowercase__    =			{}
								lowercase__    =			[]
								for target in targets:
												lowercase__    =			vocab.get(lowerCamelCase,  lowerCamelCase  )
												if id_ is None:
																lowercase__    =			self.tokenizer(
																    lowerCamelCase,  add_special_tokens=lowerCamelCase,  return_attention_mask=lowerCamelCase,  return_token_type_ids=lowerCamelCase,  max_length=1,  truncation=lowerCamelCase,  )['''input_ids''']
																if len(lowerCamelCase  ) == 0:
																				logger.warning(
																				    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																				    '''We cannot replace it with anything meaningful, ignoring it'''  )
																				continue
																lowercase__    =			input_ids[0]
																# XXX: If users encounter this pass
																# it becomes pretty slow, so let's make sure
																# The warning enables them to fix the input to
																# get faster performance.
																logger.warning(
																    F"""The specified target token `{target}` does not exist in the model vocabulary. """
																    F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_  )}`."""  )
												target_ids.append(id_  )
								lowercase__    =			list(set(lowerCamelCase  )  )
								if len(lowerCamelCase  ) == 0:
												raise ValueError('''At least one target must be provided when passed.'''  )
								lowercase__    =			np.array(lowerCamelCase  )
								return target_ids




				def 				lowercase__   (     self						:    List[str],  lowerCamelCase						:    int=None,  lowerCamelCase						:    Any=None  ):

								'''simple docstring'''
								lowercase__    =			{}

								if targets is not None:
												lowercase__    =			self.get_target_ids(lowerCamelCase,  lowerCamelCase  )
												lowercase__    =			target_ids

								if top_k is not None:
												lowercase__    =			top_k

								if self.tokenizer.mask_token_id is None:
												raise PipelineException(
												    '''fill-mask''',  self.model.base_model_prefix,  '''The tokenizer does not define a `mask_token`.'''  )
								return {}, {}, postprocess_params




				def __call__(     self						:    List[Any],  lowerCamelCase						:    Optional[Any],  *lowerCamelCase						:    Optional[Any],  **lowerCamelCase						:    Optional[Any]  ):

								'''simple docstring'''
								lowercase__    =			super().__call__(lowerCamelCase,  **lowerCamelCase  )
								if isinstance(lowerCamelCase,  lowerCamelCase  ) and len(lowerCamelCase  ) == 1:
												return outputs[0]
								return outputs




