
from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowercase  :					Any						    =							logging.get_logger(__name__)

# General docstring
lowercase  :					Tuple						    =							"""RegNetConfig"""

# Base docstring
lowercase  :					int						    =							"""facebook/regnet-y-040"""
lowercase  :					str						    =							[1, 1088, 7, 7]

# Image classification docstring
lowercase  :					Tuple						    =							"""facebook/regnet-y-040"""
lowercase  :					Optional[int]						    =							"""tabby, tabby cat"""

lowercase  :					str						    =							[
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]

class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case = 3		,snake_case = 1		,snake_case = 1		,snake_case = "relu"		,**snake_case		,):



           '''simple docstring'''







           super().__init__(**snake_case      )
           # The padding and conv has been verified in
           # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
           lowercase							:     Optional[Any]       	=      tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2      )
           lowercase							:     Any       	=      tf.keras.layers.ConvaD(
               filters=snake_case		,kernel_size=snake_case		,strides=snake_case		,padding="""VALID"""		,groups=snake_case		,use_bias=snake_case		,name="""convolution"""		,)
           lowercase							:     List[str]       	=      tf.keras.layers.BatchNormalization(epsilon=1e-5		,momentum=0.9		,name="""normalization"""      )
           lowercase							:     Dict       	=      ACTaFN[activation] if activation is not None else tf.identity
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.convolution(self.padding(snake_case      )      )
           lowercase							:     Any       	=      self.normalization(snake_case      )
           lowercase							:     int       	=      self.activation(snake_case      )
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     Dict       	=      config.num_channels
           lowercase							:     Any       	=      TFRegNetConvLayer(
               out_channels=config.embedding_size		,kernel_size=3		,stride=2		,activation=config.hidden_act		,name="""embedder"""		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     List[Any]       	=      shape_list(snake_case      )[1]
           if tf.executing_eagerly() and num_channels != self.num_channels:
                  raise ValueError(
                      """Make sure that the channel dimension of the pixel values match with the one set in the configuration."""      )

           # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
           # So change the input format from `NCHW` to `NHWC`.
           # shape = (batch_size, in_height, in_width, in_channels=num_channels)
           lowercase							:     str       	=      tf.transpose(snake_case		,perm=(0, 2, 3, 1)      )
           lowercase							:     Dict       	=      self.embedder(snake_case      )
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case = 2		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     Dict       	=      tf.keras.layers.ConvaD(
               filters=snake_case		,kernel_size=1		,strides=snake_case		,use_bias=snake_case		,name="""convolution"""      )
           lowercase							:     List[str]       	=      tf.keras.layers.BatchNormalization(epsilon=1e-5		,momentum=0.9		,name="""normalization"""      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = False      ):



           '''simple docstring'''







           return self.normalization(self.convolution(snake_case      )		,training=snake_case      )






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     Optional[Any]       	=      tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case		,name="""pooler"""      )
           lowercase							:     Dict       	=      [
               tf.keras.layers.ConvaD(filters=snake_case		,kernel_size=1		,activation="""relu"""		,name="""attention.0"""      ),
               tf.keras.layers.ConvaD(filters=snake_case		,kernel_size=1		,activation="""sigmoid"""		,name="""attention.2"""      ),
           ]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     int       	=      self.pooler(snake_case      )
           for layer_module in self.attention:
                  lowercase							:     List[Any]       	=      layer_module(snake_case      )
           lowercase							:     Union[str, Any]       	=      hidden_state * pooled
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case		,snake_case		,snake_case = 1		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     List[Any]       	=      in_channels != out_channels or stride != 1
           lowercase							:     Tuple       	=      max(1		,out_channels // config.groups_width      )
           lowercase							:     str       	=      (
               TFRegNetShortCut(snake_case		,stride=snake_case		,name="""shortcut"""      )
               if should_apply_shortcut
               else tf.keras.layers.Activation("""linear"""		,name="""shortcut"""      )
           )
           # `self.layers` instead of `self.layer` because that is a reserved argument.
           lowercase							:     List[Any]       	=      [
               TFRegNetConvLayer(snake_case		,kernel_size=1		,activation=config.hidden_act		,name="""layer.0"""      ),
               TFRegNetConvLayer(
                   snake_case		,stride=snake_case		,groups=snake_case		,activation=config.hidden_act		,name="""layer.1"""      ),
               TFRegNetConvLayer(snake_case		,kernel_size=1		,activation=snake_case		,name="""layer.2"""      ),
           ]
           lowercase							:     Any       	=      ACTaFN[config.hidden_act]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      hidden_state
           for layer_module in self.layers:
                  lowercase							:     Optional[int]       	=      layer_module(snake_case      )
           lowercase							:     Optional[Any]       	=      self.shortcut(snake_case      )
           hidden_state += residual
           lowercase							:     Dict       	=      self.activation(snake_case      )
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case		,snake_case		,snake_case = 1		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     Optional[Any]       	=      in_channels != out_channels or stride != 1
           lowercase							:     List[Any]       	=      max(1		,out_channels // config.groups_width      )
           lowercase							:     Optional[Any]       	=      (
               TFRegNetShortCut(snake_case		,stride=snake_case		,name="""shortcut"""      )
               if should_apply_shortcut
               else tf.keras.layers.Activation("""linear"""		,name="""shortcut"""      )
           )
           lowercase							:     Optional[int]       	=      [
               TFRegNetConvLayer(snake_case		,kernel_size=1		,activation=config.hidden_act		,name="""layer.0"""      ),
               TFRegNetConvLayer(
                   snake_case		,stride=snake_case		,groups=snake_case		,activation=config.hidden_act		,name="""layer.1"""      ),
               TFRegNetSELayer(snake_case		,reduced_channels=int(round(in_channels / 4      )      )		,name="""layer.2"""      ),
               TFRegNetConvLayer(snake_case		,kernel_size=1		,activation=snake_case		,name="""layer.3"""      ),
           ]
           lowercase							:     List[Any]       	=      ACTaFN[config.hidden_act]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     List[str]       	=      hidden_state
           for layer_module in self.layers:
                  lowercase							:     Tuple       	=      layer_module(snake_case      )
           lowercase							:     Union[str, Any]       	=      self.shortcut(snake_case      )
           hidden_state += residual
           lowercase							:     Optional[int]       	=      self.activation(snake_case      )
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,snake_case		,snake_case		,snake_case = 2		,snake_case = 2		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )

           lowercase							:     List[str]       	=      TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
           lowercase							:     List[Any]       	=      [
               # downsampling is done in the first layer with stride of 2
               layer(snake_case		,snake_case		,snake_case		,stride=snake_case		,name="""layers.0"""      ),
               *[layer(snake_case		,snake_case		,snake_case		,name=f"layers.{i+1}"      ) for i in range(depth - 1      )],
           ]
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           for layer_module in self.layers:
                  lowercase							:     Dict       	=      layer_module(snake_case      )
           return hidden_state






class __snake_case		(      tf.keras.layers.Layer     ):
    def __init__(  self		,snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     int       	=      []
           # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
           self.stages.append(
               TFRegNetStage(
                   snake_case		,config.embedding_size		,config.hidden_sizes[0]		,stride=2 if config.downsample_in_first_stage else 1		,depth=config.depths[0]		,name="""stages.0"""		,)      )
           lowercase							:     str       	=      zip(config.hidden_sizes		,config.hidden_sizes[1:]      )
           for i, ((in_channels, out_channels), depth) in enumerate(zip(snake_case		,config.depths[1:]      )      ):
                  self.stages.append(TFRegNetStage(snake_case		,snake_case		,snake_case		,depth=snake_case		,name=f"stages.{i+1}"      )      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = False		,snake_case = True      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      () if output_hidden_states else None

           for stage_module in self.stages:
                  if output_hidden_states:
                         lowercase							:     str       	=      hidden_states + (hidden_state,)

                  lowercase							:     Union[str, Any]       	=      stage_module(snake_case      )

           if output_hidden_states:
                  lowercase							:     int       	=      hidden_states + (hidden_state,)

           if not return_dict:
                  return tuple(v for v in [hidden_state, hidden_states] if v is not None      )

           return TFBaseModelOutputWithNoAttention(last_hidden_state=snake_case		,hidden_states=snake_case      )






@keras_serializable
class __snake_case		(      tf.keras.layers.Layer     ):
    _a		:						List[Any]=				RegNetConfig
    def __init__(  self		,snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(**snake_case      )
           lowercase							:     List[str]       	=      config
           lowercase							:     Optional[int]       	=      TFRegNetEmbeddings(snake_case		,name="""embedder"""      )
           lowercase							:     List[Any]       	=      TFRegNetEncoder(snake_case		,name="""encoder"""      )
           lowercase							:     Union[str, Any]       	=      tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case		,name="""pooler"""      )
    @unpack_inputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = None		,snake_case = None		,snake_case = False		,):



           '''simple docstring'''







           lowercase							:     Tuple       	=      (
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           lowercase							:     List[str]       	=      return_dict if return_dict is not None else self.config.use_return_dict

           lowercase							:     List[Any]       	=      self.embedder(snake_case		,training=snake_case      )

           lowercase							:     Optional[Any]       	=      self.encoder(
               snake_case		,output_hidden_states=snake_case		,return_dict=snake_case		,training=snake_case      )

           lowercase							:     Optional[Any]       	=      encoder_outputs[0]
           lowercase							:     Optional[int]       	=      self.pooler(snake_case      )

           # Change to NCHW output format have uniformity in the modules
           lowercase							:     Union[str, Any]       	=      tf.transpose(snake_case		,perm=(0, 3, 1, 2)      )
           lowercase							:     Dict       	=      tf.transpose(snake_case		,perm=(0, 3, 1, 2)      )

           # Change the other hidden state outputs to NCHW as well
           if output_hidden_states:
                  lowercase							:     Any       	=      tuple([tf.transpose(snake_case		,perm=(0, 3, 1, 2)      ) for h in encoder_outputs[1]]      )

           if not return_dict:
                  return (last_hidden_state, pooled_output) + encoder_outputs[1:]

           return TFBaseModelOutputWithPoolingAndNoAttention(
               last_hidden_state=snake_case		,pooler_output=snake_case		,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states		,)






class __snake_case		(      lowerCAmelCase     ):
    _a		:						Union[str, Any]=				RegNetConfig
    _a		:						Optional[int]=				"regnet"
    _a		:						str=				"pixel_values"
    @property
    def       _SCREAMING_SNAKE_CASE       (  self      ):



           '''simple docstring'''







           return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224)		,dtype=tf.floataa      )}






lowercase  :					Union[str, Any]						    =							R"""
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowercase  :					Tuple						    =							R"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""

@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top."					,	lowerCAmelCase					,	)
class __snake_case		(      lowerCAmelCase     ):
    def __init__(  self		,snake_case		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(snake_case		,*snake_case		,**snake_case      )
           lowercase							:     Dict       	=      TFRegNetMainLayer(snake_case		,name="""regnet"""      )
    @unpack_inputs
    @add_start_docstrings_to_model_forward(snake_case      )
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC		,output_type=snake_case		,config_class=_CONFIG_FOR_DOC		,modality="""vision"""		,expected_output=_EXPECTED_OUTPUT_SHAPE		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case = None		,snake_case = None		,snake_case=False		,):



           '''simple docstring'''







           lowercase							:     int       	=      (
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           lowercase							:     Union[str, Any]       	=      return_dict if return_dict is not None else self.config.use_return_dict

           lowercase							:     Optional[int]       	=      self.regnet(
               pixel_values=snake_case		,output_hidden_states=snake_case		,return_dict=snake_case		,training=snake_case		,)
           if not return_dict:
                  return (outputs[0],) + outputs[1:]

           return TFBaseModelOutputWithPoolingAndNoAttention(
               last_hidden_state=outputs.last_hidden_state		,pooler_output=outputs.pooler_output		,hidden_states=outputs.hidden_states		,)






@add_start_docstrings(
    "\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "					,	lowerCAmelCase					,	)
class __snake_case		(      lowerCAmelCase					,	lowerCAmelCase     ):
    def __init__(  self		,snake_case		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           super().__init__(snake_case		,*snake_case		,**snake_case      )
           lowercase							:     Optional[int]       	=      config.num_labels
           lowercase							:     Optional[Any]       	=      TFRegNetMainLayer(snake_case		,name="""regnet"""      )
           # classification head
           lowercase							:     Union[str, Any]       	=      [
               tf.keras.layers.Flatten(),
               tf.keras.layers.Dense(config.num_labels		,name="""classifier.1"""      ) if config.num_labels > 0 else tf.identity,
           ]
    @unpack_inputs
    @add_start_docstrings_to_model_forward(snake_case      )
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT		,output_type=snake_case		,config_class=_CONFIG_FOR_DOC		,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT		,)
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case = None		,snake_case = None		,snake_case = None		,snake_case = None		,snake_case=False		,):



           '''simple docstring'''







           lowercase							:     Any       	=      (
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )
           lowercase							:     Union[str, Any]       	=      return_dict if return_dict is not None else self.config.use_return_dict

           lowercase							:     Optional[int]       	=      self.regnet(
               snake_case		,output_hidden_states=snake_case		,return_dict=snake_case		,training=snake_case      )

           lowercase							:     Any       	=      outputs.pooler_output if return_dict else outputs[1]

           lowercase							:     Dict       	=      self.classifier[0](snake_case      )
           lowercase							:     Optional[int]       	=      self.classifier[1](snake_case      )

           lowercase							:     Dict       	=      None if labels is None else self.hf_compute_loss(labels=snake_case		,logits=snake_case      )

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

           return TFSequenceClassifierOutput(loss=snake_case		,logits=snake_case		,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


lowercase  :					List[str]						    =							logging.get_logger(__name__)

@add_end_docstrings(
    lowerCAmelCase					,	R"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    "					,	)
class __snake_case		(      lowerCAmelCase     ):
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if self.framework == "tf":
                  lowercase							:     str       	=      tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
           elif self.framework == "pt":
                  lowercase							:     Optional[int]       	=      torch.nonzero(input_ids == self.tokenizer.mask_token_id		,as_tuple=snake_case      )
           else:
                  raise ValueError("""Unsupported framework"""      )
           return masked_index
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      self.get_masked_index(snake_case      )
           lowercase							:     Dict       	=      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       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           if isinstance(snake_case		,snake_case      ):
                  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(snake_case      )
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None		,**snake_case      ):



           '''simple docstring'''







           if return_tensors is None:
                  lowercase							:     int       	=      self.framework
           lowercase							:     Optional[Any]       	=      self.tokenizer(snake_case		,return_tensors=snake_case      )
           self.ensure_exactly_one_mask_token(snake_case      )
           return model_inputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case      ):



           '''simple docstring'''







           lowercase							:     Optional[int]       	=      self.model(**snake_case      )
           lowercase							:     Tuple       	=      model_inputs["""input_ids"""]
           return model_outputs
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=5		,snake_case=None      ):



           '''simple docstring'''







           if target_ids is not None and target_ids.shape[0] < top_k:
                  lowercase							:     str       	=      target_ids.shape[0]
           lowercase							:     Optional[Any]       	=      model_outputs["""input_ids"""][0]
           lowercase							:     List[str]       	=      model_outputs["""logits"""]

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

                  lowercase							:     Tuple       	=      outputs.numpy()

                  lowercase							:     Tuple       	=      outputs[0, masked_index, :]
                  lowercase							:     Any       	=      stable_softmax(snake_case		,axis=-1      )
                  if target_ids is not None:
                         lowercase							:     Union[str, Any]       	=      tf.gather_nd(tf.squeeze(snake_case		,0      )		,target_ids.reshape(-1		,1      )      )
                         lowercase							:     int       	=      tf.expand_dims(snake_case		,0      )

                  lowercase							:     Tuple       	=      tf.math.top_k(snake_case		,k=snake_case      )
                  lowercase	,			lowercase							:     int       	=      topk.values.numpy(), topk.indices.numpy()
           else:
                  lowercase							:     Optional[Any]       	=      torch.nonzero(input_ids == self.tokenizer.mask_token_id		,as_tuple=snake_case      ).squeeze(-1      )
                  # Fill mask pipeline supports only one ${mask_token} per sample

                  lowercase							:     Union[str, Any]       	=      outputs[0, masked_index, :]
                  lowercase							:     Tuple       	=      logits.softmax(dim=-1      )
                  if target_ids is not None:
                         lowercase							:     List[str]       	=      probs[..., target_ids]

                  lowercase	,			lowercase							:     Union[str, Any]       	=      probs.topk(snake_case      )

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

                         lowercase							:     Tuple       	=      p
                         # Filter padding out:
                         lowercase							:     List[str]       	=      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							:     Tuple       	=      self.tokenizer.decode(snake_case		,skip_special_tokens=snake_case      )
                         lowercase							:     Optional[Any]       	=      {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]      ), """sequence""": sequence}
                         row.append(snake_case      )
                  result.append(snake_case      )
           if single_mask:
                  return result[0]
           return result
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case		,snake_case=None      ):



           '''simple docstring'''







           if isinstance(snake_case		,snake_case      ):
                  lowercase							:     List[Any]       	=      [targets]
           try:
                  lowercase							:     List[str]       	=      self.tokenizer.get_vocab()
           except Exception:
                  lowercase							:     Any       	=      {}
           lowercase							:     Dict       	=      []
           for target in targets:
                  lowercase							:     Dict       	=      vocab.get(snake_case		,snake_case      )
                  if id_ is None:
                         lowercase							:     Optional[int]       	=      self.tokenizer(
                             snake_case		,add_special_tokens=snake_case		,return_attention_mask=snake_case		,return_token_type_ids=snake_case		,max_length=1		,truncation=snake_case		,)["""input_ids"""]
                         if len(snake_case      ) == 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							:     Union[str, Any]       	=      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							:     Optional[Any]       	=      list(set(snake_case      )      )
           if len(snake_case      ) == 0:
                  raise ValueError("""At least one target must be provided when passed."""      )
           lowercase							:     Optional[Any]       	=      np.array(snake_case      )
           return target_ids
    def       _SCREAMING_SNAKE_CASE       (  self		,snake_case=None		,snake_case=None      ):



           '''simple docstring'''







           lowercase							:     Dict       	=      {}

           if targets is not None:
                  lowercase							:     str       	=      self.get_target_ids(snake_case		,snake_case      )
                  lowercase							:     List[Any]       	=      target_ids

           if top_k is not None:
                  lowercase							:     List[str]       	=      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		,snake_case		,*snake_case		,**snake_case      ):



           '''simple docstring'''







           lowercase							:     Tuple       	=      super().__call__(snake_case		,**snake_case      )
           if isinstance(snake_case		,snake_case      ) and len(snake_case      ) == 1:
                  return outputs[0]
           return outputs
