


"""simple docstring"""





import argparse
import gc
import os
import sys
from pathlib import Path
from typing import List  # noqa: F401

import pytorch_lightning as pl
import torch
from finetune import SummarizationModule, TranslationModule
from finetune import main as ft_main
from make_student import create_student_by_copying_alternating_layers, get_layers_to_supervise
from torch import nn

from transformers import AutoModelForSeqaSeqLM, MBartTokenizer, TaForConditionalGeneration
from transformers.models.bart.modeling_bart import shift_tokens_right
from utils import calculate_bleu, check_output_dir, freeze_params, label_smoothed_nll_loss, use_task_specific_params


# need the parent dir module
sys.path.insert(2, str(Path(__file__).resolve().parents[1]))
from lightning_base import generic_train  # noqa



class 		snake_case_(							a__      ):
     __UpperCamelCase	=       ['''loss''', '''ce_loss''', '''mlm_loss''', '''hid_loss_enc''', '''hid_loss_dec''']






     def __init__(						self	:       int       ,					UpperCamelCase_	:       Optional[Any]					):
           assert Path(hparams.data_dir					).exists()
           lowerCAmelCase       :						Tuple							= Path(hparams.output_dir					)
           self.output_dir.mkdir(exist_ok=UpperCamelCase_					)

           lowerCAmelCase       :						str							= self.output_dir.joinpath('''student'''					)

           lowerCAmelCase       :						str							= str(UpperCamelCase_					)  # Tell lightning we are training the student
           lowerCAmelCase       :						Tuple							= AutoModelForSeqaSeqLM.from_pretrained(hparams.teacher					).eval()
           use_task_specific_params(UpperCamelCase_       ,					hparams.task					)  # We copy good generation parameters to student by default
           if hparams.student is not None:
                 lowerCAmelCase       :						Optional[Any]							= AutoModelForSeqaSeqLM.from_pretrained(hparams.student					)
                 use_task_specific_params(UpperCamelCase_       ,					hparams.task					)
                 lowerCAmelCase,   lowerCAmelCase       :						Tuple							= None, None
           else:
                 lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase       :						List[Any]							= create_student_by_copying_alternating_layers(
                     UpperCamelCase_       ,					e=hparams.student_encoder_layers       ,					d=hparams.student_decoder_layers       ,					save_path=UpperCamelCase_					)

           if hparams.length_penalty != -1:
                 lowerCAmelCase       :						List[Any]							= hparams.length_penalty
           lowerCAmelCase       :						Union[str, Any]							= hparams.teacher  # Use teacher's tokenizer
           super().__init__(UpperCamelCase_       ,					model=UpperCamelCase_       ,					config=student.config					)
           assert student.config.model_type == teacher.config.model_type, (
               F'''teacher, student model types should be the same, got {student.config.model_type} !='''
               F''' {teacher.config.model_type}'''
           )

           if student.config.model_type == "t5":
                 lowerCAmelCase       :						Union[str, Any]							= len(student.get_encoder().block					)
                 lowerCAmelCase       :						Optional[Any]							= len(student.get_decoder().block					)
                 lowerCAmelCase       :						Dict							= len(teacher.get_encoder().block					)
                 lowerCAmelCase       :						List[Any]							= len(teacher.get_decoder().block					)
           else:
                 lowerCAmelCase       :						int							= student.config.encoder_layers
                 lowerCAmelCase       :						List[Any]							= student.config.decoder_layers
                 lowerCAmelCase       :						Union[str, Any]							= teacher.config.encoder_layers
                 lowerCAmelCase       :						Optional[int]							= teacher.config.decoder_layers

           lowerCAmelCase       :						str							= not (hparams.student is None or hparams.teacher == hparams.student)
           lowerCAmelCase       :						Dict							= (not self.different_base_models) and hparams.alpha_hid > 0
           lowerCAmelCase       :						Optional[int]							= self.different_base_models or (student_encoder_layers != teacher_encoder_layers)
           # self.different_encoder determines whether we need to run the teacher encoder
           lowerCAmelCase       :						Dict							= teacher
           freeze_params(self.teacher					)

           if not self.different_encoder:  # To save RAM, delete teacher encoder and freeze student encoder.
                 try:
                       del self.teacher.model.encoder
                 except AttributeError:  # T5
                       del self.teacher.encoder

           if e_layer_ids is None:
                 lowerCAmelCase       :						int							= list(range(UpperCamelCase_					)					)
           if d_layer_ids is None:
                 lowerCAmelCase       :						str							= list(range(UpperCamelCase_					)					)

           lowerCAmelCase,   lowerCAmelCase       :						Tuple							= e_layer_ids, d_layer_ids  # type: List[int], List[int]

           if self.do_calc_hidden_loss:  # Intermediate supervision: Decide which layers to supervise
                 if hparams.supervise_forward:
                       lowerCAmelCase       :						Dict							= get_layers_to_supervise(
                           n_student=len(self.e_layer_ids					)       ,					n_teacher=UpperCamelCase_					)
                       lowerCAmelCase       :						Any							= get_layers_to_supervise(
                           n_student=len(self.d_layer_ids					)       ,					n_teacher=UpperCamelCase_					)
                 else:  # student layer should emulate hidden states of the teacher layer it was copied from
                       lowerCAmelCase       :						Tuple							= self.e_layer_ids
                       lowerCAmelCase       :						int							= self.d_layer_ids
           else:
                 lowerCAmelCase       :						Dict							= None
                 lowerCAmelCase       :						Tuple							= None

           lowerCAmelCase       :						Union[str, Any]							= nn.KLDivLoss(reduction='''batchmean'''					)
           lowerCAmelCase       :						int							= 2.0
           lowerCAmelCase       :						Any							= hparams.alpha_mlm
           lowerCAmelCase       :						Optional[int]							= hparams.alpha_ce
           lowerCAmelCase       :						Dict							= hparams.alpha_hid
           gc.collect()
           torch.cuda.empty_cache()






     def   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Any					):
           lowerCAmelCase       :						Optional[int]							= mask[:, :, None].expand_as(UpperCamelCase_					)
           lowerCAmelCase       :						List[str]							= s_logits.size(-1					)
           lowerCAmelCase       :						str							= torch.masked_select(UpperCamelCase_       ,					UpperCamelCase_					)  # (bs * seq_length * voc_size) modulo the 1s in mask
           lowerCAmelCase       :						Optional[int]							= torch.masked_select(UpperCamelCase_       ,					UpperCamelCase_					)  # (bs * seq_length * voc_size) modulo the 1s in mask
           lowerCAmelCase       :						int							= s_logits_slct.view(-1       ,					UpperCamelCase_					)  # (bs * seq_length, voc_size) modulo the 1s in mask
           lowerCAmelCase       :						Tuple							= t_logits_slct.view(-1       ,					UpperCamelCase_					)  # (bs * seq_length, voc_size) modulo the 1s in mask
           assert t_logits_slct.size() == s_logits_slct.size()
           lowerCAmelCase       :						Tuple							= (
               self.ce_loss_fct(
                   nn.functional.log_softmax(s_logits_slct / self.temperature       ,					dim=-1					)       ,					nn.functional.softmax(t_logits_slct / self.temperature       ,					dim=-1					)       ,					)
               * (self.temperature) ** 2
           )
           return loss_ce






     @staticmethod
     def   lowerCamelCase__  (						UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       int					):
           SummarizationModule.add_model_specific_args(UpperCamelCase_       ,					UpperCamelCase_					)
           add_distill_args(UpperCamelCase_					)
           return parser






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       dict					):
           lowerCAmelCase       :						int							= self.tokenizer.pad_token_id
           lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase       :						List[str]							= batch['''input_ids'''], batch['''attention_mask'''], batch['''labels''']
           if isinstance(self.model       ,					UpperCamelCase_					):
                 lowerCAmelCase       :						int							= self.model._shift_right(UpperCamelCase_					)
           else:
                 lowerCAmelCase       :						Optional[int]							= shift_tokens_right(UpperCamelCase_       ,					UpperCamelCase_					)

           # noinspection PyCallingNonCallable
           lowerCAmelCase       :						Any							= self(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					decoder_input_ids=UpperCamelCase_       ,					output_hidden_states=self.do_calc_hidden_loss       ,					output_attentions=UpperCamelCase_       ,					use_cache=UpperCamelCase_       ,					)
           lowerCAmelCase       :						Optional[Any]							= student_outputs['''logits''']

           # Same cross entropy vs. label smoothing logic as finetune.py
           assert lm_logits.shape[-1] == self.model.config.vocab_size
           if self.hparams.label_smoothing == 0:
                 # Same behavior as modeling_bart.py, besides ignoring pad_token_id
                 lowerCAmelCase       :						str							= nn.CrossEntropyLoss(ignore_index=UpperCamelCase_					)
                 lowerCAmelCase       :						List[str]							= loss_fct(lm_logits.view(-1       ,					lm_logits.shape[-1]					)       ,					labels.view(-1					)					)
           else:
                 lowerCAmelCase       :						List[str]							= nn.functional.log_softmax(UpperCamelCase_       ,					dim=-1					)
                 lowerCAmelCase,   lowerCAmelCase       :						str							= label_smoothed_nll_loss(
                     UpperCamelCase_       ,					UpperCamelCase_       ,					self.hparams.label_smoothing       ,					ignore_index=UpperCamelCase_					)

           def zero_tensor():
                 return torch.tensor(0.0					).type_as(UpperCamelCase_					)

           lowerCAmelCase       :						Any							= student_outputs[
               '''encoder_last_hidden_state'''
           ]  # use this unless self.different_base_models
           lowerCAmelCase,   lowerCAmelCase       :						List[str]							= zero_tensor(), zero_tensor()
           if self.different_encoder:  # compute encoder hidden state loss
                 lowerCAmelCase       :						Dict							= self.teacher.get_encoder()(
                     UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					output_hidden_states=self.do_calc_hidden_loss       ,					)
                 if self.different_base_models:
                       lowerCAmelCase       :						Union[str, Any]							= all_teacher_encoder_outputs['''last_hidden_state''']
                 elif self.do_calc_hidden_loss:
                       lowerCAmelCase       :						int							= self.calc_hidden_loss(
                           UpperCamelCase_       ,					student_outputs['''encoder_hidden_states''']       ,					all_teacher_encoder_outputs['''hidden_states''']       ,					self.e_matches       ,					normalize_hidden=self.hparams.normalize_hidden       ,					)

           lowerCAmelCase       :						Optional[Any]							= self.teacher(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					encoder_outputs=(teacher_enc_outputs,)       ,					decoder_input_ids=UpperCamelCase_       ,					output_hidden_states=self.do_calc_hidden_loss       ,					use_cache=UpperCamelCase_       ,					)
           lowerCAmelCase       :						List[Any]							= decoder_input_ids.ne(UpperCamelCase_					)
           lowerCAmelCase       :						int							= self.calc_ce_loss(UpperCamelCase_       ,					UpperCamelCase_       ,					teacher_outputs['''logits''']					)
           if self.do_calc_hidden_loss:  # Intermediate supervision of decoder hidden states
                 lowerCAmelCase       :						str							= self.calc_hidden_loss(
                     UpperCamelCase_       ,					student_outputs['''decoder_hidden_states''']       ,					teacher_outputs['''decoder_hidden_states''']       ,					self.d_matches       ,					normalize_hidden=self.hparams.normalize_hidden       ,					)

           lowerCAmelCase       :						str							= (
               self.alpha_ce * loss_ce
               + self.alpha_mlm * student_lm_loss
               + self.hparams.alpha_hid * (hid_loss_enc + hid_loss_dec)
           )
           return blended_loss, loss_ce, student_lm_loss, hid_loss_enc, hid_loss_dec






     @staticmethod
     def   lowerCamelCase__  (						UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						Any							= '''expected list or tuple for hidden_states, got tensor of shape: '''
           assert not isinstance(UpperCamelCase_       ,					torch.Tensor					), F'''{msg}{hidden_states.shape}'''
           assert not isinstance(UpperCamelCase_       ,					torch.Tensor					), F'''{msg}{hidden_states_T.shape}'''
           lowerCAmelCase       :						Union[str, Any]							= attention_mask.to(hidden_states[0]					)
           lowerCAmelCase       :						Any							= mask.sum() * hidden_states[0].size(-1					)
           lowerCAmelCase       :						int							= torch.stack([hidden_states[i] for i in range(len(UpperCamelCase_					)					)]					)
           lowerCAmelCase       :						Tuple							= torch.stack([hidden_states_T[j] for j in matches]					)
           assert student_states.shape == teacher_states.shape, F'''{student_states.shape} != {teacher_states.shape}'''
           if normalize_hidden:
                 lowerCAmelCase       :						List[Any]							= nn.functional.layer_norm(UpperCamelCase_       ,					student_states.shape[1:]					)
                 lowerCAmelCase       :						Any							= nn.functional.layer_norm(UpperCamelCase_       ,					teacher_states.shape[1:]					)
           lowerCAmelCase       :						Dict							= nn.functional.mse_loss(UpperCamelCase_       ,					UpperCamelCase_       ,					reduction='''none'''					)
           lowerCAmelCase       :						Optional[int]							= (mse * mask.unsqueeze(0					).unsqueeze(-1					)).sum() / valid_count
           return masked_mse



def   _snake_case    (    _snake_case					:      Union[str, Any]      ):
      # NOTE: if --student argument was specified and the teacher and student base models
      # are different, the models still have to have the same tokenizer, specified by
      # --tokenizer_name. So, for example, you can distill from t5_large to t5_small but not
      # from bart to t5. This s because if the tokenizers are different, the output space
      # for the two models is also different and their logits are not comparable.
      parser.add_argument('''--teacher'''			, type=_snake_case      )
      parser.add_argument('''--alpha_ce'''			, default=0.8			, type=_snake_case      )
      parser.add_argument('''--alpha_mlm'''			, default=0.2			, type=_snake_case      )
      parser.add_argument('''--alpha_hid'''			, default=0.0			, type=_snake_case			, required=_snake_case      )
      parser.add_argument('''--student'''			, type=_snake_case			, required=_snake_case      )
      parser.add_argument('''--student_decoder_layers'''			, default=12			, type=_snake_case			, required=_snake_case      )
      parser.add_argument('''--student_encoder_layers'''			, default=12			, type=_snake_case			, required=_snake_case      )
      parser.add_argument('''--no_teacher'''			, action='''store_true'''			, default=_snake_case      )
      parser.add_argument('''--length_penalty'''			, type=_snake_case			, default=-1      )
      parser.add_argument('''--supervise_forward'''			, action='''store_true'''			, default=_snake_case      )
      parser.add_argument('''--normalize_hidden'''			, action='''store_true'''			, default=_snake_case      )



class 		snake_case_(							a__      ):
     __UpperCamelCase	=       '''translation'''
     __UpperCamelCase	=       ['''bleu''']
     __UpperCamelCase	=       '''bleu'''






     def __init__(						self	:       Optional[int]       ,					UpperCamelCase_	:       Tuple       ,					**UpperCamelCase_	:       Optional[Any]					):
           super().__init__(UpperCamelCase_       ,					**UpperCamelCase_					)
           assert hparams.src_lang is not None
           assert hparams.tgt_lang is not None
           lowerCAmelCase       :						Tuple							= hparams.src_lang
           lowerCAmelCase       :						str							= hparams.tgt_lang
           if self.model.config.decoder_start_token_id is None and isinstance(self.tokenizer       ,					UpperCamelCase_					):
                 lowerCAmelCase       :						List[str]							= self.tokenizer.lang_code_to_id[hparams.tgt_lang]






     def   lowerCamelCase__  (						self	:       List[str]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[Any]					):
           return calculate_bleu(UpperCamelCase_       ,					UpperCamelCase_					)






     @staticmethod
     def   lowerCamelCase__  (						UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       Dict					):
           TranslationModule.add_model_specific_args(UpperCamelCase_       ,					UpperCamelCase_					)
           add_distill_args(UpperCamelCase_					)
           return parser



def   _snake_case    (    _snake_case					:      Optional[int]      ):
      if args.no_teacher:
            lowerCAmelCase       :						Optional[Any]							= TranslationModule if '''translation''' in args.task else SummarizationModule
      else:  # DISTILL WITH TEACHER
            lowerCAmelCase       :						Any							= TranslationDistiller if '''translation''' in args.task else SummarizationDistiller
      lowerCAmelCase       :						str							= module_cls.__name__
      print(f'''using module {args.setup_cls}'''      )
      lowerCAmelCase       :						Optional[Any]							= module_cls(_snake_case      )
      return model


def   _snake_case    (    _snake_case					:      List[str]      ):
      Path(args.output_dir      ).mkdir(exist_ok=_snake_case      )
      check_output_dir(_snake_case			, expected_items=3      )

      lowerCAmelCase       :						str							= create_module(_snake_case      )
      return ft_main(_snake_case			, model=_snake_case      )


if __name__ == "__main__":
 snake_case__		:  str     					=					argparse.ArgumentParser()
 snake_case__		:  str     					=					pl.Trainer.add_argparse_args(parser)
 snake_case__		:  str     					=					SummarizationDistiller.add_model_specific_args(parser, os.getcwd())
 snake_case__		:  List[str]     					=					parser.parse_args()

 distill_main(args)






"""simple docstring"""





import unittest

from transformers import ErnieMConfig, 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 (
     ErnieMForInformationExtraction,
     ErnieMForMultipleChoice,
     ErnieMForQuestionAnswering,
     ErnieMForSequenceClassification,
     ErnieMForTokenClassification,
     ErnieMModel,
 )
 from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST



class 		snake_case_:






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






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

           lowerCAmelCase       :						List[Any]							= None
           if self.use_input_mask:
                 lowerCAmelCase       :						str							= random_attention_mask([self.batch_size, self.seq_length]					)

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

           lowerCAmelCase       :						Any							= self.get_config()

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






     def   lowerCamelCase__  (						self	:       str					):
           lowerCAmelCase       :						Tuple							= ids_tensor([self.batch_size, self.seq_length]       ,					self.vocab_size					)

           lowerCAmelCase       :						Optional[Any]							= None
           if self.use_input_mask:
                 lowerCAmelCase       :						Union[str, Any]							= random_attention_mask([self.batch_size, self.seq_length]					)
           lowerCAmelCase       :						Dict							= self.get_config()

           return config, input_ids, input_mask






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           return ErnieMConfig(
               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       ,					initializer_range=self.initializer_range       ,					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						List[str]							= ErnieMModel(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= model(UpperCamelCase_       ,					return_dict=UpperCamelCase_					)
           self.parent.assertEqual(result.last_hidden_state.shape       ,					(self.batch_size, self.seq_length, self.hidden_size)					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Optional[Any]					):
           lowerCAmelCase       :						Optional[int]							= ErnieMForQuestionAnswering(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						List[Any]							= 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   lowerCamelCase__  (						self	:       Dict       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Optional[Any]       ,					UpperCamelCase_	:       Union[str, Any]					):
           lowerCAmelCase       :						Tuple							= ErnieMForInformationExtraction(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Tuple							= torch.ones_like(UpperCamelCase_       ,					dtype=torch.floataa					)
           lowerCAmelCase       :						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   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Union[str, Any]       ,					UpperCamelCase_	:       Any					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						Tuple							= ErnieMForSequenceClassification(UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Union[str, Any]							= model(UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_labels)					)






     def   lowerCamelCase__  (						self	:       Optional[int]       ,					UpperCamelCase_	:       Any       ,					UpperCamelCase_	:       List[str]       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[str]					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_labels
           lowerCAmelCase       :						List[Any]							= ErnieMForTokenClassification(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           input_ids.to(UpperCamelCase_					)
           input_mask.to(UpperCamelCase_					)
           token_labels.to(UpperCamelCase_					)

           lowerCAmelCase       :						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   lowerCamelCase__  (						self	:       Any       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       Optional[int]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       Dict       ,					UpperCamelCase_	:       str					):
           lowerCAmelCase       :						Union[str, Any]							= self.num_choices
           lowerCAmelCase       :						Any							= ErnieMForMultipleChoice(config=UpperCamelCase_					)
           model.to(UpperCamelCase_					)
           model.eval()
           lowerCAmelCase       :						Any							= input_ids.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						int							= input_mask.unsqueeze(1					).expand(-1       ,					self.num_choices       ,					-1					).contiguous()
           lowerCAmelCase       :						Any							= model(
               UpperCamelCase_       ,					attention_mask=UpperCamelCase_       ,					labels=UpperCamelCase_       ,					)
           self.parent.assertEqual(result.logits.shape       ,					(self.batch_size, self.num_choices)					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[Any]							= self.prepare_config_and_inputs()
           (
               (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   (
               lowerCAmelCase
           ),   
           )       :						str							= config_and_inputs
           lowerCAmelCase       :						Dict							= {'''input_ids''': input_ids, '''attention_mask''': input_mask}
           return config, inputs_dict



@require_torch
class 		snake_case_(							a__				,       a__				,       unittest.TestCase      ):
     __UpperCamelCase	=       (
         (
             ErnieMModel,
             ErnieMForMultipleChoice,
             ErnieMForQuestionAnswering,
             ErnieMForSequenceClassification,
             ErnieMForTokenClassification,
         )
         if is_torch_available()
         else ()
     )
     __UpperCamelCase	=       ()
     __UpperCamelCase	=       (
         {
             '''feature-extraction''': ErnieMModel,
             '''question-answering''': ErnieMForQuestionAnswering,
             '''text-classification''': ErnieMForSequenceClassification,
             '''token-classification''': ErnieMForTokenClassification,
             '''zero-shot''': ErnieMForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )
     __UpperCamelCase	=       False






     def   lowerCamelCase__  (						self	:       Optional[Any]       ,					UpperCamelCase_	:       str       ,					UpperCamelCase_	:       List[Any]       ,					UpperCamelCase_	:       Tuple       ,					UpperCamelCase_	:       int       ,					UpperCamelCase_	:       Any					):
           if pipeline_test_casse_name == "QAPipelineTests":
                 return True

           return False






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						str							= ErnieMModelTester(self					)
           lowerCAmelCase       :						Optional[Any]							= ConfigTester(self       ,					config_class=UpperCamelCase_       ,					hidden_size=3_7					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           self.config_tester.run_common_tests()






     def   lowerCamelCase__  (						self	:       List[str]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Union[str, Any]					):
           lowerCAmelCase       :						Optional[Any]							= self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                 lowerCAmelCase       :						Union[str, Any]							= type
                 self.model_tester.create_and_check_model(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						Dict							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						int							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Optional[int]					):
           lowerCAmelCase       :						Tuple							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       Tuple					):
           lowerCAmelCase       :						List[str]							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_information_extraction(*UpperCamelCase_					)






     def   lowerCamelCase__  (						self	:       List[Any]					):
           lowerCAmelCase       :						str							= self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(*UpperCamelCase_					)






     @slow
     def   lowerCamelCase__  (						self	:       List[str]					):
           for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCAmelCase       :						int							= ErnieMModel.from_pretrained(UpperCamelCase_					)
                 self.assertIsNotNone(UpperCamelCase_					)



@require_torch
class 		snake_case_(							unittest.TestCase      ):






     @slow
     def   lowerCamelCase__  (						self	:       Dict					):
           lowerCAmelCase       :						Optional[int]							= ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''					)
           model.eval()
           lowerCAmelCase       :						Optional[int]							= torch.tensor([[0, 1, 2, 3, 4, 5]]					)
           lowerCAmelCase       :						str							= model(UpperCamelCase_					)[0]

           # TODO Replace vocab size
           lowerCAmelCase       :						Any							= 7_6_8

           lowerCAmelCase       :						int							= torch.Size((1, 6, hidden_size)					)
           self.assertEqual(output.shape       ,					UpperCamelCase_					)

           lowerCAmelCase       :						str							= torch.tensor(
               [[[-0.0_012, 0.1_245, -0.0_214], [-0.0_742, 0.0_244, -0.0_771], [-0.0_333, 0.1_164, -0.1_554]]]					)

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


