


'''simple docstring'''




from __future__ import annotations

import unittest

from transformers import MPNetConfig, 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.models.mpnet.modeling_tf_mpnet import (
       TFMPNetForMaskedLM,
       TFMPNetForMultipleChoice,
       TFMPNetForQuestionAnswering,
       TFMPNetForSequenceClassification,
       TFMPNetForTokenClassification,
       TFMPNetModel,
   )




class  _lowercase   :
   def __init__(	self					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			List[str]=13					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=7					,      SCREAMING_SNAKE_CASE_					:			Any=True					,      SCREAMING_SNAKE_CASE_					:			Tuple=True					,      SCREAMING_SNAKE_CASE_					:			Any=False					,      SCREAMING_SNAKE_CASE_					:			List[str]=True					,      SCREAMING_SNAKE_CASE_					:			int=99					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=64					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=2					,      SCREAMING_SNAKE_CASE_					:			str=4					,      SCREAMING_SNAKE_CASE_					:			List[Any]=64					,      SCREAMING_SNAKE_CASE_					:			Optional[int]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Any=0.1					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=0.1					,      SCREAMING_SNAKE_CASE_					:			Any=512					,      SCREAMING_SNAKE_CASE_					:			Dict=16					,      SCREAMING_SNAKE_CASE_					:			List[str]=2					,      SCREAMING_SNAKE_CASE_					:			List[str]=0.0_2					,      SCREAMING_SNAKE_CASE_					:			Dict=3					,      SCREAMING_SNAKE_CASE_					:			Dict=4					,      SCREAMING_SNAKE_CASE_					:			List[Any]=None					,      )   ->       Dict:
        __snake_case    			=	parent
        __snake_case    			=	batch_size
        __snake_case    			=	seq_length
        __snake_case    			=	is_training
        __snake_case    			=	use_input_mask
        __snake_case    			=	use_token_type_ids
        __snake_case    			=	use_labels
        __snake_case    			=	vocab_size
        __snake_case    			=	hidden_size
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	intermediate_size
        __snake_case    			=	hidden_act
        __snake_case    			=	hidden_dropout_prob
        __snake_case    			=	attention_probs_dropout_prob
        __snake_case    			=	max_position_embeddings
        __snake_case    			=	type_vocab_size
        __snake_case    			=	type_sequence_label_size
        __snake_case    			=	initializer_range
        __snake_case    			=	num_labels
        __snake_case    			=	num_choices
        __snake_case    			=	scope
   def a     (	self					:			Any			)   ->       Optional[Any]:
        __snake_case    			=	ids_tensor([self.batch_size, self.seq_length]					,      self.vocab_size			)

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

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

        __snake_case    			=	MPNetConfig(
            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					,      initializer_range=self.initializer_range					,      )
        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
   def a     (	self					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			int					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			int			)   ->       Dict:
        __snake_case    			=	TFMPNetModel(config=lowercase_			)
        __snake_case    			=	{'input_ids': input_ids, 'attention_mask': input_mask}
        __snake_case    			=	model(lowercase_			)
        __snake_case    			=	[input_ids, input_mask]
        __snake_case    			=	model(lowercase_			)
        self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)			)
   def a     (	self					:			Dict					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			int					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]			)   ->       Optional[Any]:
        __snake_case    			=	TFMPNetForMaskedLM(config=lowercase_			)
        __snake_case    			=	{'input_ids': input_ids, 'attention_mask': input_mask}
        __snake_case    			=	model(lowercase_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.vocab_size)			)
   def a     (	self					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			Dict			)   ->       List[Any]:
        __snake_case    			=	TFMPNetForQuestionAnswering(config=lowercase_			)
        __snake_case    			=	{
            'input_ids': input_ids,
            'attention_mask': input_mask,
        }
        __snake_case    			=	model(lowercase_			)
        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[Any]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			List[str]			)   ->       str:
        __snake_case    			=	self.num_labels
        __snake_case    			=	TFMPNetForSequenceClassification(lowercase_			)
        __snake_case    			=	{'input_ids': input_ids, 'attention_mask': input_mask}
        __snake_case    			=	model(lowercase_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)			)
   def a     (	self					:			int					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			List[str]			)   ->       Optional[Any]:
        __snake_case    			=	self.num_choices
        __snake_case    			=	TFMPNetForMultipleChoice(lowercase_			)
        __snake_case    			=	tf.tile(tf.expand_dims(lowercase_					,      1			)					,      (1, self.num_choices, 1)			)
        __snake_case    			=	tf.tile(tf.expand_dims(lowercase_					,      1			)					,      (1, self.num_choices, 1)			)
        __snake_case    			=	{
            'input_ids': multiple_choice_inputs_ids,
            'attention_mask': multiple_choice_input_mask,
        }
        __snake_case    			=	model(lowercase_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_choices)			)
   def a     (	self					:			str					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			int					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			int			)   ->       List[Any]:
        __snake_case    			=	self.num_labels
        __snake_case    			=	TFMPNetForTokenClassification(lowercase_			)
        __snake_case    			=	{'input_ids': input_ids, 'attention_mask': input_mask}
        __snake_case    			=	model(lowercase_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.seq_length, self.num_labels)			)





   def a     (	self					:			Any			)   ->       int:
        __snake_case    			=	self.prepare_config_and_inputs()
        ((__snake_case)			,					(__snake_case)			,					(__snake_case)			,					(__snake_case)			,					(__snake_case)			,					(__snake_case))    			=	config_and_inputs
        __snake_case    			=	{'input_ids': input_ids, 'attention_mask': input_mask}
        return config, inputs_dict




@require_tf
class  _lowercase   (  lowerCamelCase__	,				lowerCamelCase__	,				unittest.TestCase       ):
   _SCREAMING_SNAKE_CASE     :     Any									=  (
       (
           TFMPNetForMaskedLM,
           TFMPNetForMultipleChoice,
           TFMPNetForQuestionAnswering,
           TFMPNetForSequenceClassification,
           TFMPNetForTokenClassification,
           TFMPNetModel,
       )
       if is_tf_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE     :     str									=  (
       {
           'feature-extraction': TFMPNetModel,
           'fill-mask': TFMPNetForMaskedLM,
           'question-answering': TFMPNetForQuestionAnswering,
           'text-classification': TFMPNetForSequenceClassification,
           'token-classification': TFMPNetForTokenClassification,
           'zero-shot': TFMPNetForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   _SCREAMING_SNAKE_CASE     :     List[str]									=  False
   _SCREAMING_SNAKE_CASE     :     Dict									=  False
   def a     (	self					:			List[str]			)   ->       Any:
        __snake_case    			=	TFMPNetModelTester(self			)
        __snake_case    			=	ConfigTester(self					,      config_class=lowercase_					,      hidden_size=37			)
   def a     (	self					:			Any			)   ->       int:
        self.config_tester.run_common_tests()
   def a     (	self					:			Any			)   ->       Tuple:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_model(*lowercase_			)
   def a     (	self					:			Tuple			)   ->       Any:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_masked_lm(*lowercase_			)
   def a     (	self					:			Dict			)   ->       Tuple:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase_			)
   def a     (	self					:			Dict			)   ->       Union[str, Any]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase_			)
   def a     (	self					:			str			)   ->       List[str]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase_			)
   def a     (	self					:			Optional[int]			)   ->       List[Any]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase_			)





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






        for model_name in ["microsoft/mpnet-base"]:
             __snake_case    			=	TFMPNetModel.from_pretrained(lowercase_			)
             self.assertIsNotNone(lowercase_			)




@require_tf
class  _lowercase   (  unittest.TestCase       ):
   @slow
   def a     (	self					:			List[Any]			)   ->       str:
        __snake_case    			=	TFMPNetModel.from_pretrained('microsoft/mpnet-base'			)
        __snake_case    			=	tf.constant([[0, 1, 2, 3, 4, 5]]			)
        __snake_case    			=	model(lowercase_			)[0]

        __snake_case    			=	[1, 6, 768]
        self.assertEqual(output.shape					,      lowercase_			)

        __snake_case    			=	tf.constant(
            [
                [
                    [-0.1_0_6_7_1_7_2, 0.0_8_2_1_6_4_7_3, 0.0_0_2_4_5_4_3],
                    [-0.0_3_4_6_5_8_7_9, 0.8_3_5_4_1_1_8, -0.0_3_2_5_2_2_8_8],
                    [-0.0_6_5_6_9_4_7_6, -0.1_2_4_2_4_1_1_1, -0.0_4_9_4_4_3_6],
                ]
            ]			)
        tf.debugging.assert_near(output[:, :3, :3]					,      lowercase_					,      atol=1e-4			)








'''simple docstring'''




from functools import partial
from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload

import torch
import torch.nn as nn
import torch.types





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      torch.Tensor       ,      lowercase__ :      bool	) -> torch.Tensor:






     """simple docstring"""
     # The first operation in a checkpoint can't be in-place, but it's
     # nice to have in-place addition during inference. Thus...
     if not inplace:
          __snake_case    			=	ma + ma
     else:
          ma += ma

     return ma





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      List[int]	) -> torch.Tensor:






     """simple docstring"""
     __snake_case    			=	-1 * len(lowercase__	)
     __snake_case    			=	list(range(len(tensor.shape[:zero_index]	)	)	)
     return tensor.permute(first_inds + [zero_index + i for i in inds]	)





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      int	) -> torch.Tensor:






     """simple docstring"""
     return t.reshape(t.shape[:-no_dims] + (-1,)	)





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      torch.Tensor       ,      lowercase__ :      int       ,      lowercase__ :      float = 1e-4	) -> torch.Tensor:






     """simple docstring"""
     __snake_case    			=	mask.expand(*value.shape	)
     return torch.sum(mask * value       ,      dim=lowercase__	) / (eps + torch.sum(lowercase__       ,      dim=lowercase__	))





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      torch.types.Number = 2.31_25       ,      lowercase__ :      torch.types.Number = 21.68_75       ,      lowercase__ :      int = 6_4	) -> torch.Tensor:






     """simple docstring"""
     __snake_case    			=	torch.linspace(lowercase__       ,      lowercase__       ,      no_bins - 1       ,      device=pts.device	)
     __snake_case    			=	torch.sqrt(torch.sum((pts.unsqueeze(-2	) - pts.unsqueeze(-3	)) ** 2       ,      dim=-1	)	)
     return torch.bucketize(lowercase__       ,      lowercase__	)





def      _a		(lowercase__ :      Callable[[list], Any]       ,      lowercase__ :      List[dict]	) -> dict:






     """simple docstring"""
     __snake_case    			=	dicts[0]
     __snake_case    			=	{}
     for k, v in first.items():
          __snake_case    			=	[d[k] for d in dicts]
          if isinstance(lowercase__       ,      lowercase__	):
               __snake_case    			=	dict_multimap(lowercase__       ,      lowercase__	)
          else:
               __snake_case    			=	fn(lowercase__	)

     return new_dict





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      torch.Tensor	) -> torch.Tensor:






     """simple docstring"""
     __snake_case    			=	v_bins.view(((1,) * len(x.shape	)) + (len(lowercase__	),)	)
     __snake_case    			=	x[..., None] - reshaped_bins
     __snake_case    			=	torch.argmin(torch.abs(lowercase__	)       ,      dim=-1	)
     return nn.functional.one_hot(lowercase__       ,      num_classes=len(lowercase__	)	).float()





def      _a		(lowercase__ :      torch.Tensor       ,      lowercase__ :      torch.Tensor       ,      lowercase__ :      int = 0       ,      lowercase__ :      int = 0	) -> torch.Tensor:






     """simple docstring"""
     __snake_case    			=	[]
     for i, s in enumerate(data.shape[:no_batch_dims]	):
          __snake_case    			=	torch.arange(lowercase__	)
          __snake_case    			=	r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape	) - i - 1)))	)
          ranges.append(lowercase__	)

     __snake_case    			=	[slice(lowercase__	) for _ in range(len(data.shape	) - no_batch_dims	)]
     __snake_case    			=	inds
     ranges.extend(lowercase__	)
     # Matt note: Editing this to get around the behaviour of using a list as an array index changing
     # in recent Numpy versions
     return data[tuple(lowercase__	)]


_a      :      str       				=      TypeVar("T")





def      _a		(lowercase__ :      Callable[[T], Any]       ,      lowercase__ :      Dict[Any, Union[dict, list, tuple, T]]       ,      lowercase__ :      Type[T]	) -> Dict[Any, Union[dict, list, tuple, Any]]:






     """simple docstring"""
     __snake_case    			=	{}
     for k, v in dic.items():
          if isinstance(lowercase__       ,      lowercase__	):
               __snake_case    			=	dict_map(lowercase__       ,      lowercase__       ,      lowercase__	)
          else:
               __snake_case    			=	tree_map(lowercase__       ,      lowercase__       ,      lowercase__	)

     return new_dict





@overload
def      _a		(lowercase__ :      Callable[[T], Any]       ,      lowercase__ :      T       ,      lowercase__ :      Type[T]	) -> Any:






     """simple docstring"""
     ...





@overload
def      _a		(lowercase__ :      Callable[[T], Any]       ,      lowercase__ :      dict       ,      lowercase__ :      Type[T]	) -> dict:






     """simple docstring"""
     ...





@overload
def      _a		(lowercase__ :      Callable[[T], Any]       ,      lowercase__ :      list       ,      lowercase__ :      Type[T]	) -> list:






     """simple docstring"""
     ...





@overload
def      _a		(lowercase__ :      Callable[[T], Any]       ,      lowercase__ :      tuple       ,      lowercase__ :      Type[T]	) -> tuple:






     """simple docstring"""
     ...





def      _a		(lowercase__ :      str       ,      lowercase__ :      Any       ,      lowercase__ :      Dict	) -> Union[str, Any]:






     """simple docstring"""
     if isinstance(lowercase__       ,      lowercase__	):
          return dict_map(lowercase__       ,      lowercase__       ,      lowercase__	)
     elif isinstance(lowercase__       ,      lowercase__	):
          return [tree_map(lowercase__       ,      lowercase__       ,      lowercase__	) for x in tree]
     elif isinstance(lowercase__       ,      lowercase__	):
          return tuple(tree_map(lowercase__       ,      lowercase__       ,      lowercase__	) for x in tree	)
     elif isinstance(lowercase__       ,      lowercase__	):
          return fn(lowercase__	)
     else:
          print(type(lowercase__	)	)
          raise ValueError('Not supported'	)


_a      :      Union[str, Any]       				=      partial(tree_map, leaf_type=torch.Tensor)




