


'''simple docstring'''
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     a   (    __a     )						->			int:



					'''simple docstring'''






					UpperCamelCase__     :Dict							      =				torch.exp(__a     )
					UpperCamelCase__     :int							      =				torch.sum(__a				,      dim=1     )  # sum of exp(x_i)
					UpperCamelCase__     :Any							      =				torch.sum(x * exp_x				,      dim=1     )  # sum of x_i * exp(x_i)
					return torch.log(__a     ) - B / A
class      lowercase			(							nn.Module      ):

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__     :Optional[Any]							      =				config.output_attentions
							UpperCamelCase__     :Tuple							      =				config.output_hidden_states
							UpperCamelCase__     :List[Any]							      =				nn.ModuleList([BertLayer(UpperCamelCase_							) for _ in range(config.num_hidden_layers							)]							)
							UpperCamelCase__     :Optional[int]							      =				nn.ModuleList([BertHighway(UpperCamelCase_							) for _ in range(config.num_hidden_layers							)]							)

							UpperCamelCase__     :str							      =				[-1 for _ in range(config.num_hidden_layers							)]




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							if (type(UpperCamelCase_							) is float) or (type(UpperCamelCase_							) is int):
												for i in range(len(self.early_exit_entropy							)							):
																	UpperCamelCase__     :int							      =				x
							else:
												UpperCamelCase__     :List[str]							      =				x




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :str							      =				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					,     UpperCamelCase_					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     ):

							'''simple docstring'''


							UpperCamelCase__     :List[Any]							      =				()
							UpperCamelCase__     :Tuple							      =				()
							UpperCamelCase__     :List[str]							      =				()
							for i, layer_module in enumerate(self.layer							):
												if self.output_hidden_states:
																	UpperCamelCase__     :Any							      =				all_hidden_states + (hidden_states,)

												UpperCamelCase__     :str							      =				layer_module(
												    UpperCamelCase_					,     UpperCamelCase_					,     head_mask[i]					,     UpperCamelCase_					,     UpperCamelCase_							)
												UpperCamelCase__     :str							      =				layer_outputs[0]

												if self.output_attentions:
																	UpperCamelCase__     :List[Any]							      =				all_attentions + (layer_outputs[1],)

												UpperCamelCase__     :Optional[int]							      =				(hidden_states,)
												if self.output_hidden_states:
																	UpperCamelCase__     :Union[str, Any]							      =				current_outputs + (all_hidden_states,)
												if self.output_attentions:
																	UpperCamelCase__     :int							      =				current_outputs + (all_attentions,)

												UpperCamelCase__     :Optional[Any]							      =				self.highway[i](UpperCamelCase_							)
												# logits, pooled_output

												if not self.training:
																	UpperCamelCase__     :Optional[int]							      =				highway_exit[0]
																	UpperCamelCase__     :List[Any]							      =				entropy(UpperCamelCase_							)
																	UpperCamelCase__     :str							      =				highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
																	UpperCamelCase__     :Any							      =				all_highway_exits + (highway_exit,)

																	if highway_entropy < self.early_exit_entropy[i]:
																						UpperCamelCase__     :Optional[Any]							      =				(highway_logits,) + current_outputs[1:] + (all_highway_exits,)
																						raise HighwayException(UpperCamelCase_					,     i + 1							)
												else:
																	UpperCamelCase__     :Optional[Any]							      =				all_highway_exits + (highway_exit,)

        # Add last layer
							if self.output_hidden_states:
												UpperCamelCase__     :Optional[Any]							      =				all_hidden_states + (hidden_states,)

							UpperCamelCase__     :List[str]							      =				(hidden_states,)
							if self.output_hidden_states:
												UpperCamelCase__     :Union[str, Any]							      =				outputs + (all_hidden_states,)
							if self.output_attentions:
												UpperCamelCase__     :Optional[int]							      =				outputs + (all_attentions,)

							UpperCamelCase__     :str							      =				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). '			,	A__			,	)
class      lowercase			(							A__      ):

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_							)
							UpperCamelCase__     :Dict							      =				config

							UpperCamelCase__     :int							      =				BertEmbeddings(UpperCamelCase_							)
							UpperCamelCase__     :Union[str, Any]							      =				DeeBertEncoder(UpperCamelCase_							)
							UpperCamelCase__     :int							      =				BertPooler(UpperCamelCase_							)

							self.init_weights()




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							self.encoder.init_highway_pooler(self.pooler							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							return self.embeddings.word_embeddings




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :Optional[int]							      =				value




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


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




		@add_start_docstrings_to_model_forward(UpperCamelCase_							)
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=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:
												UpperCamelCase__     :Union[str, Any]							      =				input_ids.size()
							elif inputs_embeds is not None:
												UpperCamelCase__     :int							      =				inputs_embeds.size()[:-1]
							else:
												raise ValueError('''You have to specify either input_ids or inputs_embeds'''							)

							UpperCamelCase__     :str							      =				input_ids.device if input_ids is not None else inputs_embeds.device

							if attention_mask is None:
												UpperCamelCase__     :Union[str, Any]							      =				torch.ones(UpperCamelCase_					,     device=UpperCamelCase_							)
							if encoder_attention_mask is None:
												UpperCamelCase__     :Optional[Any]							      =				torch.ones(UpperCamelCase_					,     device=UpperCamelCase_							)
							if token_type_ids is None:
												UpperCamelCase__     :str							      =				torch.zeros(UpperCamelCase_					,     dtype=torch.long					,     device=UpperCamelCase_							)

							# 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.
							UpperCamelCase__     :torch.Tensor							      =				self.get_extended_attention_mask(UpperCamelCase_					,     UpperCamelCase_					,     UpperCamelCase_							)

							# 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:
												UpperCamelCase__     :Dict							      =				encoder_attention_mask[:, None, :, :]
							if encoder_attention_mask.dim() == 2:
												UpperCamelCase__     :List[str]							      =				encoder_attention_mask[:, None, None, :]

							UpperCamelCase__     :Tuple							      =				encoder_extended_attention_mask.to(
							    dtype=next(self.parameters()							).dtype							)  # fp16 compatibility
							UpperCamelCase__     :int							      =				(1.0 - encoder_extended_attention_mask) * -10000.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]
							UpperCamelCase__     :List[str]							      =				self.get_head_mask(UpperCamelCase_					,     self.config.num_hidden_layers							)

							UpperCamelCase__     :Any							      =				self.embeddings(
							    input_ids=UpperCamelCase_					,     position_ids=UpperCamelCase_					,     token_type_ids=UpperCamelCase_					,     inputs_embeds=UpperCamelCase_							)
							UpperCamelCase__     :str							      =				self.encoder(
							    UpperCamelCase_					,     attention_mask=UpperCamelCase_					,     head_mask=UpperCamelCase_					,     encoder_hidden_states=UpperCamelCase_					,     encoder_attention_mask=UpperCamelCase_					,     )
							UpperCamelCase__     :List[str]							      =				encoder_outputs[0]
							UpperCamelCase__     :Optional[int]							      =				self.pooler(UpperCamelCase_							)

							UpperCamelCase__     :List[str]							      =				(
							    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      lowercase			(							A__      ):

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :int							      =				message
							UpperCamelCase__     :Any							      =				exit_layer  # start from 1!



class      lowercase			(							nn.Module      ):

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__()
							UpperCamelCase__     :List[str]							      =				BertPooler(UpperCamelCase_							)
							UpperCamelCase__     :Dict							      =				nn.Dropout(config.hidden_dropout_prob							)
							UpperCamelCase__     :List[Any]							      =				nn.Linear(config.hidden_size					,     config.num_labels							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :Tuple							      =				encoder_outputs[0]
							UpperCamelCase__     :List[str]							      =				self.pooler(UpperCamelCase_							)
							# "return" pooler_output

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

							# Dropout and classification
							UpperCamelCase__     :Dict							      =				bmodel_output[1]

							UpperCamelCase__     :Dict							      =				self.dropout(UpperCamelCase_							)
							UpperCamelCase__     :Optional[Any]							      =				self.classifier(UpperCamelCase_							)

							return logits, pooled_output



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

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							super().__init__(UpperCamelCase_							)
							UpperCamelCase__     :List[Any]							      =				config.num_labels
							UpperCamelCase__     :int							      =				config.num_hidden_layers

							UpperCamelCase__     :int							      =				DeeBertModel(UpperCamelCase_							)
							UpperCamelCase__     :Dict							      =				nn.Dropout(config.hidden_dropout_prob							)
							UpperCamelCase__     :List[Any]							      =				nn.Linear(config.hidden_size					,     self.config.num_labels							)

							self.init_weights()




		@add_start_docstrings_to_model_forward(UpperCamelCase_							)
		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=None					,     UpperCamelCase_=-1					,     UpperCamelCase_=False					,     ):

							'''simple docstring'''


							UpperCamelCase__     :Dict							      =				self.num_layers
							try:
												UpperCamelCase__     :Optional[int]							      =				self.bert(
												    UpperCamelCase_					,     attention_mask=UpperCamelCase_					,     token_type_ids=UpperCamelCase_					,     position_ids=UpperCamelCase_					,     head_mask=UpperCamelCase_					,     inputs_embeds=UpperCamelCase_					,     )
												# sequence_output, pooled_output, (hidden_states), (attentions), highway exits

												UpperCamelCase__     :Optional[Any]							      =				outputs[1]

												UpperCamelCase__     :Any							      =				self.dropout(UpperCamelCase_							)
												UpperCamelCase__     :List[Any]							      =				self.classifier(UpperCamelCase_							)
												UpperCamelCase__     :Dict							      =				(logits,) + outputs[2:]  # add hidden states and attention if they are here
							except HighwayException as e:
												UpperCamelCase__     :List[Any]							      =				e.message
												UpperCamelCase__     :str							      =				e.exit_layer
												UpperCamelCase__     :Tuple							      =				outputs[0]

							if not self.training:
												UpperCamelCase__     :List[Any]							      =				entropy(UpperCamelCase_							)
												UpperCamelCase__     :Tuple							      =				[]
												UpperCamelCase__     :Tuple							      =				[]
							if labels is not None:
												if self.num_labels == 1:
																	#  We are doing regression
																	UpperCamelCase__     :Tuple							      =				MSELoss()
																	UpperCamelCase__     :Dict							      =				loss_fct(logits.view(-1							)					,     labels.view(-1							)							)
												else:
																	UpperCamelCase__     :List[Any]							      =				CrossEntropyLoss()
																	UpperCamelCase__     :List[Any]							      =				loss_fct(logits.view(-1					,     self.num_labels							)					,     labels.view(-1							)							)

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

												if train_highway:
																	UpperCamelCase__     :List[str]							      =				(sum(highway_losses[:-1]							),) + outputs
																	# exclude the final highway, of course
												else:
																	UpperCamelCase__     :Any							      =				(loss,) + outputs
							if not self.training:
												UpperCamelCase__     :List[Any]							      =				outputs + ((original_entropy, highway_entropy), exit_layer)
												if output_layer >= 0:
																	UpperCamelCase__     :Optional[int]							      =				(
																	    (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)



'''simple docstring'''
import json
import logging
import os
import sys
from time import time
from unittest.mock import patch

from transformers.testing_utils import TestCasePlus, require_torch_tpu


logging.basicConfig(level=logging.DEBUG)

__snake_case							   =  logging.getLogger()


def     a   (    __a     )						->			Dict:



					'''simple docstring'''






					UpperCamelCase__     :str							      =				{}
					UpperCamelCase__     :Dict							      =				os.path.join(__a				,      '''all_results.json'''     )
					if os.path.exists(__a     ):
										with open(__a				,      '''r'''     ) as f:
															UpperCamelCase__     :int							      =				json.load(__a     )
					else:
										raise ValueError(f'''can\'t find {path}'''     )
					return results


__snake_case							   =  logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)







@require_torch_tpu
class      lowercase			(							A__      ):

		"""simple docstring"""

		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							import xla_spawn

							UpperCamelCase__     :Any							      =				self.get_auto_remove_tmp_dir()
							UpperCamelCase__     :List[str]							      =				F'''
            ./examples/pytorch/text-classification/run_glue.py
            --num_cores=8
            ./examples/pytorch/text-classification/run_glue.py
            --model_name_or_path distilbert-base-uncased
            --output_dir {tmp_dir}
            --overwrite_output_dir
            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv
            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv
            --do_train
            --do_eval
            --debug tpu_metrics_debug
            --per_device_train_batch_size=2
            --per_device_eval_batch_size=1
            --learning_rate=1e-4
            --max_steps=10
            --warmup_steps=2
            --seed=42
            --max_seq_length=128
            '''.split()

							with patch.object(UpperCamelCase_					,     '''argv'''					,     UpperCamelCase_							):
												UpperCamelCase__     :List[Any]							      =				time()
												xla_spawn.main()
												UpperCamelCase__     :List[Any]							      =				time()

												UpperCamelCase__     :Tuple							      =				get_results(UpperCamelCase_							)
												self.assertGreaterEqual(result['''eval_accuracy''']					,     0.75							)

												# Assert that the script takes less than 500 seconds to make sure it doesn't hang.
												self.assertLess(end - start					,     500							)




		def 					lowerCAmelCase__       (	self							):

							'''simple docstring'''


							import xla_spawn

							UpperCamelCase__     :Tuple							      =				'''
            ./tests/test_trainer_tpu.py
            --num_cores=8
            ./tests/test_trainer_tpu.py
            '''.split()
							with patch.object(UpperCamelCase_					,     '''argv'''					,     UpperCamelCase_							):
												xla_spawn.main()