




'''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


a_      :		Optional[int]							      =       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   __UpperCamelCase       ( lowerCamelCase__				):






       def      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







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






       def      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=self.get_masked_index(lowerCAmelCase  )
              lowerCamelCase_							=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,		lowerCAmelCase  ):



              """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,		lowerCAmelCase,		lowerCAmelCase=None,		**lowerCAmelCase  ):



              """simple docstring"""







              if return_tensors is None:
                     lowerCamelCase_							=self.framework
              lowerCamelCase_							=self.tokenizer(lowerCAmelCase,		return_tensors=lowerCAmelCase  )
              self.ensure_exactly_one_mask_token(lowerCAmelCase  )
              return model_inputs






       def      lowercase__     (							self,		lowerCAmelCase  ):



              """simple docstring"""







              lowerCamelCase_							=self.model(**lowerCAmelCase  )
              lowerCamelCase_							=model_inputs['''input_ids''']
              return model_outputs






       def      lowercase__     (							self,		lowerCAmelCase,		lowerCAmelCase=5,		lowerCAmelCase=None  ):



              """simple docstring"""







              if target_ids is not None and target_ids.shape[0] < top_k:
                     lowerCamelCase_							=target_ids.shape[0]
              lowerCamelCase_							=model_outputs['''input_ids'''][0]
              lowerCamelCase_							=model_outputs['''logits''']

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

                     lowerCamelCase_							=outputs.numpy()

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

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

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

                     lowerCamelCase_,      lowerCamelCase_							=probs.topk(lowerCAmelCase  )

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

                            lowerCamelCase_							=p
                            # Filter padding out:
                            lowerCamelCase_							=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
                            lowerCamelCase_							=self.tokenizer.decode(lowerCAmelCase,		skip_special_tokens=lowerCAmelCase  )
                            lowerCamelCase_							={'''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,		lowerCAmelCase,		lowerCAmelCase=None  ):



              """simple docstring"""







              if isinstance(lowerCAmelCase,		lowerCAmelCase  ):
                     lowerCamelCase_							=[targets]
              try:
                     lowerCamelCase_							=self.tokenizer.get_vocab()
              except Exception:
                     lowerCamelCase_							={}
              lowerCamelCase_							=[]
              for target in targets:
                     lowerCamelCase_							=vocab.get(lowerCAmelCase,		lowerCAmelCase  )
                     if id_ is None:
                            lowerCamelCase_							=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
                            lowerCamelCase_							=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_  )
              lowerCamelCase_							=list(set(lowerCAmelCase  )  )
              if len(lowerCAmelCase  ) == 0:
                     raise ValueError('''At least one target must be provided when passed.'''  )
              lowerCamelCase_							=np.array(lowerCAmelCase  )
              return target_ids






       def      lowercase__     (							self,		lowerCAmelCase=None,		lowerCAmelCase=None  ):



              """simple docstring"""







              lowerCamelCase_							={}

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

              if top_k is not None:
                     lowerCamelCase_							=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  ):



              """simple docstring"""







              lowerCamelCase_							=super().__call__(lowerCAmelCase,		**lowerCAmelCase  )
              if isinstance(lowerCAmelCase,		lowerCAmelCase  ) and len(lowerCAmelCase  ) == 1:
                     return outputs[0]
              return outputs





'''simple docstring'''

import json
import os
import unittest

from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class 			UpperCAmelCase  (						a__    ,						unittest.TestCase					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    CTRLTokenizer
       SCREAMING_SNAKE_CASE							=    False
       SCREAMING_SNAKE_CASE							=    False

       def _lowerCAmelCase(						self )  ->  Dict:
        super().setUp()

        # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
        lowercase__				:    Optional[Any]  =					['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>''']
        lowercase__				:    str  =					dict(zip(__lowerCAmelCase	,   range(len(__lowerCAmelCase ) ) ) )
        lowercase__				:    Tuple  =					['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', '''''']
        lowercase__				:    Optional[Any]  =					{'''unk_token''': '''<unk>'''}

        lowercase__				:    Dict  =					os.path.join(self.tmpdirname	,   VOCAB_FILES_NAMES['''vocab_file'''] )
        lowercase__				:    Dict  =					os.path.join(self.tmpdirname	,   VOCAB_FILES_NAMES['''merges_file'''] )
        with open(self.vocab_file	,   '''w'''	,   encoding='''utf-8''' ) as fp:
         fp.write(json.dumps(__lowerCAmelCase ) + '''\n''' )
        with open(self.merges_file	,   '''w'''	,   encoding='''utf-8''' ) as fp:
         fp.write('''\n'''.join(__lowerCAmelCase ) )

       def _lowerCAmelCase(						self	,   **__lowerCAmelCase )  ->  List[str]:
        kwargs.update(self.special_tokens_map )
        return CTRLTokenizer.from_pretrained(self.tmpdirname	,   **__lowerCAmelCase )

       def _lowerCAmelCase(						self	,   __lowerCAmelCase )  ->  List[str]:
        lowercase__				:    List[str]  =					'''adapt react readapt apt'''
        lowercase__				:    Union[str, Any]  =					'''adapt react readapt apt'''
        return input_text, output_text


       def _lowerCAmelCase(						self )  ->  Optional[Any]:
        lowercase__				:    Union[str, Any]  =					CTRLTokenizer(self.vocab_file	,   self.merges_file	,   **self.special_tokens_map )
        lowercase__				:    Optional[Any]  =					'''adapt react readapt apt'''
        lowercase__				:    Dict  =					'''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split()
        lowercase__				:    Union[str, Any]  =					tokenizer.tokenize(__lowerCAmelCase )
        self.assertListEqual(__lowerCAmelCase	,   __lowerCAmelCase )

        lowercase__				:    int  =					tokens + [tokenizer.unk_token]

        lowercase__				:    List[str]  =					[0, 1, 2, 4, 5, 1, 0, 3, 6]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase )	,   __lowerCAmelCase )

