
'''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'\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    _a				(SCREAMING_SNAKE_CASE_):





       """simple docstring"""




       def        UpperCamelCase				(							self       ,							A__      )    ->			Dict:
          if self.framework == "tf":
             _SCREAMING_SNAKE_CASE      =				tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
          elif self.framework == "pt":
             _SCREAMING_SNAKE_CASE      =				torch.nonzero(input_ids == self.tokenizer.mask_token_id       ,							as_tuple=UpperCamelCase__      )
          else:
             raise ValueError("""Unsupported framework"""      )
          return masked_index






       def        UpperCamelCase				(							self       ,							A__      )    ->			List[Any]:
          _SCREAMING_SNAKE_CASE      =				self.get_masked_index(UpperCamelCase__      )
          _SCREAMING_SNAKE_CASE      =				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       ,							A__      )    ->			Optional[int]:
          if isinstance(UpperCamelCase__       ,							UpperCamelCase__      ):
             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(UpperCamelCase__      )






       def        UpperCamelCase				(							self       ,							A__       ,							A__=None       ,							**A__      )    ->			int:
          if return_tensors is None:
             _SCREAMING_SNAKE_CASE      =				self.framework
          _SCREAMING_SNAKE_CASE      =				self.tokenizer(UpperCamelCase__       ,							return_tensors=UpperCamelCase__      )
          self.ensure_exactly_one_mask_token(UpperCamelCase__      )
          return model_inputs






       def        UpperCamelCase				(							self       ,							A__      )    ->			Union[str, Any]:
          _SCREAMING_SNAKE_CASE      =				self.model(**UpperCamelCase__      )
          _SCREAMING_SNAKE_CASE      =				model_inputs['''input_ids''']
          return model_outputs






       def        UpperCamelCase				(							self       ,							A__       ,							A__=5       ,							A__=None      )    ->			Dict:
          # Cap top_k if there are targets
          if target_ids is not None and target_ids.shape[0] < top_k:
             _SCREAMING_SNAKE_CASE      =				target_ids.shape[0]
          _SCREAMING_SNAKE_CASE      =				model_outputs['''input_ids'''][0]
          _SCREAMING_SNAKE_CASE      =				model_outputs['''logits''']

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

             _SCREAMING_SNAKE_CASE      =				outputs.numpy()

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

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

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

             _SCREAMING_SNAKE_CASE      =				probs.topk(UpperCamelCase__      )

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

                _SCREAMING_SNAKE_CASE      =				p
                # Filter padding out:
                _SCREAMING_SNAKE_CASE      =				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
                _SCREAMING_SNAKE_CASE      =				self.tokenizer.decode(UpperCamelCase__       ,							skip_special_tokens=UpperCamelCase__      )
                _SCREAMING_SNAKE_CASE      =				{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]      ), '''sequence''': sequence}
                row.append(UpperCamelCase__      )
             result.append(UpperCamelCase__      )
          if single_mask:
             return result[0]
          return result






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






       def        UpperCamelCase				(							self       ,							A__=None       ,							A__=None      )    ->			Tuple:
          _SCREAMING_SNAKE_CASE      =				{}

          if targets is not None:
             _SCREAMING_SNAKE_CASE      =				self.get_target_ids(UpperCamelCase__       ,							UpperCamelCase__      )
             _SCREAMING_SNAKE_CASE      =				target_ids

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








'''simple docstring'''



import numpy as np
import torch
from torch.utils.data import Dataset

from utils import logger

class    _a				(_lowerCamelCase):





       """simple docstring"""




       def __init__(							self       ,							A__       ,							A__      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				params

          _SCREAMING_SNAKE_CASE      =				np.array(A__      )
          _SCREAMING_SNAKE_CASE      =				np.array([len(A__      ) for t in data]      )

          self.check()
          self.remove_long_sequences()
          self.remove_empty_sequences()
          self.remove_unknown_sequences()
          self.check()
          self.print_statistics()






       def __getitem__(							self       ,							A__      )    ->			Dict:
          return (self.token_ids[index], self.lengths[index])






       def __len__(							self      )    ->			Tuple:
          return len(self.lengths      )






       def        UpperCamelCase				(							self      )    ->			Dict:
          assert len(self.token_ids      ) == len(self.lengths      )
          assert all(self.lengths[i] == len(self.token_ids[i]      ) for i in range(len(self.lengths      )      )      )






       def        UpperCamelCase				(							self      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				self.params.max_model_input_size
          _SCREAMING_SNAKE_CASE      =				self.lengths > max_len
          logger.info(F"Splitting {sum(A__      )} too long sequences."      )

          def divide_chunks(A__       ,							A__      ):
             return [l[i : i + n] for i in range(0       ,							len(A__      )       ,							A__      )]

          _SCREAMING_SNAKE_CASE      =				[]
          _SCREAMING_SNAKE_CASE      =				[]
          if self.params.mlm:
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""cls_token"""], self.params.special_tok_ids["""sep_token"""]
          else:
             _SCREAMING_SNAKE_CASE ,							_SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""bos_token"""], self.params.special_tok_ids["""eos_token"""]

          for seq_, len_ in zip(self.token_ids       ,							self.lengths      ):
             assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_
             if len_ <= max_len:
                new_tok_ids.append(seq_      )
                new_lengths.append(len_      )
             else:
                _SCREAMING_SNAKE_CASE      =				[]
                for sub_s in divide_chunks(seq_       ,							max_len - 2      ):
                   if sub_s[0] != cls_id:
                      _SCREAMING_SNAKE_CASE      =				np.insert(A__       ,							0       ,							A__      )
                   if sub_s[-1] != sep_id:
                      _SCREAMING_SNAKE_CASE      =				np.insert(A__       ,							len(A__      )       ,							A__      )
                   assert len(A__      ) <= max_len
                   assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s
                   sub_seqs.append(A__      )

                new_tok_ids.extend(A__      )
                new_lengths.extend([len(A__      ) for l in sub_seqs]      )

          _SCREAMING_SNAKE_CASE      =				np.array(A__      )
          _SCREAMING_SNAKE_CASE      =				np.array(A__      )






       def        UpperCamelCase				(							self      )    ->			List[str]:
          _SCREAMING_SNAKE_CASE      =				len(self      )
          _SCREAMING_SNAKE_CASE      =				self.lengths > 11
          _SCREAMING_SNAKE_CASE      =				self.token_ids[indices]
          _SCREAMING_SNAKE_CASE      =				self.lengths[indices]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          logger.info(F"Remove {init_size - new_size} too short (<=11 tokens) sequences."      )






       def        UpperCamelCase				(							self      )    ->			int:
          if "unk_token" not in self.params.special_tok_ids:
             return
          else:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""unk_token"""]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          _SCREAMING_SNAKE_CASE      =				np.array([np.count_nonzero(a == unk_token_id      ) for a in self.token_ids]      )
          _SCREAMING_SNAKE_CASE      =				(unk_occs / self.lengths) < 0.5
          _SCREAMING_SNAKE_CASE      =				self.token_ids[indices]
          _SCREAMING_SNAKE_CASE      =				self.lengths[indices]
          _SCREAMING_SNAKE_CASE      =				len(self      )
          logger.info(F"Remove {init_size - new_size} sequences with a high level of unknown tokens (50%)."      )






       def        UpperCamelCase				(							self      )    ->			Optional[Any]:
          if not self.params.is_master:
             return
          logger.info(F"{len(self      )} sequences"      )
          # data_len = sum(self.lengths)
          # nb_unique_tokens = len(Counter(list(chain(*self.token_ids))))
          # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)')

          # unk_idx = self.params.special_tok_ids['unk_token']
          # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids])
          # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)')






       def        UpperCamelCase				(							self       ,							A__      )    ->			Any:
          _SCREAMING_SNAKE_CASE      =				[t[0] for t in batch]
          _SCREAMING_SNAKE_CASE      =				[t[1] for t in batch]
          assert len(A__      ) == len(A__      )

          # Max for paddings
          _SCREAMING_SNAKE_CASE      =				max(A__      )

          # Pad token ids
          if self.params.mlm:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""pad_token"""]
          else:
             _SCREAMING_SNAKE_CASE      =				self.params.special_tok_ids["""unk_token"""]
          _SCREAMING_SNAKE_CASE      =				[list(t.astype(A__      )      ) + [pad_idx] * (max_seq_len_ - len(A__      )) for t in token_ids]
          assert len(tk_      ) == len(A__      )
          assert all(len(A__      ) == max_seq_len_ for t in tk_      )

          _SCREAMING_SNAKE_CASE      =				torch.tensor(tk_      )  # (bs, max_seq_len_)
          _SCREAMING_SNAKE_CASE      =				torch.tensor(A__      )  # (bs)
          return tk_t, lg_t






