



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		:

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Union[str, Any]=13							,   __lowerCAmelCase			:       Optional[int]=7							,   __lowerCAmelCase			:       Tuple=True							,   __lowerCAmelCase			:       Tuple=True							,   __lowerCAmelCase			:       Union[str, Any]=True							,   __lowerCAmelCase			:       Optional[int]=True							,   __lowerCAmelCase			:       List[Any]=99							,   __lowerCAmelCase			:       str=32							,   __lowerCAmelCase			:       List[str]=5							,   __lowerCAmelCase			:       List[str]=4							,   __lowerCAmelCase			:       List[str]=37							,   __lowerCAmelCase			:       int="gelu"							,   __lowerCAmelCase			:       Any=0.1							,   __lowerCAmelCase			:       List[str]=0.1							,   __lowerCAmelCase			:       List[str]=512							,   __lowerCAmelCase			:       Any=16							,   __lowerCAmelCase			:       Any=2							,   __lowerCAmelCase			:       Dict=0.0_2							,   __lowerCAmelCase			:       Dict=3							,   __lowerCAmelCase			:       List[str]=4							,   __lowerCAmelCase			:       List[Any]=None							,   )       ->				Any:


    """simple docstring"""






    a						=		parent
    a						=		batch_size
    a						=		seq_length
    a						=		is_training
    a						=		use_input_mask
    a						=		use_token_type_ids
    a						=		use_labels
    a						=		vocab_size
    a						=		hidden_size
    a						=		num_hidden_layers
    a						=		num_attention_heads
    a						=		intermediate_size
    a						=		hidden_act
    a						=		hidden_dropout_prob
    a						=		attention_probs_dropout_prob
    a						=		max_position_embeddings
    a						=		type_vocab_size
    a						=		type_sequence_label_size
    a						=		initializer_range
    a						=		num_labels
    a						=		num_choices
    a						=		scope

   def 		A							(      self			:       int							)       ->				Dict:


    """simple docstring"""






    a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.vocab_size							)

    a						=		None
    if self.use_input_mask:
     a						=		random_attention_mask([self.batch_size, self.seq_length]							)

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

    a						=		None
    a						=		None
    a						=		None
    if self.use_labels:
     a						=		ids_tensor([self.batch_size]							,   self.type_sequence_label_size							)
     a						=		ids_tensor([self.batch_size, self.seq_length]							,   self.num_labels							)
     a						=		ids_tensor([self.batch_size]							,   self.num_choices							)

    a						=		self.get_config()

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

   def 		A							(      self			:       int							)       ->				Optional[int]:


    """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 		A							(      self			:       List[str]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       List[str]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		NystromformerModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							)
    self.parent.assertEqual(result.last_hidden_state.shape							,   (self.batch_size, self.seq_length, self.hidden_size)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[Any]							)       ->				List[Any]:


    """simple docstring"""






    a						=		NystromformerForMaskedLM(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		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 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Optional[int]							)       ->				int:


    """simple docstring"""






    a						=		NystromformerForQuestionAnswering(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		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 		A							(      self			:       Optional[int]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Optional[Any]							)       ->				str:


    """simple docstring"""






    a						=		self.num_labels
    a						=		NystromformerForSequenceClassification(__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       str							)       ->				List[str]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		NystromformerForTokenClassification(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		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 		A							(      self			:       Tuple							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Dict							)       ->				str:


    """simple docstring"""






    a						=		self.num_choices
    a						=		NystromformerForMultipleChoice(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		input_ids.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		token_type_ids.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		input_mask.unsqueeze(1							).expand(-1							,   self.num_choices							,   -1							).contiguous()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_choices)							)




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


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    (
        (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  (
        a
    )		,  
    )						=		config_and_inputs
    a						=		{"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
    return config, inputs_dict



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           NystromformerModel,
           NystromformerForMaskedLM,
           NystromformerForMultipleChoice,
           NystromformerForQuestionAnswering,
           NystromformerForSequenceClassification,
           NystromformerForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {
           '''feature-extraction''': NystromformerModel,
           '''fill-mask''': NystromformerForMaskedLM,
           '''question-answering''': NystromformerForQuestionAnswering,
           '''text-classification''': NystromformerForSequenceClassification,
           '''token-classification''': NystromformerForTokenClassification,
           '''zero-shot''': NystromformerForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False

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


    """simple docstring"""






    a						=		NystromformerModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       int							)       ->				str:


    """simple docstring"""






    self.config_tester.run_common_tests()

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase							)

   def 		A							(      self			:       Optional[Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
     a						=		type
     self.model_tester.create_and_check_model(*__lowerCAmelCase							)

   def 		A							(      self			:       Tuple							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase							)

   def 		A							(      self			:       str							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase							)

   def 		A							(      self			:       Union[str, Any]							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase							)

   def 		A							(      self			:       Any							)       ->				str:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase							)

   def 		A							(      self			:       List[str]							)       ->				Tuple:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase							)




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


    """simple docstring"""






    for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     a						=		NystromformerModel.from_pretrained(__lowerCAmelCase							)
     self.assertIsNotNone(__lowerCAmelCase							)



@require_torch
class 		_lowercase		(       unittest.TestCase	):

   @slow
   def 		A							(      self			:       int							)       ->				Optional[int]:


    """simple docstring"""






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

    with torch.no_grad():
     a						=		model(__lowerCAmelCase							)[0]

    a						=		torch.Size((1, 6, 768)							)
    self.assertEqual(output.shape							,   __lowerCAmelCase							)

    a						=		torch.tensor(
        [[[-0.4_5_3_2, -0.0_9_3_6, 0.5_1_3_7], [-0.2_6_7_6, 0.0_6_2_8, 0.6_1_8_6], [-0.3_6_2_9, -0.1_7_2_6, 0.4_7_1_6]]]							)

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




   @slow
   def 		A							(      self			:       List[str]							)       ->				int:


    """simple docstring"""






    a						=		"the [MASK] of Belgium is Brussels"

    a						=		AutoTokenizer.from_pretrained("uw-madison/nystromformer-512"							)
    a						=		NystromformerForMaskedLM.from_pretrained("uw-madison/nystromformer-512"							)

    a						=		tokenizer(__lowerCAmelCase							,   return_tensors="pt"							)

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

    a						=		token_logits[:, 2, :].argmax(-1							)[0]

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






def 	UpperCAmelCase__      (      UpperCAmelCase__ :Any					):






 '''simple docstring'''

 if not head:
  return True
 # split the list to two parts
 a		,  a						=		head.next, head
 while fast and fast.next:
  a						=		fast.next.next
  a						=		slow.next
 a						=		slow.next
 a						=		None  # Don't forget here! But forget still works!
 # reverse the second part
 a						=		None
 while second:
  a						=		second.next
  a						=		node
  a						=		second
  a						=		nxt
 # compare two parts
 # second part has the same or one less node
 while node:
  if node.val != head.val:
   return False
  a						=		node.next
  a						=		head.next
 return True


def 	UpperCAmelCase__      (      UpperCAmelCase__ :str					):






 '''simple docstring'''

 if not head or not head.next:
  return True

 # 1. Get the midpoint (slow)
 a						=		a						=		a						=		head
 while fast and fast.next:
  a		,  a						=		fast.next.next, slow.next

 # 2. Push the second half into the stack
 a						=		[slow.val]
 while slow.next:
  a						=		slow.next
  stack.append(slow.val					)

 # 3. Comparison
 while stack:
  if stack.pop() != cur.val:
   return False
  a						=		cur.next

 return True




def 	UpperCAmelCase__      (      UpperCAmelCase__ :Any					):






 '''simple docstring'''

 if not head or not head.next:
  return True
 a						=		{}
 a						=		0
 while head:
  if head.val in d:
   d[head.val].append(UpperCAmelCase__					)
  else:
   a						=		[pos]
  a						=		head.next
  pos += 1
 a						=		pos - 1
 a						=		0
 for v in d.values():
  if len(UpperCAmelCase__					) % 2 != 0:
   middle += 1
  else:
   a						=		0
   for i in range(0 ,					len(UpperCAmelCase__					)					):
    if v[i] + v[len(UpperCAmelCase__					) - 1 - step] != checksum:
     return False
    step += 1
  if middle > 1:
   return False
 return True

