



import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)





def   __snake_case			(    _UpperCAmelCase       ):
    __a		 =       torch.exp(_UpperCAmelCase       )
    __a		 =       torch.sum(_UpperCAmelCase     ,				dim=1       )  # sum of exp(x_i)
    __a		 =       torch.sum(x * exp_x     ,				dim=1       )  # sum of x_i * exp(x_i)
    return torch.log(_UpperCAmelCase       ) - B / A

class 					_A (			nn.Module					):



       def __init__(	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           super().__init__()
           __a		 =       config.output_attentions
           __a		 =       config.output_hidden_states
           __a		 =       nn.ModuleList([BertLayer(__SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)])
           __a		 =       nn.ModuleList([BertHighway(__SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)])

           __a		 =       [-1 for _ in range(config.num_hidden_layers)]



       def 	_lowerCamelCase    (	self							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict):


           '''simple docstring'''

           if (type(__SCREAMING_SNAKE_CASE) is float) or (type(__SCREAMING_SNAKE_CASE) is int):
               for i in range(len(self.early_exit_entropy)):
                   __a		 =       x
           else:
               __a		 =       x



       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  int):


           '''simple docstring'''

           __a		 =       pooler.state_dict()
           for highway in self.highway:
               for name, param in highway.pooler.state_dict().items():
                   param.copy_(loaded_model[name])





       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  Dict=None  ,	__SCREAMING_SNAKE_CASE							:  Any=None  ,	__SCREAMING_SNAKE_CASE							:  Any=None  ,	__SCREAMING_SNAKE_CASE							:  int=None  ,	):


           '''simple docstring'''

           __a		 =       ()
           __a		 =       ()
           __a		 =       ()
           for i, layer_module in enumerate(self.layer):
               if self.output_hidden_states:
                   __a		 =       all_hidden_states + (hidden_states,)

               __a		 =       layer_module(
                   __SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	head_mask[i]  ,	__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)
               __a		 =       layer_outputs[0]

               if self.output_attentions:
                   __a		 =       all_attentions + (layer_outputs[1],)

               __a		 =       (hidden_states,)
               if self.output_hidden_states:
                   __a		 =       current_outputs + (all_hidden_states,)
               if self.output_attentions:
                   __a		 =       current_outputs + (all_attentions,)

               __a		 =       self.highway[i](__SCREAMING_SNAKE_CASE)
               # logits, pooled_output

               if not self.training:
                   __a		 =       highway_exit[0]
                   __a		 =       entropy(__SCREAMING_SNAKE_CASE)
                   __a		 =       highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                   __a		 =       all_highway_exits + (highway_exit,)

                   if highway_entropy < self.early_exit_entropy[i]:
                       __a		 =       (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                       raise HighwayException(__SCREAMING_SNAKE_CASE  ,	i + 1)
               else:
                   __a		 =       all_highway_exits + (highway_exit,)

        # Add last layer
           if self.output_hidden_states:
               __a		 =       all_hidden_states + (hidden_states,)

           __a		 =       (hidden_states,)
           if self.output_hidden_states:
               __a		 =       outputs + (all_hidden_states,)
           if self.output_attentions:
               __a		 =       outputs + (all_attentions,)

           __a		 =       outputs + (all_highway_exits,)
           return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits


@add_start_docstrings(
    '''The Bert Model transformer with early exiting (DeeBERT). '''   ,__UpperCAmelCase   ,)
class 					_A (			__UpperCAmelCase					):



       def __init__(	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]):


           '''simple docstring'''

           super().__init__(__SCREAMING_SNAKE_CASE)
           __a		 =       config

           __a		 =       BertEmbeddings(__SCREAMING_SNAKE_CASE)
           __a		 =       DeeBertEncoder(__SCREAMING_SNAKE_CASE)
           __a		 =       BertPooler(__SCREAMING_SNAKE_CASE)

           self.init_weights()



       def 	_lowerCamelCase    (	self							:  Optional[Any]):


           '''simple docstring'''

           self.encoder.init_highway_pooler(self.pooler)



       def 	_lowerCamelCase    (	self							:  Optional[int]):


           '''simple docstring'''

           return self.embeddings.word_embeddings



       def 	_lowerCamelCase    (	self							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           __a		 =       value



       def 	_lowerCamelCase    (	self							:  Union[str, Any]  ,	__SCREAMING_SNAKE_CASE							:  int):


           '''simple docstring'''

           for layer, heads in heads_to_prune.items():
               self.encoder.layer[layer].attention.prune_heads(__SCREAMING_SNAKE_CASE)





       @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  str=None  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=None  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=None  ,	__SCREAMING_SNAKE_CASE							:  str=None  ,	__SCREAMING_SNAKE_CASE							:  Any=None  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=None  ,	__SCREAMING_SNAKE_CASE							:  str=None  ,	__SCREAMING_SNAKE_CASE							:  str=None  ,	):


           '''simple docstring'''

           if input_ids is not None and inputs_embeds is not None:
               raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''')
           elif input_ids is not None:
               __a		 =       input_ids.size()
           elif inputs_embeds is not None:
               __a		 =       inputs_embeds.size()[:-1]
           else:
               raise ValueError('''You have to specify either input_ids or inputs_embeds''')

           __a		 =       input_ids.device if input_ids is not None else inputs_embeds.device

           if attention_mask is None:
               __a		 =       torch.ones(__SCREAMING_SNAKE_CASE  ,	device=__SCREAMING_SNAKE_CASE)
           if encoder_attention_mask is None:
               __a		 =       torch.ones(__SCREAMING_SNAKE_CASE  ,	device=__SCREAMING_SNAKE_CASE)
           if token_type_ids is None:
               __a		 =       torch.zeros(__SCREAMING_SNAKE_CASE  ,	dtype=torch.long  ,	device=__SCREAMING_SNAKE_CASE)

           # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
           # ourselves in which case we just need to make it broadcastable to all heads.
           __a		 =       self.get_extended_attention_mask(__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE  ,	__SCREAMING_SNAKE_CASE)

           # If a 2D ou 3D attention mask is provided for the cross-attention
           # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
           if encoder_attention_mask.dim() == 3:
               __a		 =       encoder_attention_mask[:, None, :, :]
           if encoder_attention_mask.dim() == 2:
               __a		 =       encoder_attention_mask[:, None, None, :]

           __a		 =       encoder_extended_attention_mask.to(
               dtype=next(self.parameters()).dtype)  # fp16 compatibility
           __a		 =       (1.0 - encoder_extended_attention_mask) * -1_00_00.0

           # Prepare head mask if needed
           # 1.0 in head_mask indicate we keep the head
           # attention_probs has shape bsz x n_heads x N x N
           # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
           # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
           __a		 =       self.get_head_mask(__SCREAMING_SNAKE_CASE  ,	self.config.num_hidden_layers)

           __a		 =       self.embeddings(
               input_ids=__SCREAMING_SNAKE_CASE  ,	position_ids=__SCREAMING_SNAKE_CASE  ,	token_type_ids=__SCREAMING_SNAKE_CASE  ,	inputs_embeds=__SCREAMING_SNAKE_CASE)
           __a		 =       self.encoder(
               __SCREAMING_SNAKE_CASE  ,	attention_mask=__SCREAMING_SNAKE_CASE  ,	head_mask=__SCREAMING_SNAKE_CASE  ,	encoder_hidden_states=__SCREAMING_SNAKE_CASE  ,	encoder_attention_mask=__SCREAMING_SNAKE_CASE  ,	)
           __a		 =       encoder_outputs[0]
           __a		 =       self.pooler(__SCREAMING_SNAKE_CASE)

           __a		 =       (
               sequence_output,
               pooled_output,
           ) + encoder_outputs[
               1:
           ]  # add hidden_states and attentions if they are here
           return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits


class 					_A (			__UpperCAmelCase					):



       def __init__(	self							:  Any  ,	__SCREAMING_SNAKE_CASE							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           __a		 =       message
           __a		 =       exit_layer  # start from 1!


class 					_A (			nn.Module					):



       def __init__(	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  str):


           '''simple docstring'''

           super().__init__()
           __a		 =       BertPooler(__SCREAMING_SNAKE_CASE)
           __a		 =       nn.Dropout(config.hidden_dropout_prob)
           __a		 =       nn.Linear(config.hidden_size  ,	config.num_labels)





       def 	_lowerCamelCase    (	self							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]):


           '''simple docstring'''

           __a		 =       encoder_outputs[0]
           __a		 =       self.pooler(__SCREAMING_SNAKE_CASE)
           # "return" pooler_output

           # BertModel
           __a		 =       (pooler_input, pooler_output) + encoder_outputs[1:]
           # "return" bmodel_output

           # Dropout and classification
           __a		 =       bmodel_output[1]

           __a		 =       self.dropout(__SCREAMING_SNAKE_CASE)
           __a		 =       self.classifier(__SCREAMING_SNAKE_CASE)

           return logits, pooled_output


@add_start_docstrings(
    '''Bert Model (with early exiting - DeeBERT) with a classifier on top,
    also takes care of multi-layer training. '''   ,__UpperCAmelCase   ,)
class 					_A (			__UpperCAmelCase					):



       def __init__(	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  int):


           '''simple docstring'''

           super().__init__(__SCREAMING_SNAKE_CASE)
           __a		 =       config.num_labels
           __a		 =       config.num_hidden_layers

           __a		 =       DeeBertModel(__SCREAMING_SNAKE_CASE)
           __a		 =       nn.Dropout(config.hidden_dropout_prob)
           __a		 =       nn.Linear(config.hidden_size  ,	self.config.num_labels)

           self.init_weights()





       @add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=None  ,	__SCREAMING_SNAKE_CASE							:  Any=None  ,	__SCREAMING_SNAKE_CASE							:  str=None  ,	__SCREAMING_SNAKE_CASE							:  Union[str, Any]=None  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]=None  ,	__SCREAMING_SNAKE_CASE							:  Tuple=None  ,	__SCREAMING_SNAKE_CASE							:  int=None  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=-1  ,	__SCREAMING_SNAKE_CASE							:  str=False  ,	):


           '''simple docstring'''

           __a		 =       self.num_layers
           try:
               __a		 =       self.bert(
                   __SCREAMING_SNAKE_CASE  ,	attention_mask=__SCREAMING_SNAKE_CASE  ,	token_type_ids=__SCREAMING_SNAKE_CASE  ,	position_ids=__SCREAMING_SNAKE_CASE  ,	head_mask=__SCREAMING_SNAKE_CASE  ,	inputs_embeds=__SCREAMING_SNAKE_CASE  ,	)
               # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

               __a		 =       outputs[1]

               __a		 =       self.dropout(__SCREAMING_SNAKE_CASE)
               __a		 =       self.classifier(__SCREAMING_SNAKE_CASE)
               __a		 =       (logits,) + outputs[2:]  # add hidden states and attention if they are here
           except HighwayException as e:
               __a		 =       e.message
               __a		 =       e.exit_layer
               __a		 =       outputs[0]

           if not self.training:
               __a		 =       entropy(__SCREAMING_SNAKE_CASE)
               __a		 =       []
               __a		 =       []
           if labels is not None:
               if self.num_labels == 1:
                   #  We are doing regression
                   __a		 =       MSELoss()
                   __a		 =       loss_fct(logits.view(-1)  ,	labels.view(-1))
               else:
                   __a		 =       CrossEntropyLoss()
                   __a		 =       loss_fct(logits.view(-1  ,	self.num_labels)  ,	labels.view(-1))

               # work with highway exits
               __a		 =       []
               for highway_exit in outputs[-1]:
                   __a		 =       highway_exit[0]
                   if not self.training:
                       highway_logits_all.append(__SCREAMING_SNAKE_CASE)
                       highway_entropy.append(highway_exit[2])
                   if self.num_labels == 1:
                       #  We are doing regression
                       __a		 =       MSELoss()
                       __a		 =       loss_fct(highway_logits.view(-1)  ,	labels.view(-1))
                   else:
                       __a		 =       CrossEntropyLoss()
                       __a		 =       loss_fct(highway_logits.view(-1  ,	self.num_labels)  ,	labels.view(-1))
                   highway_losses.append(__SCREAMING_SNAKE_CASE)

               if train_highway:
                   __a		 =       (sum(highway_losses[:-1]),) + outputs
                   # exclude the final highway, of course
               else:
                   __a		 =       (loss,) + outputs
           if not self.training:
               __a		 =       outputs + ((original_entropy, highway_entropy), exit_layer)
               if output_layer >= 0:
                   __a		 =       (
                       (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
                   )  # use the highway of the last layer

           return outputs  # (loss), logits, (hidden_states), (attentions), (highway_exits)










# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__snake_case		:Union[str, Any]   	=  Path(__file__).resolve().parents[3] / '''src'''
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__snake_case		:str   	=  {'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''}

__snake_case		:List[Any]   	=  '''zero2'''
__snake_case		:Optional[Any]   	=  '''zero3'''
__snake_case		:str   	=  [ZEROa, ZEROa]





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       ):
    # customize the test name generator function as we want both params to appear in the sub-test
    # name, as by default it shows only the first param
    __a		 =       parameterized.to_safe_name('''_'''.join(str(_UpperCAmelCase       ) for x in param.args       )       )
    return f'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
__snake_case		:List[Any]   	=  list(itertools.product(stages, models.keys()))

@slow
@require_deepspeed
@require_torch_gpu
class 					_A (			__UpperCAmelCase					):



       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  Dict  ,	__SCREAMING_SNAKE_CASE							:  Optional[Any]  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @require_torch_multi_gpu
       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  str  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  Any):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       @require_torch_multi_gpu
       @parameterized.expand(__SCREAMING_SNAKE_CASE  ,	name_func=__SCREAMING_SNAKE_CASE)
       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  Optional[int]  ,	__SCREAMING_SNAKE_CASE							:  List[Any]):


           '''simple docstring'''

           self.run_and_check(
               stage=__SCREAMING_SNAKE_CASE  ,	model=__SCREAMING_SNAKE_CASE  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)



       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  List[str]):


           '''simple docstring'''

           pass



       def 	_lowerCamelCase    (	self							:  Any  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  int = 10  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	):


           '''simple docstring'''

           __a		 =       models[model]

           __a		 =       self.run_trainer(
               stage=__SCREAMING_SNAKE_CASE  ,	model_name=__SCREAMING_SNAKE_CASE  ,	eval_steps=__SCREAMING_SNAKE_CASE  ,	num_train_epochs=1  ,	distributed=__SCREAMING_SNAKE_CASE  ,	fpaa=__SCREAMING_SNAKE_CASE  ,	)

           self.do_checks(__SCREAMING_SNAKE_CASE)

           return output_dir



       def 	_lowerCamelCase    (	self							:  List[str]  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  str  ,	__SCREAMING_SNAKE_CASE							:  int = 10  ,	__SCREAMING_SNAKE_CASE							:  int = 1  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	__SCREAMING_SNAKE_CASE							:  bool = True  ,	):


           '''simple docstring'''

           __a		 =       self.get_auto_remove_tmp_dir('''./xxx'''  ,	after=__SCREAMING_SNAKE_CASE)
           __a		 =       F'\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(__SCREAMING_SNAKE_CASE)}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        '.split()

           if fpaa:
               args.extend(['''--fp16'''])

           # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
           # hence the separate config files
           __a		 =       F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
           __a		 =       [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
           __a		 =       self.get_launcher(__SCREAMING_SNAKE_CASE)

           __a		 =       launcher + script + args + ds_args
           # keep for quick debug
           # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
           execute_subprocess_async(__SCREAMING_SNAKE_CASE  ,	env=self.get_env())

           return output_dir





       def 	_lowerCamelCase    (	self							:  int  ,	__SCREAMING_SNAKE_CASE							:  List[Any]=False):


           '''simple docstring'''

           __a		 =       min(2  ,	get_gpu_count()) if distributed else 1
           return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()





