






'''simple docstring'''

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


UpperCamelCase							=logging.get_logger(__name__)




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






 """simple docstring"""





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       if self.framework == "tf":
             UpperCamelCase_				:   int					    =							tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
       elif self.framework == "pt":
             UpperCamelCase_				:   Tuple					    =							torch.nonzero(input_ids == self.tokenizer.mask_token_id			,     as_tuple=__lowerCAmelCase )
       else:
             raise ValueError("""Unsupported framework""" )
       return masked_index
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Any					    =							self.get_masked_index(__lowerCAmelCase )
       UpperCamelCase_				:   int					    =							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			,     __lowerCAmelCase ):
       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			,     __lowerCAmelCase			,     __lowerCAmelCase=None			,     **__lowerCAmelCase ):
       if return_tensors is None:
             UpperCamelCase_				:   List[Any]					    =							self.framework
       UpperCamelCase_				:   Dict					    =							self.tokenizer(__lowerCAmelCase			,     return_tensors=__lowerCAmelCase )
       self.ensure_exactly_one_mask_token(__lowerCAmelCase )
       return model_inputs
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Optional[int]					    =							self.model(**__lowerCAmelCase )
       UpperCamelCase_				:   Optional[int]					    =							model_inputs["""input_ids"""]
       return model_outputs
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase=5			,     __lowerCAmelCase=None ):
       # Cap top_k if there are targets
       if target_ids is not None and target_ids.shape[0] < top_k:
             UpperCamelCase_				:   Dict					    =							target_ids.shape[0]
       UpperCamelCase_				:   Optional[int]					    =							model_outputs["""input_ids"""][0]
       UpperCamelCase_				:   Optional[Any]					    =							model_outputs["""logits"""]

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

             UpperCamelCase_				:   Optional[int]					    =							outputs.numpy()

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

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

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

             UpperCamelCase_				:   Any					    =							probs.topk(__lowerCAmelCase )

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

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

       if targets is not None:
             UpperCamelCase_				:   Any					    =							self.get_target_ids(__lowerCAmelCase			,     __lowerCAmelCase )
             UpperCamelCase_				:   int					    =							target_ids

       if top_k is not None:
             UpperCamelCase_				:   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			,     __lowerCAmelCase			,     *__lowerCAmelCase			,     **__lowerCAmelCase ):
       UpperCamelCase_				:   Optional[Any]					    =							super().__call__(__lowerCAmelCase			,     **__lowerCAmelCase )
       if isinstance(__lowerCAmelCase			,     __lowerCAmelCase ) and len(__lowerCAmelCase ) == 1:
             return outputs[0]
       return outputs














'''simple docstring'''

import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union

import numpy as np
import torch

from .utils import deprecate, is_transformers_available


if is_transformers_available():
      import transformers



def 							snake_case					(     a_							: int	)       ->				Union[str, Any]:





      """simple docstring"""

      random.seed(a_	)
      np.random.seed(a_	)
      torch.manual_seed(a_	)
      torch.cuda.manual_seed_all(a_	)
      # ^^ safe to call this function even if cuda is not available




class     A    :






 """simple docstring"""





 def __init__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase = 0.99_99			,     __lowerCAmelCase = 0.0			,     __lowerCAmelCase = 0			,     __lowerCAmelCase = False			,     __lowerCAmelCase = 1.0			,     __lowerCAmelCase = 2 / 3			,     __lowerCAmelCase = None			,     __lowerCAmelCase = None			,     **__lowerCAmelCase			,     ):

       if isinstance(__lowerCAmelCase			,     torch.nn.Module ):
             UpperCamelCase_				:   Dict					    =							(
                 """Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. """
                 """Please pass the parameters of the module instead."""
             )
             deprecate(
                 """passing a `torch.nn.Module` to `ExponentialMovingAverage`"""			,     """1.0.0"""			,     __lowerCAmelCase			,     standard_warn=__lowerCAmelCase			,     )
             UpperCamelCase_				:   str					    =							parameters.parameters()

             # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
             UpperCamelCase_				:   Optional[int]					    =							True

       if kwargs.get("""max_value"""			,     __lowerCAmelCase ) is not None:
             UpperCamelCase_				:   Tuple					    =							"""The `max_value` argument is deprecated. Please use `decay` instead."""
             deprecate("""max_value"""			,     """1.0.0"""			,     __lowerCAmelCase			,     standard_warn=__lowerCAmelCase )
             UpperCamelCase_				:   str					    =							kwargs["""max_value"""]

       if kwargs.get("""min_value"""			,     __lowerCAmelCase ) is not None:
             UpperCamelCase_				:   Dict					    =							"""The `min_value` argument is deprecated. Please use `min_decay` instead."""
             deprecate("""min_value"""			,     """1.0.0"""			,     __lowerCAmelCase			,     standard_warn=__lowerCAmelCase )
             UpperCamelCase_				:   Optional[Any]					    =							kwargs["""min_value"""]

       UpperCamelCase_				:   Optional[Any]					    =							list(__lowerCAmelCase )
       UpperCamelCase_				:   Any					    =							[p.clone().detach() for p in parameters]

       if kwargs.get("""device"""			,     __lowerCAmelCase ) is not None:
             UpperCamelCase_				:   str					    =							"""The `device` argument is deprecated. Please use `to` instead."""
             deprecate("""device"""			,     """1.0.0"""			,     __lowerCAmelCase			,     standard_warn=__lowerCAmelCase )
             self.to(device=kwargs["""device"""] )

       UpperCamelCase_				:   List[Any]					    =							None

       UpperCamelCase_				:   Optional[Any]					    =							decay
       UpperCamelCase_				:   List[str]					    =							min_decay
       UpperCamelCase_				:   int					    =							update_after_step
       UpperCamelCase_				:   Optional[int]					    =							use_ema_warmup
       UpperCamelCase_				:   Optional[int]					    =							inv_gamma
       UpperCamelCase_				:   Any					    =							power
       UpperCamelCase_				:   str					    =							0
       UpperCamelCase_				:   List[str]					    =							None  # set in `step()`

       UpperCamelCase_				:   Union[str, Any]					    =							model_cls
       UpperCamelCase_				:   Any					    =							model_config
 @classmethod
 def   _UpperCAmelCase       (							cls			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_    ,			UpperCamelCase_				:   int					    =							model_cls.load_config(__lowerCAmelCase			,     return_unused_kwargs=__lowerCAmelCase )
       UpperCamelCase_				:   str					    =							model_cls.from_pretrained(__lowerCAmelCase )

       UpperCamelCase_				:   Union[str, Any]					    =							cls(model.parameters()			,     model_cls=__lowerCAmelCase			,     model_config=model.config )

       ema_model.load_state_dict(__lowerCAmelCase )
       return ema_model
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       if self.model_cls is None:
             raise ValueError("""`save_pretrained` can only be used if `model_cls` was defined at __init__.""" )

       if self.model_config is None:
             raise ValueError("""`save_pretrained` can only be used if `model_config` was defined at __init__.""" )

       UpperCamelCase_				:   int					    =							self.model_cls.from_config(self.model_config )
       UpperCamelCase_				:   List[Any]					    =							self.state_dict()
       state_dict.pop("""shadow_params"""			,     __lowerCAmelCase )

       model.register_to_config(**__lowerCAmelCase )
       self.copy_to(model.parameters() )
       model.save_pretrained(__lowerCAmelCase )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Any					    =							max(0			,     optimization_step - self.update_after_step - 1 )

       if step <= 0:
             return 0.0

       if self.use_ema_warmup:
             UpperCamelCase_				:   List[Any]					    =							1 - (1 + step / self.inv_gamma) ** -self.power
       else:
             UpperCamelCase_				:   List[Any]					    =							(1 + step) / (10 + step)

       UpperCamelCase_				:   Optional[Any]					    =							min(__lowerCAmelCase			,     self.decay )
       # make sure decay is not smaller than min_decay
       UpperCamelCase_				:   Optional[Any]					    =							max(__lowerCAmelCase			,     self.min_decay )
       return cur_decay_value
 @torch.no_grad()
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       if isinstance(__lowerCAmelCase			,     torch.nn.Module ):
             UpperCamelCase_				:   str					    =							(
                 """Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. """
                 """Please pass the parameters of the module instead."""
             )
             deprecate(
                 """passing a `torch.nn.Module` to `ExponentialMovingAverage.step`"""			,     """1.0.0"""			,     __lowerCAmelCase			,     standard_warn=__lowerCAmelCase			,     )
             UpperCamelCase_				:   int					    =							parameters.parameters()

       UpperCamelCase_				:   Optional[int]					    =							list(__lowerCAmelCase )

       self.optimization_step += 1

       # Compute the decay factor for the exponential moving average.
       UpperCamelCase_				:   Any					    =							self.get_decay(self.optimization_step )
       UpperCamelCase_				:   List[str]					    =							decay
       UpperCamelCase_				:   Any					    =							1 - decay

       UpperCamelCase_				:   Optional[int]					    =							contextlib.nullcontext
       if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
             import deepspeed

       for s_param, param in zip(self.shadow_params			,     __lowerCAmelCase ):
             if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
                   UpperCamelCase_				:   Optional[Any]					    =							deepspeed.zero.GatheredParameters(__lowerCAmelCase			,     modifier_rank=__lowerCAmelCase )

             with context_manager():
                   if param.requires_grad:
                         s_param.sub_(one_minus_decay * (s_param - param) )
                   else:
                         s_param.copy_(__lowerCAmelCase )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							list(__lowerCAmelCase )
       for s_param, param in zip(self.shadow_params			,     __lowerCAmelCase ):
             param.data.copy_(s_param.to(param.device ).data )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase=None			,     __lowerCAmelCase=None ):
       UpperCamelCase_				:   Union[str, Any]					    =							[
           p.to(device=__lowerCAmelCase			,     dtype=__lowerCAmelCase ) if p.is_floating_point() else p.to(device=__lowerCAmelCase )
           for p in self.shadow_params
       ]
 def   _UpperCAmelCase       (							self ):
       return {
           "decay": self.decay,
           "min_decay": self.min_decay,
           "optimization_step": self.optimization_step,
           "update_after_step": self.update_after_step,
           "use_ema_warmup": self.use_ema_warmup,
           "inv_gamma": self.inv_gamma,
           "power": self.power,
           "shadow_params": self.shadow_params,
       }
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[str]					    =							[param.detach().cpu().clone() for param in parameters]
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       if self.temp_stored_params is None:
             raise RuntimeError("""This ExponentialMovingAverage has no `store()`ed weights """ """to `restore()`""" )
       for c_param, param in zip(self.temp_stored_params			,     __lowerCAmelCase ):
             param.data.copy_(c_param.data )

       # Better memory-wise.
       UpperCamelCase_				:   List[Any]					    =							None





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[Any]					    =							copy.deepcopy(__lowerCAmelCase )

       UpperCamelCase_				:   int					    =							state_dict.get("""decay"""			,     self.decay )
       if self.decay < 0.0 or self.decay > 1.0:
             raise ValueError("""Decay must be between 0 and 1""" )

       UpperCamelCase_				:   Dict					    =							state_dict.get("""min_decay"""			,     self.min_decay )
       if not isinstance(self.min_decay			,     __lowerCAmelCase ):
             raise ValueError("""Invalid min_decay""" )

       UpperCamelCase_				:   str					    =							state_dict.get("""optimization_step"""			,     self.optimization_step )
       if not isinstance(self.optimization_step			,     __lowerCAmelCase ):
             raise ValueError("""Invalid optimization_step""" )

       UpperCamelCase_				:   Dict					    =							state_dict.get("""update_after_step"""			,     self.update_after_step )
       if not isinstance(self.update_after_step			,     __lowerCAmelCase ):
             raise ValueError("""Invalid update_after_step""" )

       UpperCamelCase_				:   List[str]					    =							state_dict.get("""use_ema_warmup"""			,     self.use_ema_warmup )
       if not isinstance(self.use_ema_warmup			,     __lowerCAmelCase ):
             raise ValueError("""Invalid use_ema_warmup""" )

       UpperCamelCase_				:   Any					    =							state_dict.get("""inv_gamma"""			,     self.inv_gamma )
       if not isinstance(self.inv_gamma			,     (float, int) ):
             raise ValueError("""Invalid inv_gamma""" )

       UpperCamelCase_				:   str					    =							state_dict.get("""power"""			,     self.power )
       if not isinstance(self.power			,     (float, int) ):
             raise ValueError("""Invalid power""" )

       UpperCamelCase_				:   Dict					    =							state_dict.get("""shadow_params"""			,     __lowerCAmelCase )
       if shadow_params is not None:
             UpperCamelCase_				:   Any					    =							shadow_params
             if not isinstance(self.shadow_params			,     __lowerCAmelCase ):
                   raise ValueError("""shadow_params must be a list""" )
             if not all(isinstance(__lowerCAmelCase			,     torch.Tensor ) for p in self.shadow_params ):
                   raise ValueError("""shadow_params must all be Tensors""" )






