




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 __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  torch.exp(_A  )
						lowerCAmelCase_      			=  torch.sum(_A ,  dim=1  )  # sum of exp(x_i)
						lowerCAmelCase_      			=  torch.sum(x * exp_x ,  dim=1  )  # sum of x_i * exp(x_i)
						return torch.log(_A  ) - B / A


class  A		(  nn.Module     ):



		def __init__(     self,	UpperCamelCase__   ):







								"""simple docstring"""



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

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



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



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



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



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







		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	):







								"""simple docstring"""



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

														lowerCAmelCase_      			=  layer_module(
														    UpperCamelCase__,	UpperCamelCase__,	head_mask[i],	UpperCamelCase__,	UpperCamelCase__   )
														lowerCAmelCase_      			=  layer_outputs[0]

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

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

														lowerCAmelCase_      			=  self.highway[i](UpperCamelCase__   )
														# logits, pooled_output

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

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

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

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

								lowerCAmelCase_      			=  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,	UpperCamelCase__   ):







								"""simple docstring"""



								super().__init__(UpperCamelCase__   )
								lowerCAmelCase_      			=  config

								lowerCAmelCase_      			=  BertEmbeddings(UpperCamelCase__   )
								lowerCAmelCase_      			=  DeeBertEncoder(UpperCamelCase__   )
								lowerCAmelCase_      			=  BertPooler(UpperCamelCase__   )

								self.init_weights()



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								self.encoder.init_highway_pooler(self.pooler   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								return self.embeddings.word_embeddings



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  value



		def        SCREAMING_SNAKE_CASE__			(     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        SCREAMING_SNAKE_CASE__			(     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:
														lowerCAmelCase_      			=  input_ids.size()
								elif inputs_embeds is not None:
														lowerCAmelCase_      			=  inputs_embeds.size()[:-1]
								else:
														raise ValueError('''You have to specify either input_ids or inputs_embeds'''   )

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

								if attention_mask is None:
														lowerCAmelCase_      			=  torch.ones(UpperCamelCase__,	device=UpperCamelCase__   )
								if encoder_attention_mask is None:
														lowerCAmelCase_      			=  torch.ones(UpperCamelCase__,	device=UpperCamelCase__   )
								if token_type_ids is None:
														lowerCAmelCase_      			=  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.
								lowerCAmelCase_      			=  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:
														lowerCAmelCase_      			=  encoder_attention_mask[:, None, :, :]
								if encoder_attention_mask.dim() == 2:
														lowerCAmelCase_      			=  encoder_attention_mask[:, None, None, :]

								lowerCAmelCase_      			=  encoder_extended_attention_mask.to(
								    dtype=next(self.parameters()   ).dtype   )  # fp16 compatibility
								lowerCAmelCase_      			=  (1.0 - encoder_extended_attention_mask) * -10_000.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]
								lowerCAmelCase_      			=  self.get_head_mask(UpperCamelCase__,	self.config.num_hidden_layers   )

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

								lowerCAmelCase_      			=  (
								    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,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  message
								lowerCAmelCase_      			=  exit_layer  # start from 1!







class  A		(  nn.Module     ):



		def __init__(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								super().__init__()
								lowerCAmelCase_      			=  BertPooler(UpperCamelCase__   )
								lowerCAmelCase_      			=  nn.Dropout(config.hidden_dropout_prob   )
								lowerCAmelCase_      			=  nn.Linear(config.hidden_size,	config.num_labels   )







		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  encoder_outputs[0]
								lowerCAmelCase_      			=  self.pooler(UpperCamelCase__   )
								# "return" pooler_output

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

								# Dropout and classification
								lowerCAmelCase_      			=  bmodel_output[1]

								lowerCAmelCase_      			=  self.dropout(UpperCamelCase__   )
								lowerCAmelCase_      			=  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. '      ,				__UpperCAmelCase      ,				)
class  A		(  __UpperCAmelCase     ):



		def __init__(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								super().__init__(UpperCamelCase__   )
								lowerCAmelCase_      			=  config.num_labels
								lowerCAmelCase_      			=  config.num_hidden_layers

								lowerCAmelCase_      			=  DeeBertModel(UpperCamelCase__   )
								lowerCAmelCase_      			=  nn.Dropout(config.hidden_dropout_prob   )
								lowerCAmelCase_      			=  nn.Linear(config.hidden_size,	self.config.num_labels   )

								self.init_weights()







		@add_start_docstrings_to_model_forward(UpperCamelCase__   )
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=None,	UpperCamelCase__=-1,	UpperCamelCase__=False,	):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.num_layers
								try:
														lowerCAmelCase_      			=  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

														lowerCAmelCase_      			=  outputs[1]

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

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

														# work with highway exits
														lowerCAmelCase_      			=  []
														for highway_exit in outputs[-1]:
																				lowerCAmelCase_      			=  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
																										lowerCAmelCase_      			=  MSELoss()
																										lowerCAmelCase_      			=  loss_fct(highway_logits.view(-1   ),	labels.view(-1   )   )
																				else:
																										lowerCAmelCase_      			=  CrossEntropyLoss()
																										lowerCAmelCase_      			=  loss_fct(highway_logits.view(-1,	self.num_labels   ),	labels.view(-1   )   )
																				highway_losses.append(UpperCamelCase__   )

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










import argparse
from collections import defaultdict

import yaml


_A     =			'''docs/source/en/_toctree.yml'''





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  defaultdict(_A  )
						for doc in model_doc:
												counts[doc["local"]] += 1
						lowerCAmelCase_      			=  [key for key, value in counts.items() if value > 1]

						lowerCAmelCase_      			=  []
						for duplicate_key in duplicates:
												lowerCAmelCase_      			=  list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key}  )
												if len(_A  ) > 1:
																		raise ValueError(
																		    f"{duplicate_key} is present several times in the documentation table of content at "
																		    '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '''
																		    '''others.'''  )
												# Only add this once
												new_doc.append({'''local''': duplicate_key, '''title''': titles[0]}  )

						# Add none duplicate-keys
						new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1]  )

						# Sort
						return sorted(_A ,  key=lambda _A  : s["title"].lower()  )





def __UpperCamelCase			(       _A=False  ):
						with open(_A ,  encoding='''utf-8'''  ) as f:
												lowerCAmelCase_      			=  yaml.safe_load(f.read()  )

						# Get to the API doc
						lowerCAmelCase_      			=  0
						while content[api_idx]["title"] != "API":
												api_idx += 1
						lowerCAmelCase_      			=  content[api_idx]['''sections''']

						# Then to the model doc
						lowerCAmelCase_      			=  0
						while api_doc[model_idx]["title"] != "Models":
												model_idx += 1

						lowerCAmelCase_      			=  api_doc[model_idx]['''sections''']

						lowerCAmelCase_      			=  [(idx, section) for idx, section in enumerate(_A  ) if '''sections''' in section]
						lowerCAmelCase_      			=  False
						for idx, modality_doc in modalities_docs:
												lowerCAmelCase_      			=  modality_doc['''sections''']
												lowerCAmelCase_      			=  clean_model_doc_toc(_A  )

												if old_modality_doc != new_modality_doc:
																		lowerCAmelCase_      			=  True
																		if overwrite:
																								lowerCAmelCase_      			=  new_modality_doc

						if diff:
												if overwrite:
																		lowerCAmelCase_      			=  model_doc
																		lowerCAmelCase_      			=  api_doc
																		with open(_A ,  '''w''' ,  encoding='''utf-8'''  ) as f:
																								f.write(yaml.dump(_A ,  allow_unicode=_A  )  )
												else:
																		raise ValueError(
																		    '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.'''  )


if __name__ == "__main__":
						_A     =			argparse.ArgumentParser()
						parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''')
						_A     =			parser.parse_args()

						check_model_doc(args.fix_and_overwrite)




