





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     lowercase__       :

   '''simple docstring'''


   def __init__(    self,		__magic_name__,		__magic_name__=13,		__magic_name__=7,		__magic_name__=True,		__magic_name__=True,		__magic_name__=True,		__magic_name__=True,		__magic_name__=99,		__magic_name__=32,		__magic_name__=5,		__magic_name__=4,		__magic_name__=37,		__magic_name__="gelu",		__magic_name__=0.1,		__magic_name__=0.1,		__magic_name__=512,		__magic_name__=16,		__magic_name__=2,		__magic_name__=0.02,		__magic_name__=3,		__magic_name__=4,		__magic_name__=None,		) ->      Any:






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




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				List[Any]          =      ids_tensor([self.batch_size, self.seq_length],		self.vocab_size							)

       UpperCamelCase__							:				Dict          =      None
       if self.use_input_mask:
           UpperCamelCase__							:				Optional[Any]          =      random_attention_mask([self.batch_size, self.seq_length]							)

       UpperCamelCase__							:				Tuple          =      None
       if self.use_token_type_ids:
           UpperCamelCase__							:				Dict          =      ids_tensor([self.batch_size, self.seq_length],		self.type_vocab_size							)

       UpperCamelCase__							:				Tuple          =      None
       UpperCamelCase__							:				List[Any]          =      None
       UpperCamelCase__							:				Optional[Any]          =      None
       if self.use_labels:
           UpperCamelCase__							:				List[Any]          =      ids_tensor([self.batch_size],		self.type_sequence_label_size							)
           UpperCamelCase__							:				Optional[int]          =      ids_tensor([self.batch_size, self.seq_length],		self.num_labels							)
           UpperCamelCase__							:				Optional[Any]          =      ids_tensor([self.batch_size],		self.num_choices							)

       UpperCamelCase__							:				Union[str, Any]          =      self.get_config()

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




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






       """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=__magic_name__,		initializer_range=self.initializer_range,		)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				int          =      NystromformerModel(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				Union[str, Any]          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__							)
       UpperCamelCase__							:				str          =      model(__magic_name__,		token_type_ids=__magic_name__							)
       UpperCamelCase__							:				int          =      model(__magic_name__							)
       self.parent.assertEqual(result.last_hidden_state.shape,		(self.batch_size, self.seq_length, self.hidden_size)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				str          =      NystromformerForMaskedLM(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				Dict          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.vocab_size)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      NystromformerForQuestionAnswering(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				Tuple          =      model(
           __magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		start_positions=__magic_name__,		end_positions=__magic_name__,		)
       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       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      self.num_labels
       UpperCamelCase__							:				Any          =      NystromformerForSequenceClassification(__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[str]          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_labels)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      List[str]:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      self.num_labels
       UpperCamelCase__							:				Union[str, Any]          =      NystromformerForTokenClassification(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[Any]          =      model(__magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		labels=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.seq_length, self.num_labels)							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      self.num_choices
       UpperCamelCase__							:				Optional[Any]          =      NystromformerForMultipleChoice(config=__magic_name__							)
       model.to(__magic_name__							)
       model.eval()
       UpperCamelCase__							:				List[Any]          =      input_ids.unsqueeze(1							).expand(-1,		self.num_choices,		-1							).contiguous()
       UpperCamelCase__							:				int          =      token_type_ids.unsqueeze(1							).expand(-1,		self.num_choices,		-1							).contiguous()
       UpperCamelCase__							:				Dict          =      input_mask.unsqueeze(1							).expand(-1,		self.num_choices,		-1							).contiguous()
       UpperCamelCase__							:				Any          =      model(
           __magic_name__,		attention_mask=__magic_name__,		token_type_ids=__magic_name__,		labels=__magic_name__,		)
       self.parent.assertEqual(result.logits.shape,		(self.batch_size, self.num_choices)							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,(
           UpperCamelCase__
       )   ,
       )							:				List[Any]          =      config_and_inputs
       UpperCamelCase__							:				str          =      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
       return config, inputs_dict






@require_torch
class     lowercase__       (	__lowerCamelCase			,				__lowerCamelCase			,				unittest.TestCase				):

   '''simple docstring'''


   a						:							int   		=		(
       (
           NystromformerModel,
           NystromformerForMaskedLM,
           NystromformerForMultipleChoice,
           NystromformerForQuestionAnswering,
           NystromformerForSequenceClassification,
           NystromformerForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   a						:							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 {}
   )
   a						:							Optional[int]   		=		False
   a						:							int   		=		False




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				int          =      NystromformerModelTester(self							)
       UpperCamelCase__							:				List[Any]          =      ConfigTester(self,		config_class=__magic_name__,		hidden_size=37							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       self.config_tester.run_common_tests()




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Union[str, Any]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
           UpperCamelCase__							:				Dict          =      type
           self.model_tester.create_and_check_model(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Dict          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*__magic_name__							)




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






       """simple docstring"""
       UpperCamelCase__							:				int          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*__magic_name__							)




   def       UpperCamelCase__  (    self							) ->      int:






       """simple docstring"""
       UpperCamelCase__							:				str          =      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*__magic_name__							)




   @slow
   def       UpperCamelCase__  (    self							) ->      str:






       """simple docstring"""
       for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:				Union[str, Any]          =      NystromformerModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)






@require_torch
class     lowercase__       (	unittest.TestCase				):

   '''simple docstring'''


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






       """simple docstring"""
       UpperCamelCase__							:				Tuple          =      NystromformerModel.from_pretrained('''uw-madison/nystromformer-512'''							)
       UpperCamelCase__							:				Union[str, Any]          =      torch.tensor([[0, 1, 2, 3, 4, 5]]							)

       with torch.no_grad():
           UpperCamelCase__							:				Union[str, Any]          =      model(__magic_name__							)[0]

       UpperCamelCase__							:				int          =      torch.Size((1, 6, 768)							)
       self.assertEqual(output.shape,		__magic_name__							)

       UpperCamelCase__							:				Optional[int]          =      torch.tensor(
           [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]]							)

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




   @slow
   def       UpperCamelCase__  (    self							) ->      Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      '''the [MASK] of Belgium is Brussels'''

       UpperCamelCase__							:				Dict          =      AutoTokenizer.from_pretrained('''uw-madison/nystromformer-512'''							)
       UpperCamelCase__							:				List[Any]          =      NystromformerForMaskedLM.from_pretrained('''uw-madison/nystromformer-512'''							)

       UpperCamelCase__							:				Union[str, Any]          =      tokenizer(__magic_name__,		return_tensors='''pt'''							)

       with torch.no_grad():
           UpperCamelCase__							:				Tuple          =      model(encoding.input_ids							).logits

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

       self.assertEqual(tokenizer.decode(__magic_name__							),		'''capital'''							)








UpperCAmelCase_     							= 'Input must be a string of 8 numbers plus letter'
UpperCAmelCase_     							= 'TRWAGMYFPDXBNJZSQVHLCKE'




def 		lowerCAmelCase_    (  __UpperCAmelCase:			str      )      ->	bool:

    if not isinstance(__UpperCAmelCase		,   __UpperCAmelCase      ):
        UpperCamelCase__							:				Any          =      f"Expected string as input, found {type(__UpperCAmelCase      ).__name__}"
        raise TypeError(__UpperCAmelCase      )

    UpperCamelCase__							:				int          =      spanish_id.replace('''-'''		,   ''''''      ).upper()
    if len(__UpperCAmelCase      ) != 9:
        raise ValueError(__UpperCAmelCase      )

    try:
        UpperCamelCase__							:				List[str]          =      int(spanish_id_clean[0:8]      )
        UpperCamelCase__							:				Optional[int]          =      spanish_id_clean[8]
    except ValueError as ex:
        raise ValueError(__UpperCAmelCase      ) from ex

    if letter.isdigit():
        raise ValueError(__UpperCAmelCase      )

    return letter == LOOKUP_LETTERS[number % 23]


if __name__ == "__main__":
  import doctest

  doctest.testmod()

