





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     :     Any 					=	logging.get_logger(__name__)







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







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						np.ndarray:



        '''simple docstring'''




        if self.framework == "tf":
          a__     : Dict  =tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
        elif self.framework == "pt":
          a__     : List[Any]  =torch.nonzero(input_ids == self.tokenizer.mask_token_id		,				as_tuple=lowerCAmelCase__							)
        else:
          raise ValueError("Unsupported framework"							)
        return masked_index







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						np.ndarray:



        '''simple docstring'''




        a__     : int  =self.get_masked_index(lowerCAmelCase__							)
        a__     : Tuple  =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__							)       ->						Any:



        '''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__							)       ->						Dict[str, GenericTensor]:



        '''simple docstring'''




        if return_tensors is None:
          a__     : Tuple  =self.framework
        a__     : List[Any]  =self.tokenizer(lowerCAmelCase__		,				return_tensors=lowerCAmelCase__							)
        self.ensure_exactly_one_mask_token(lowerCAmelCase__							)
        return model_inputs







      def        _lowercase  (   self		,				lowerCAmelCase__							)       ->						int:



        '''simple docstring'''




        a__     : Union[str, Any]  =self.model(**lowerCAmelCase__							)
        a__     : Union[str, Any]  =model_inputs["input_ids"]
        return model_outputs







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__=5		,				lowerCAmelCase__=None							)       ->						Optional[Any]:



        '''simple docstring'''




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

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

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

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

          a__     : List[Any]  =tf.math.top_k(lowerCAmelCase__		,				k=lowerCAmelCase__							)
          a__     : Any  =topk.values.numpy(), topk.indices.numpy()
        else:
          a__     : List[str]  =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__     : int  =outputs[0, masked_index, :]
          a__     : Union[str, Any]  =logits.softmax(dim=-1							)
          if target_ids is not None:
            a__     : Optional[Any]  =probs[..., target_ids]

          a__     : str  =probs.topk(lowerCAmelCase__							)

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

            a__     : str  =p
            # Filter padding out:
            a__     : Tuple  =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__     : Dict  =self.tokenizer.decode(lowerCAmelCase__		,				skip_special_tokens=lowerCAmelCase__							)
            a__     : Dict  ={"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							)       ->						Any:



        '''simple docstring'''




        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							):
          a__     : str  =[targets]
        try:
          a__     : Tuple  =self.tokenizer.get_vocab()
        except Exception:
          a__     : List[str]  ={}
        a__     : int  =[]
        for target in targets:
          a__     : Tuple  =vocab.get(lowerCAmelCase__		,				lowerCAmelCase__							)
          if id_ is None:
            a__     : Optional[int]  =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__     : int  =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__     : List[Any]  =list(set(lowerCAmelCase__							)							)
        if len(lowerCAmelCase__							) == 0:
          raise ValueError("At least one target must be provided when passed."							)
        a__     : Tuple  =np.array(lowerCAmelCase__							)
        return target_ids







      def        _lowercase  (   self		,				lowerCAmelCase__=None		,				lowerCAmelCase__=None							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : Union[str, Any]  ={}

        if targets is not None:
          a__     : Any  =self.get_target_ids(lowerCAmelCase__		,				lowerCAmelCase__							)
          a__     : Union[str, Any]  =target_ids

        if top_k is not None:
          a__     : Any  =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__							)       ->						str:



        '''simple docstring'''




        a__     : List[str]  =super().__call__(lowerCAmelCase__		,				**lowerCAmelCase__							)
        if isinstance(lowerCAmelCase__		,				lowerCAmelCase__							) and len(lowerCAmelCase__							) == 1:
          return outputs[0]
        return outputs













import unittest

from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         NystromformerForMaskedLM,
         NystromformerForMultipleChoice,
         NystromformerForQuestionAnswering,
         NystromformerForSequenceClassification,
         NystromformerForTokenClassification,
         NystromformerModel,
     )
     from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST







class     __lowerCAmelCase	:







      def __init__(   self		,				lowerCAmelCase__		,				lowerCAmelCase__=1_3		,				lowerCAmelCase__=7		,				lowerCAmelCase__=True		,				lowerCAmelCase__=True		,				lowerCAmelCase__=True		,				lowerCAmelCase__=True		,				lowerCAmelCase__=9_9		,				lowerCAmelCase__=3_2		,				lowerCAmelCase__=5		,				lowerCAmelCase__=4		,				lowerCAmelCase__=3_7		,				lowerCAmelCase__="gelu"		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=0.1		,				lowerCAmelCase__=5_1_2		,				lowerCAmelCase__=1_6		,				lowerCAmelCase__=2		,				lowerCAmelCase__=0.02		,				lowerCAmelCase__=3		,				lowerCAmelCase__=4		,				lowerCAmelCase__=None		,				)       ->						List[Any]:



        '''simple docstring'''




        a__     : Optional[Any]  =parent
        a__     : Tuple  =batch_size
        a__     : List[Any]  =seq_length
        a__     : Dict  =is_training
        a__     : Any  =use_input_mask
        a__     : int  =use_token_type_ids
        a__     : Optional[Any]  =use_labels
        a__     : Optional[Any]  =vocab_size
        a__     : List[str]  =hidden_size
        a__     : int  =num_hidden_layers
        a__     : Tuple  =num_attention_heads
        a__     : Union[str, Any]  =intermediate_size
        a__     : Optional[int]  =hidden_act
        a__     : int  =hidden_dropout_prob
        a__     : Union[str, Any]  =attention_probs_dropout_prob
        a__     : List[Any]  =max_position_embeddings
        a__     : str  =type_vocab_size
        a__     : Optional[Any]  =type_sequence_label_size
        a__     : Union[str, Any]  =initializer_range
        a__     : List[Any]  =num_labels
        a__     : str  =num_choices
        a__     : int  =scope







      def        _lowercase  (   self							)       ->						int:



        '''simple docstring'''




        a__     : List[Any]  =ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

        a__     : str  =None
        if self.use_input_mask:
          a__     : List[Any]  =random_attention_mask([self.batch_size, self.seq_length]							)

        a__     : str  =None
        if self.use_token_type_ids:
          a__     : List[str]  =ids_tensor([self.batch_size, self.seq_length]		,				self.type_vocab_size							)

        a__     : Dict  =None
        a__     : str  =None
        a__     : str  =None
        if self.use_labels:
          a__     : List[str]  =ids_tensor([self.batch_size]		,				self.type_sequence_label_size							)
          a__     : Tuple  =ids_tensor([self.batch_size, self.seq_length]		,				self.num_labels							)
          a__     : Dict  =ids_tensor([self.batch_size]		,				self.num_choices							)

        a__     : Tuple  =self.get_config()

        return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







      def        _lowercase  (   self							)       ->						Tuple:



        '''simple docstring'''




        return NystromformerConfig(
            vocab_size=self.vocab_size		,				hidden_size=self.hidden_size		,				num_hidden_layers=self.num_hidden_layers		,				num_attention_heads=self.num_attention_heads		,				intermediate_size=self.intermediate_size		,				hidden_act=self.hidden_act		,				hidden_dropout_prob=self.hidden_dropout_prob		,				attention_probs_dropout_prob=self.attention_probs_dropout_prob		,				max_position_embeddings=self.max_position_embeddings		,				type_vocab_size=self.type_vocab_size		,				is_decoder=lowerCAmelCase__		,				initializer_range=self.initializer_range		,				)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						List[Any]:



        '''simple docstring'''




        a__     : Tuple  =NystromformerModel(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : Optional[Any]  =model(lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__							)
        a__     : str  =model(lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__							)
        a__     : Optional[int]  =model(lowerCAmelCase__							)
        self.parent.assertEqual(result.last_hidden_state.shape		,				(self.batch_size, self.seq_length, self.hidden_size)							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						int:



        '''simple docstring'''




        a__     : int  =NystromformerForMaskedLM(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : Dict  =model(lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__		,				labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Any:



        '''simple docstring'''




        a__     : Optional[int]  =NystromformerForQuestionAnswering(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : str  =model(
            lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__		,				start_positions=lowerCAmelCase__		,				end_positions=lowerCAmelCase__		,				)
        self.parent.assertEqual(result.start_logits.shape		,				(self.batch_size, self.seq_length)							)
        self.parent.assertEqual(result.end_logits.shape		,				(self.batch_size, self.seq_length)							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Optional[int]:



        '''simple docstring'''




        a__     : Optional[Any]  =self.num_labels
        a__     : Dict  =NystromformerForSequenceClassification(lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : List[str]  =model(lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__		,				labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						List[str]:



        '''simple docstring'''




        a__     : Tuple  =self.num_labels
        a__     : List[str]  =NystromformerForTokenClassification(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : List[Any]  =model(lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__		,				labels=lowerCAmelCase__							)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)							)







      def        _lowercase  (   self		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__		,				lowerCAmelCase__							)       ->						Tuple:



        '''simple docstring'''




        a__     : List[Any]  =self.num_choices
        a__     : Optional[Any]  =NystromformerForMultipleChoice(config=lowerCAmelCase__							)
        model.to(lowerCAmelCase__							)
        model.eval()
        a__     : List[str]  =input_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
        a__     : List[Any]  =token_type_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
        a__     : List[Any]  =input_mask.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
        a__     : Dict  =model(
            lowerCAmelCase__		,				attention_mask=lowerCAmelCase__		,				token_type_ids=lowerCAmelCase__		,				labels=lowerCAmelCase__		,				)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)							)







      def        _lowercase  (   self							)       ->						Tuple:



        '''simple docstring'''




        a__     : Optional[Any]  =self.prepare_config_and_inputs()
        (
            (
            a__
        ) ,							(
            a__
        ) ,							(
            a__
        ) ,							(
            a__
        ) ,							(
            a__
        ) ,							(
            a__
        ) ,							(
            a__
        ) ,							
        )     : List[str]  =config_and_inputs
        a__     : str  ={"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
        return config, inputs_dict







@require_torch
class     __lowerCAmelCase	(   UpperCamelCase__						,    UpperCamelCase__						,    unittest.TestCase):
      _lowercase    : int            =      (
          (
              NystromformerModel,
              NystromformerForMaskedLM,
              NystromformerForMultipleChoice,
              NystromformerForQuestionAnswering,
              NystromformerForSequenceClassification,
              NystromformerForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      _lowercase    : Union[str, Any]            =      (
          {
              """feature-extraction""": NystromformerModel,
              """fill-mask""": NystromformerForMaskedLM,
              """question-answering""": NystromformerForQuestionAnswering,
              """text-classification""": NystromformerForSequenceClassification,
              """token-classification""": NystromformerForTokenClassification,
              """zero-shot""": NystromformerForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      _lowercase    : Union[str, Any]            =      False
      _lowercase    : Union[str, Any]            =      False







      def        _lowercase  (   self							)       ->						List[str]:



        '''simple docstring'''




        a__     : Optional[int]  =NystromformerModelTester(self							)
        a__     : Optional[int]  =ConfigTester(self		,				config_class=lowerCAmelCase__		,				hidden_size=3_7							)







      def        _lowercase  (   self							)       ->						int:



        '''simple docstring'''




        self.config_tester.run_common_tests()







      def        _lowercase  (   self							)       ->						Dict:



        '''simple docstring'''




        a__     : List[str]  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




        a__     : Tuple  =self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
          a__     : int  =type
          self.model_tester.create_and_check_model(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




        a__     : Optional[Any]  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Dict:



        '''simple docstring'''




        a__     : str  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						List[str]:



        '''simple docstring'''




        a__     : Tuple  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Union[str, Any]:



        '''simple docstring'''




        a__     : Tuple  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__							)







      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




        a__     : int  =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__							)







      @slow
      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          a__     : int  =NystromformerModel.from_pretrained(lowerCAmelCase__							)
          self.assertIsNotNone(lowerCAmelCase__							)







@require_torch
class     __lowerCAmelCase	(   unittest.TestCase):







      @slow
      def        _lowercase  (   self							)       ->						str:



        '''simple docstring'''




        a__     : str  =NystromformerModel.from_pretrained("uw-madison/nystromformer-512"							)
        a__     : int  =torch.tensor([[0, 1, 2, 3, 4, 5]]							)

        with torch.no_grad():
          a__     : Tuple  =model(lowerCAmelCase__							)[0]

        a__     : List[str]  =torch.Size((1, 6, 7_6_8)							)
        self.assertEqual(output.shape		,				lowerCAmelCase__							)

        a__     : int  =torch.tensor(
            [[[-0.45_32, -0.09_36, 0.51_37], [-0.26_76, 0.06_28, 0.61_86], [-0.36_29, -0.17_26, 0.47_16]]]							)

        self.assertTrue(torch.allclose(output[:, :3, :3]		,				lowerCAmelCase__		,				atol=1E-4							)							)







      @slow
      def        _lowercase  (   self							)       ->						Optional[Any]:



        '''simple docstring'''




        a__     : Union[str, Any]  ="the [MASK] of Belgium is Brussels"

        a__     : str  =AutoTokenizer.from_pretrained("uw-madison/nystromformer-512"							)
        a__     : int  =NystromformerForMaskedLM.from_pretrained("uw-madison/nystromformer-512"							)

        a__     : List[Any]  =tokenizer(lowerCAmelCase__		,				return_tensors="pt"							)

        with torch.no_grad():
          a__     : str  =model(encoding.input_ids							).logits

        a__     : List[str]  =token_logits[:, 2, :].argmax(-1							)[0]

        self.assertEqual(tokenizer.decode(lowerCAmelCase__							)		,				"capital"							)






