



import unittest

from transformers import MPNetConfig, 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 (
          MPNetForMaskedLM,
          MPNetForMultipleChoice,
          MPNetForQuestionAnswering,
          MPNetForSequenceClassification,
          MPNetForTokenClassification,
          MPNetModel,
      )

class       _SCREAMING_SNAKE_CASE	:





     def __init__(       self :							Optional[Any]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							int=1_3     ,  UpperCamelCase :							Union[str, Any]=7     ,  UpperCamelCase :							Union[str, Any]=True     ,  UpperCamelCase :							Union[str, Any]=True     ,  UpperCamelCase :							Union[str, Any]=False     ,  UpperCamelCase :							Any=True     ,  UpperCamelCase :							str=9_9     ,  UpperCamelCase :							str=6_4     ,  UpperCamelCase :							List[str]=5     ,  UpperCamelCase :							Any=4     ,  UpperCamelCase :							List[str]=6_4     ,  UpperCamelCase :							str="gelu"     ,  UpperCamelCase :							List[Any]=0.1     ,  UpperCamelCase :							str=0.1     ,  UpperCamelCase :							Union[str, Any]=5_1_2     ,  UpperCamelCase :							Optional[Any]=1_6     ,  UpperCamelCase :							str=2     ,  UpperCamelCase :							List[Any]=0.0_2     ,  UpperCamelCase :							Union[str, Any]=3     ,  UpperCamelCase :							Union[str, Any]=4     ,  UpperCamelCase :							Dict=None     ,  )->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	parent
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	batch_size
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	seq_length
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	is_training
      __SCREAMING_SNAKE_CASE       :    Dict       =	use_input_mask
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	use_token_type_ids
      __SCREAMING_SNAKE_CASE       :    Dict       =	use_labels
      __SCREAMING_SNAKE_CASE       :    List[str]       =	vocab_size
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	hidden_size
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	num_hidden_layers
      __SCREAMING_SNAKE_CASE       :    str       =	num_attention_heads
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	intermediate_size
      __SCREAMING_SNAKE_CASE       :    int       =	hidden_act
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	hidden_dropout_prob
      __SCREAMING_SNAKE_CASE       :    Tuple       =	attention_probs_dropout_prob
      __SCREAMING_SNAKE_CASE       :    str       =	max_position_embeddings
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	type_vocab_size
      __SCREAMING_SNAKE_CASE       :    Any       =	type_sequence_label_size
      __SCREAMING_SNAKE_CASE       :    Dict       =	initializer_range
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	num_labels
      __SCREAMING_SNAKE_CASE       :    Tuple       =	num_choices
      __SCREAMING_SNAKE_CASE       :    str       =	scope





     def 	__snake_case    (       self :							Union[str, Any]				)->Union[str, Any]:
      return MPNetConfig.from_pretrained("microsoft/mpnet-base"				)





     def 	__snake_case    (       self :							str				)->Tuple:
      __SCREAMING_SNAKE_CASE       :    Any       =	ids_tensor([self.batch_size, self.seq_length]     ,  self.vocab_size				)

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

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

      __SCREAMING_SNAKE_CASE       :    str       =	self.get_config()
      return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels





     def 	__snake_case    (       self :							Optional[Any]				)->Any:
      return 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     ,  )





     def 	__snake_case    (       self :							Tuple     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							int     ,  UpperCamelCase :							str     ,  UpperCamelCase :							Tuple     ,  UpperCamelCase :							str     ,  UpperCamelCase :							Optional[int]				)->Any:
      __SCREAMING_SNAKE_CASE       :    Any       =	MPNetModel(config=UpperCamelCase				)
      model.to(UpperCamelCase				)
      model.eval()
      __SCREAMING_SNAKE_CASE       :    Any       =	model(UpperCamelCase     ,  UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	model(UpperCamelCase				)
      self.parent.assertEqual(result.last_hidden_state.shape     ,  (self.batch_size, self.seq_length, self.hidden_size)				)
      self.parent.assertEqual(result.pooler_output.shape     ,  (self.batch_size, self.hidden_size)				)





     def 	__snake_case    (       self :							Any     ,  UpperCamelCase :							Tuple     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							Tuple     ,  UpperCamelCase :							Union[str, Any]     ,  UpperCamelCase :							List[str]     ,  UpperCamelCase :							List[str]				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Any       =	MPNetForQuestionAnswering(config=UpperCamelCase				)
      model.to(UpperCamelCase				)
      model.eval()
      __SCREAMING_SNAKE_CASE       :    str       =	model(
          UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  start_positions=UpperCamelCase     ,  end_positions=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 	__snake_case    (       self :							List[Any]     ,  UpperCamelCase :							Optional[Any]     ,  UpperCamelCase :							Any     ,  UpperCamelCase :							List[str]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							Union[str, Any]     ,  UpperCamelCase :							List[Any]				)->List[str]:
      __SCREAMING_SNAKE_CASE       :    Dict       =	self.num_labels
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	MPNetForSequenceClassification(UpperCamelCase				)
      model.to(UpperCamelCase				)
      model.eval()
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	model(UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  labels=UpperCamelCase				)
      self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_labels)				)





     def 	__snake_case    (       self :							Any     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							str     ,  UpperCamelCase :							List[str]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							Union[str, Any]     ,  UpperCamelCase :							List[str]				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.num_choices
      __SCREAMING_SNAKE_CASE       :    Tuple       =	MPNetForMultipleChoice(config=UpperCamelCase				)
      model.to(UpperCamelCase				)
      model.eval()
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	input_ids.unsqueeze(1				).expand(-1     ,  self.num_choices     ,  -1				).contiguous()
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	input_mask.unsqueeze(1				).expand(-1     ,  self.num_choices     ,  -1				).contiguous()
      __SCREAMING_SNAKE_CASE       :    str       =	model(
          UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  labels=UpperCamelCase     ,  )
      self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_choices)				)





     def 	__snake_case    (       self :							int     ,  UpperCamelCase :							Any     ,  UpperCamelCase :							List[str]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							int     ,  UpperCamelCase :							str				)->str:
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.num_labels
      __SCREAMING_SNAKE_CASE       :    int       =	MPNetForTokenClassification(config=UpperCamelCase				)
      model.to(UpperCamelCase				)
      model.eval()
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	model(UpperCamelCase     ,  attention_mask=UpperCamelCase     ,  labels=UpperCamelCase				)
      self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.seq_length, self.num_labels)				)






     def 	__snake_case    (       self :							Optional[int]				)->str:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.prepare_config_and_inputs()
      ((__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE),		(__SCREAMING_SNAKE_CASE))       :    Dict       =	config_and_inputs
      __SCREAMING_SNAKE_CASE       :    str       =	{"input_ids": input_ids, "attention_mask": input_mask}
      return config, inputs_dict






@require_torch
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			(
         (
             MPNetForMaskedLM,
             MPNetForMultipleChoice,
             MPNetForQuestionAnswering,
             MPNetForSequenceClassification,
             MPNetForTokenClassification,
             MPNetModel,
         )
         if is_torch_available()
         else ()
     )
     lowerCAmelCase					=			(
         {
             """feature-extraction""": MPNetModel,
             """fill-mask""": MPNetForMaskedLM,
             """question-answering""": MPNetForQuestionAnswering,
             """text-classification""": MPNetForSequenceClassification,
             """token-classification""": MPNetForTokenClassification,
             """zero-shot""": MPNetForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     lowerCAmelCase					=			False
     lowerCAmelCase					=			True





     def 	__snake_case    (       self :							Tuple				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    str       =	MPNetModelTester(self				)
      __SCREAMING_SNAKE_CASE       :    Any       =	ConfigTester(self     ,  config_class=UpperCamelCase     ,  hidden_size=3_7				)





     def 	__snake_case    (       self :							Optional[int]				)->List[str]:
      self.config_tester.run_common_tests()





     def 	__snake_case    (       self :							str				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_model(*UpperCamelCase				)





     def 	__snake_case    (       self :							Union[str, Any]				)->int:
      __SCREAMING_SNAKE_CASE       :    str       =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_sequence_classification(*UpperCamelCase				)





     def 	__snake_case    (       self :							Dict				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_multiple_choice(*UpperCamelCase				)





     def 	__snake_case    (       self :							List[Any]				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Dict       =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_token_classification(*UpperCamelCase				)






     def 	__snake_case    (       self :							Union[str, Any]				)->Any:
      __SCREAMING_SNAKE_CASE       :    Any       =	self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_mpnet_for_question_answering(*UpperCamelCase				)






@require_torch
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     @slow
     def 	__snake_case    (       self :							Optional[Any]				)->str:
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	MPNetModel.from_pretrained("microsoft/mpnet-base"				)
      __SCREAMING_SNAKE_CASE       :    int       =	torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]				)
      __SCREAMING_SNAKE_CASE       :    Any       =	model(UpperCamelCase				)[0]
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	torch.Size((1, 1_1, 7_6_8)				)
      self.assertEqual(output.shape     ,  UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Tuple       =	torch.tensor(
          [[[-0.0_5_5_0, 0.1_9_4_3, -0.0_7_4_0], [-0.0_5_6_2, 0.2_2_1_1, -0.0_5_7_9], [-0.0_4_3_7, 0.3_3_3_7, -0.0_6_4_1]]]				)
      # compare the actual values for a slice.
      self.assertTrue(torch.allclose(output[:, :3, :3]     ,  UpperCamelCase     ,  atol=1E-4				)				)











from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
      from .deepspeed import (
          DeepSpeedEngineWrapper,
          DeepSpeedOptimizerWrapper,
          DeepSpeedSchedulerWrapper,
          DummyOptim,
          DummyScheduler,
          HfDeepSpeedConfig,
      )

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers






