


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


__lowerCamelCase        =     logging.get_logger(__name__)


@add_end_docstrings(
    lowerCAmelCase_						,       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   a__	(						lowerCAmelCase_    ):

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     GenericTensor    ):
            if self.framework == "tf":
                 a_    :     Any										=    tf.where(input_ids == self.tokenizer.mask_token_id    ).numpy()
            elif self.framework == "pt":
                 a_    :     str										=    torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,							as_tuple=lowerCamelCase_    )
            else:
                 raise ValueError("""Unsupported framework"""    )
            return masked_index

       def 						UpperCAmelCase(   self      :     Any      ,							lowerCamelCase_      :     GenericTensor    ):
            a_    :     Optional[int]										=    self.get_masked_index(lowerCamelCase_    )
            a_    :     Any										=    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 						UpperCAmelCase(   self      :     Union[str, Any]      ,							lowerCamelCase_      :     GenericTensor    ):
            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 						UpperCAmelCase(   self      :     Optional[int]      ,							lowerCamelCase_      :     Dict      ,							lowerCamelCase_      :     Optional[Any]=None      ,							**lowerCamelCase_      :     List[str]    ):
            if return_tensors is None:
                 a_    :     List[str]										=    self.framework
            a_    :     str										=    self.tokenizer(lowerCamelCase_      ,							return_tensors=lowerCamelCase_    )
            self.ensure_exactly_one_mask_token(lowerCamelCase_    )
            return model_inputs

       def 						UpperCAmelCase(   self      :     Any      ,							lowerCamelCase_      :     Optional[Any]    ):
            a_    :     Any										=    self.model(**lowerCamelCase_    )
            a_    :     Dict										=    model_inputs["""input_ids"""]
            return model_outputs

       def 						UpperCAmelCase(   self      :     str      ,							lowerCamelCase_      :     str      ,							lowerCamelCase_      :     List[str]=5      ,							lowerCamelCase_      :     int=None    ):
            # Cap top_k if there are targets
            if target_ids is not None and target_ids.shape[0] < top_k:
                 a_    :     List[str]										=    target_ids.shape[0]
            a_    :     Any										=    model_outputs["""input_ids"""][0]
            a_    :     str										=    model_outputs["""logits"""]

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

                 a_    :     Dict										=    outputs.numpy()

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

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

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

                 a_			,			a_    :     int										=    probs.topk(lowerCamelCase_    )

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

                      a_    :     str										=    p
                      # Filter padding out:
                      a_    :     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
                      a_    :     Tuple										=    self.tokenizer.decode(lowerCamelCase_      ,							skip_special_tokens=lowerCamelCase_    )
                      a_    :     Optional[Any]										=    {"""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 						UpperCAmelCase(   self      :     List[str]      ,							lowerCamelCase_      :     int      ,							lowerCamelCase_      :     Dict=None    ):
            if isinstance(lowerCamelCase_      ,							lowerCamelCase_    ):
                 a_    :     List[str]										=    [targets]
            try:
                 a_    :     int										=    self.tokenizer.get_vocab()
            except Exception:
                 a_    :     str										=    {}
            a_    :     List[str]										=    []
            for target in targets:
                 a_    :     List[str]										=    vocab.get(lowerCamelCase_      ,							lowerCamelCase_    )
                 if id_ is None:
                      a_    :     Union[str, Any]										=    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
                      a_    :     str										=    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_    )
            a_    :     Union[str, Any]										=    list(set(lowerCamelCase_    )    )
            if len(lowerCamelCase_    ) == 0:
                 raise ValueError("""At least one target must be provided when passed."""    )
            a_    :     int										=    np.array(lowerCamelCase_    )
            return target_ids

       def 						UpperCAmelCase(   self      :     Optional[Any]      ,							lowerCamelCase_      :     str=None      ,							lowerCamelCase_      :     Optional[Any]=None    ):
            a_    :     Union[str, Any]										=    {}

            if targets is not None:
                 a_    :     Tuple										=    self.get_target_ids(lowerCamelCase_      ,							lowerCamelCase_    )
                 a_    :     Tuple										=    target_ids

            if top_k is not None:
                 a_    :     Optional[int]										=    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      :     Dict      ,							lowerCamelCase_      :     Tuple      ,							*lowerCamelCase_      :     List[str]      ,							**lowerCamelCase_      :     Optional[int]    ):
            a_    :     Tuple										=    super().__call__(lowerCamelCase_      ,							**lowerCamelCase_    )
            if isinstance(lowerCamelCase_      ,							lowerCamelCase_    ) and len(lowerCamelCase_    ) == 1:
                 return outputs[0]
            return outputs







from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


__lowerCamelCase        =     logging.get_logger(__name__)

__lowerCamelCase        =     {
    '''facebook/convnextv2-tiny-1k-224''': '''https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json''',
}


class   a__	(						lowerCAmelCase_						,       lowerCAmelCase_    ):
       lowerCamelCase__:     str							    =     """convnextv2"""

       def __init__(   self      :     Tuple      ,							lowerCamelCase_      :     str=3      ,							lowerCamelCase_      :     Tuple=4      ,							lowerCamelCase_      :     Any=4      ,							lowerCamelCase_      :     Optional[int]=None      ,							lowerCamelCase_      :     Optional[int]=None      ,							lowerCamelCase_      :     Optional[int]="gelu"      ,							lowerCamelCase_      :     Optional[Any]=0.0_2      ,							lowerCamelCase_      :     str=1E-12      ,							lowerCamelCase_      :     Dict=0.0      ,							lowerCamelCase_      :     Union[str, Any]=2_2_4      ,							lowerCamelCase_      :     Dict=None      ,							lowerCamelCase_      :     Optional[Any]=None      ,							**lowerCamelCase_      :     List[Any]      ,							):
            super().__init__(**lowerCamelCase_    )

            a_    :     Dict										=    num_channels
            a_    :     Optional[int]										=    patch_size
            a_    :     int										=    num_stages
            a_    :     Any										=    [9_6, 1_9_2, 3_8_4, 7_6_8] if hidden_sizes is None else hidden_sizes
            a_    :     Any										=    [3, 3, 9, 3] if depths is None else depths
            a_    :     Any										=    hidden_act
            a_    :     Dict										=    initializer_range
            a_    :     Optional[Any]										=    layer_norm_eps
            a_    :     int										=    drop_path_rate
            a_    :     Optional[Any]										=    image_size
            a_    :     Dict										=    ["""stem"""] + [F'''stage{idx}''' for idx in range(1      ,							len(self.depths    ) + 1    )]
            a_			,			a_    :     int										=    get_aligned_output_features_output_indices(
                out_features=lowerCamelCase_      ,							out_indices=lowerCamelCase_      ,							stage_names=self.stage_names    )



