





from typing import Any, Dict, List, Mapping

import numpy as np
import torch

from ...utils import is_cython_available, requires_backends


if is_cython_available():
    import pyximport

    pyximport.install(setup_args={"""include_dirs""": np.get_include()})
    from . import algos_graphormer  # noqa E402
def  __UpperCamelCase    (						snake_case							,			snake_case = 5_1_2      )    ->		Optional[Any]:


   '''simple docstring'''







   __A    =  x.shape[1] if len(x.shape      ) > 1 else 1
   __A    =  1 + np.arange(0							,			feature_num * offset							,			snake_case							,			dtype=np.intaa      )
   __A    =  x + feature_offset
   return x
def  __UpperCamelCase    (						snake_case							,			snake_case=True      )    ->		Union[str, Any]:


   '''simple docstring'''







   requires_backends(snake_case							,			['''cython''']      )

   if keep_features and "edge_attr" in item.keys():  # edge_attr
      __A    =  np.asarray(item['''edge_attr''']							,			dtype=np.intaa      )
   else:
      __A    =  np.ones((len(item['''edge_index'''][0]      ), 1)							,			dtype=np.intaa      )  # same embedding for all

   if keep_features and "node_feat" in item.keys():  # input_nodes
      __A    =  np.asarray(item['''node_feat''']							,			dtype=np.intaa      )
   else:
      __A    =  np.ones((item['''num_nodes'''], 1)							,			dtype=np.intaa      )  # same embedding for all

   __A    =  np.asarray(item['''edge_index''']							,			dtype=np.intaa      )

   __A    =  convert_to_single_emb(snake_case      ) + 1
   __A    =  item['''num_nodes''']

   if len(edge_attr.shape      ) == 1:
      __A    =  edge_attr[:, None]
   __A    =  np.zeros([num_nodes, num_nodes, edge_attr.shape[-1]]							,			dtype=np.intaa      )
   __A    =  convert_to_single_emb(snake_case      ) + 1

   # node adj matrix [num_nodes, num_nodes] bool
   __A    =  np.zeros([num_nodes, num_nodes]							,			dtype=snake_case      )
   __A    =  True

   __A   ,		__A    =  algos_graphormer.floyd_warshall(snake_case      )
   __A    =  np.amax(snake_case      )

   __A    =  algos_graphormer.gen_edge_input(snake_case							,			snake_case							,			snake_case      )
   __A    =  np.zeros([num_nodes + 1, num_nodes + 1]							,			dtype=np.single      )  # with graph token

   # combine
   __A    =  input_nodes + 1  # we shift all indices by one for padding
   __A    =  attn_bias
   __A    =  attn_edge_type
   __A    =  shortest_path_result.astype(np.intaa      ) + 1  # we shift all indices by one for padding
   __A    =  np.sum(snake_case							,			axis=1      ).reshape(-1      ) + 1  # we shift all indices by one for padding
   __A    =  item['''in_degree''']  # for undirected graph
   __A    =  input_edges + 1  # we shift all indices by one for padding
   if "labels" not in item:
      __A    =  item['''y''']

   return item







class 		_lowerCAmelCase:

  """simple docstring"""







  def __init__(   self    ,							UpperCAmelCase=20    ,							UpperCAmelCase=False      )->   Dict:
     if not is_cython_available():
        raise ImportError('''Graphormer preprocessing needs Cython (pyximport)'''      )

     __A    =  spatial_pos_max
     __A    =  on_the_fly_processing





  def __call__(   self    ,							UpperCAmelCase      )->   Dict[str, Any]:
     if self.on_the_fly_processing:
        __A    =  [preprocess_item(UpperCAmelCase      ) for i in features]

     if not isinstance(features[0]    ,							UpperCAmelCase      ):
        __A    =  [vars(UpperCAmelCase      ) for f in features]
     __A    =  {}

     __A    =  max(len(i['''input_nodes''']      ) for i in features      )
     __A    =  len(features[0]['''input_nodes'''][0]      )
     __A    =  len(features[0]['''attn_edge_type'''][0][0]      )
     __A    =  max(len(i['''input_edges'''][0][0]      ) for i in features      )
     __A    =  len(features[0]['''input_edges'''][0][0][0]      )
     __A    =  len(UpperCAmelCase      )

     __A    =  torch.zeros(UpperCAmelCase    ,							max_node_num + 1    ,							max_node_num + 1    ,							dtype=torch.float      )
     __A    =  torch.zeros(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							dtype=torch.long      )
     __A    =  torch.zeros(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							dtype=torch.long      )
     __A    =  torch.zeros(UpperCAmelCase    ,							UpperCAmelCase    ,							dtype=torch.long      )
     __A    =  torch.zeros(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							dtype=torch.long      )
     __A    =  torch.zeros(
         UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							dtype=torch.long      )

     for ix, f in enumerate(UpperCAmelCase      ):
        for k in ["attn_bias", "attn_edge_type", "spatial_pos", "in_degree", "input_nodes", "input_edges"]:
           __A    =  torch.tensor(f[k]      )

        if len(f['''attn_bias'''][1:, 1:][f['''spatial_pos'''] >= self.spatial_pos_max]      ) > 0:
           __A    =  float('''-inf'''      )

        __A    =  f['''attn_bias''']
        __A    =  f[
            '''attn_edge_type'''
        ]
        __A    =  f['''spatial_pos''']
        __A    =  f['''in_degree''']
        __A    =  f['''input_nodes''']
        __A    =  f['''input_edges''']

     __A    =  batch['''in_degree''']

     __A    =  features[0]['''labels''']
     if len(UpperCAmelCase      ) == 1:  # one task
        if isinstance(sample[0]    ,							UpperCAmelCase      ):  # regression
           __A    =  torch.from_numpy(np.concatenate([i['''labels'''] for i in features]      )      )
        else:  # binary classification
           __A    =  torch.from_numpy(np.concatenate([i['''labels'''] for i in features]      )      )
     else:  # multi task classification, left to float to keep the NaNs
        __A    =  torch.from_numpy(np.stack([i['''labels'''] for i in features]    ,							axis=0      )      )

     return batch








from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFXLMForMultipleChoice,
        TFXLMForQuestionAnsweringSimple,
        TFXLMForSequenceClassification,
        TFXLMForTokenClassification,
        TFXLMModel,
        TFXLMWithLMHeadModel,
        XLMConfig,
    )







class 		_lowerCAmelCase:

  """simple docstring"""







  def __init__(   self    ,							UpperCAmelCase    ,							)->   List[Any]:
     __A    =  parent
     __A    =  13
     __A    =  7
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  True
     __A    =  False
     __A    =  False
     __A    =  False
     __A    =  2
     __A    =  99
     __A    =  0
     __A    =  32
     __A    =  2
     __A    =  4
     __A    =  0.1
     __A    =  0.1
     __A    =  5_12
     __A    =  16
     __A    =  2
     __A    =  0.02
     __A    =  3
     __A    =  4
     __A    =  '''last'''
     __A    =  True
     __A    =  None
     __A    =  0

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  ids_tensor([self.batch_size, self.seq_length]    ,							self.vocab_size      )
     __A    =  random_attention_mask([self.batch_size, self.seq_length]    ,							dtype=tf.floataa      )

     __A    =  None
     if self.use_input_lengths:
        __A    =  (
            ids_tensor([self.batch_size]    ,							vocab_size=2      ) + self.seq_length - 2
        )  # small variation of seq_length

     __A    =  None
     if self.use_token_type_ids:
        __A    =  ids_tensor([self.batch_size, self.seq_length]    ,							self.n_langs      )

     __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]    ,							2    ,							dtype=tf.floataa      )
        __A    =  ids_tensor([self.batch_size]    ,							self.num_choices      )

     __A    =  XLMConfig(
         vocab_size=self.vocab_size    ,							n_special=self.n_special    ,							emb_dim=self.hidden_size    ,							n_layers=self.num_hidden_layers    ,							n_heads=self.num_attention_heads    ,							dropout=self.hidden_dropout_prob    ,							attention_dropout=self.attention_probs_dropout_prob    ,							gelu_activation=self.gelu_activation    ,							sinusoidal_embeddings=self.sinusoidal_embeddings    ,							asm=self.asm    ,							causal=self.causal    ,							n_langs=self.n_langs    ,							max_position_embeddings=self.max_position_embeddings    ,							initializer_range=self.initializer_range    ,							summary_type=self.summary_type    ,							use_proj=self.use_proj    ,							bos_token_id=self.bos_token_id    ,							)

     return (
         config,
         input_ids,
         token_type_ids,
         input_lengths,
         sequence_labels,
         token_labels,
         is_impossible_labels,
         choice_labels,
         input_mask,
     )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Optional[Any]:
     __A    =  TFXLMModel(config=UpperCAmelCase      )
     __A    =  {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
     __A    =  model(UpperCAmelCase      )

     __A    =  [input_ids, input_mask]
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(result.last_hidden_state.shape    ,							(self.batch_size, self.seq_length, self.hidden_size)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Tuple:
     __A    =  TFXLMWithLMHeadModel(UpperCAmelCase      )

     __A    =  {'''input_ids''': input_ids, '''lengths''': input_lengths, '''langs''': token_type_ids}
     __A    =  model(UpperCAmelCase      )

     __A    =  outputs

     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.vocab_size)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Dict:
     __A    =  TFXLMForQuestionAnsweringSimple(UpperCAmelCase      )

     __A    =  {'''input_ids''': input_ids, '''lengths''': input_lengths}

     __A    =  model(UpperCAmelCase      )

     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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Union[str, Any]:
     __A    =  TFXLMForSequenceClassification(UpperCAmelCase      )

     __A    =  {'''input_ids''': input_ids, '''lengths''': input_lengths}

     __A    =  model(UpperCAmelCase      )

     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.type_sequence_label_size)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Tuple:
     __A    =  self.num_labels
     __A    =  TFXLMForTokenClassification(config=UpperCAmelCase      )
     __A    =  {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.seq_length, self.num_labels)      )

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							)->   Union[str, Any]:
     __A    =  self.num_choices
     __A    =  TFXLMForMultipleChoice(config=UpperCAmelCase      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  tf.tile(tf.expand_dims(UpperCAmelCase    ,							1      )    ,							(1, self.num_choices, 1)      )
     __A    =  {
         '''input_ids''': multiple_choice_inputs_ids,
         '''attention_mask''': multiple_choice_input_mask,
         '''token_type_ids''': multiple_choice_token_type_ids,
     }
     __A    =  model(UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_choices)      )





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  self.prepare_config_and_inputs()
     (
         (
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		(
         __A
     )   ,		
     )    =  config_and_inputs
     __A    =  {
         '''input_ids''': input_ids,
         '''token_type_ids''': token_type_ids,
         '''langs''': token_type_ids,
         '''lengths''': input_lengths,
     }
     return config, inputs_dict







@require_tf
class 		_lowerCAmelCase(		_a						,       _a						,       unittest.TestCase):

  """simple docstring"""







  lowerCamelCase__     	=       (
      (
          TFXLMModel,
          TFXLMWithLMHeadModel,
          TFXLMForSequenceClassification,
          TFXLMForQuestionAnsweringSimple,
          TFXLMForTokenClassification,
          TFXLMForMultipleChoice,
      )
      if is_tf_available()
      else ()
  )
  lowerCamelCase__     	=       (
      (TFXLMWithLMHeadModel,) if is_tf_available() else ()
  )  # TODO (PVP): Check other models whether language generation is also applicable
  lowerCamelCase__     	=       (
      {
          '''feature-extraction''': TFXLMModel,
          '''fill-mask''': TFXLMWithLMHeadModel,
          '''question-answering''': TFXLMForQuestionAnsweringSimple,
          '''text-classification''': TFXLMForSequenceClassification,
          '''text-generation''': TFXLMWithLMHeadModel,
          '''token-classification''': TFXLMForTokenClassification,
          '''zero-shot''': TFXLMForSequenceClassification,
      }
      if is_tf_available()
      else {}
  )
  lowerCamelCase__     	=       False
  lowerCamelCase__     	=       False

  def 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   List[Any]:
     if (
         pipeline_test_casse_name == "QAPipelineTests"
         and tokenizer_name is not None
         and not tokenizer_name.endswith('''Fast'''      )
     ):
        # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
        # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
        # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
        return True

     return False

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  TFXLMModelTester(self      )
     __A    =  ConfigTester(self    ,							config_class=UpperCAmelCase    ,							emb_dim=37      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     self.config_tester.run_common_tests()

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_model(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_lm_head(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[Any]:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_qa(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Any:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_sequence_classif(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Tuple:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_for_token_classification(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_xlm_for_multiple_choice(*UpperCAmelCase      )





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     for model_name in TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __A    =  TFXLMModel.from_pretrained(UpperCAmelCase      )
        self.assertIsNotNone(UpperCAmelCase      )







@require_tf
class 		_lowerCAmelCase(		unittest.TestCase):

  """simple docstring"""







  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  TFXLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048'''      )
     __A    =  tf.convert_to_tensor([[14, 4_47]]    ,							dtype=tf.intaa      )  # the president
     __A    =  [
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
         14,
         4_47,
     ]  # the president the president the president the president the president the president the president the president the president the president
     # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference
     __A    =  model.generate(UpperCAmelCase    ,							do_sample=UpperCAmelCase      )
     self.assertListEqual(output_ids[0].numpy().tolist()    ,							UpperCAmelCase      )

