






"""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 				snake_case      (   A__						):
			UpperCAmelCase_     : Tuple			     =					torch.exp(A__						)
			UpperCAmelCase_     : str			     =					torch.sum(A__	,dim=1						)  # sum of exp(x_i)
			UpperCAmelCase_     : Optional[int]			     =					torch.sum(x * exp_x	,dim=1						)  # sum of x_i * exp(x_i)
			return torch.log(A__						) - B / A







class 			UpperCamelCase_       (nn.Module     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: Dict						)						->			Union[str, Any]:
				super().__init__()
				UpperCAmelCase_     : int			     =					config.output_attentions
				UpperCAmelCase_     : int			     =					config.output_hidden_states
				UpperCAmelCase_     : Dict			     =					nn.ModuleList([BertLayer(lowerCAmelCase_						) for _ in range(config.num_hidden_layers						)]						)
				UpperCAmelCase_     : Tuple			     =					nn.ModuleList([BertHighway(lowerCAmelCase_						) for _ in range(config.num_hidden_layers						)]						)

				UpperCAmelCase_     : List[Any]			     =					[-1 for _ in range(config.num_hidden_layers						)]





	def      _SCREAMING_SNAKE_CASE      (      self					: str	,	lowerCAmelCase_					: Any						)						->			Dict:
				if (type(lowerCAmelCase_						) is float) or (type(lowerCAmelCase_						) is int):
							for i in range(len(self.early_exit_entropy						)						):
										UpperCAmelCase_     : Dict			     =					x
				else:
							UpperCAmelCase_     : Any			     =					x





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Tuple						)						->			Tuple:
				UpperCAmelCase_     : Tuple			     =					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					: List[str]	,	lowerCAmelCase_					: Union[str, Any]	,	lowerCAmelCase_					: List[Any]=None	,	lowerCAmelCase_					: Optional[int]=None	,	lowerCAmelCase_					: Tuple=None	,	lowerCAmelCase_					: Tuple=None	,	)						->			str:
				UpperCAmelCase_     : Tuple			     =					()
				UpperCAmelCase_     : Tuple			     =					()
				UpperCAmelCase_     : int			     =					()
				for i, layer_module in enumerate(self.layer						):
							if self.output_hidden_states:
										UpperCAmelCase_     : List[str]			     =					all_hidden_states + (hidden_states,)

							UpperCAmelCase_     : int			     =					layer_module(
							    lowerCAmelCase_	,	lowerCAmelCase_	,	head_mask[i]	,	lowerCAmelCase_	,	lowerCAmelCase_						)
							UpperCAmelCase_     : Optional[Any]			     =					layer_outputs[0]

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

							UpperCAmelCase_     : Union[str, Any]			     =					(hidden_states,)
							if self.output_hidden_states:
										UpperCAmelCase_     : List[Any]			     =					current_outputs + (all_hidden_states,)
							if self.output_attentions:
										UpperCAmelCase_     : Tuple			     =					current_outputs + (all_attentions,)

							UpperCAmelCase_     : int			     =					self.highway[i](lowerCAmelCase_						)
							# logits, pooled_output

							if not self.training:
										UpperCAmelCase_     : int			     =					highway_exit[0]
										UpperCAmelCase_     : Dict			     =					entropy(lowerCAmelCase_						)
										UpperCAmelCase_     : List[str]			     =					highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
										UpperCAmelCase_     : List[str]			     =					all_highway_exits + (highway_exit,)

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

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

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

				UpperCAmelCase_     : List[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 			UpperCamelCase_       (__A     ):





	def __init__(      self					: Tuple	,	lowerCAmelCase_					: Optional[int]						)						->			List[str]:
				super().__init__(lowerCAmelCase_						)
				UpperCAmelCase_     : int			     =					config

				UpperCAmelCase_     : Optional[int]			     =					BertEmbeddings(lowerCAmelCase_						)
				UpperCAmelCase_     : List[Any]			     =					DeeBertEncoder(lowerCAmelCase_						)
				UpperCAmelCase_     : Dict			     =					BertPooler(lowerCAmelCase_						)

				self.init_weights()





	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple						)						->			Dict:
				self.encoder.init_highway_pooler(self.pooler						)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[Any]						)						->			List[Any]:
				return self.embeddings.word_embeddings





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[Any]	,	lowerCAmelCase_					: List[Any]						)						->			Any:
				UpperCAmelCase_     : Optional[Any]			     =					value





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]	,	lowerCAmelCase_					: Optional[int]						)						->			List[Any]:
				for layer, heads in heads_to_prune.items():
							self.encoder.layer[layer].attention.prune_heads(lowerCAmelCase_						)





	@add_start_docstrings_to_model_forward(lowerCAmelCase_						)
	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple	,	lowerCAmelCase_					: int=None	,	lowerCAmelCase_					: List[Any]=None	,	lowerCAmelCase_					: Optional[int]=None	,	lowerCAmelCase_					: str=None	,	lowerCAmelCase_					: str=None	,	lowerCAmelCase_					: Any=None	,	lowerCAmelCase_					: Any=None	,	lowerCAmelCase_					: int=None	,	)						->			Optional[int]:
				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_     : Optional[int]			     =					input_ids.size()
				elif inputs_embeds is not None:
							UpperCAmelCase_     : Tuple			     =					inputs_embeds.size()[:-1]
				else:
							raise ValueError("You have to specify either input_ids or inputs_embeds"						)

				UpperCAmelCase_     : Any			     =					input_ids.device if input_ids is not None else inputs_embeds.device

				if attention_mask is None:
							UpperCAmelCase_     : int			     =					torch.ones(lowerCAmelCase_	,	device=lowerCAmelCase_						)
				if encoder_attention_mask is None:
							UpperCAmelCase_     : Dict			     =					torch.ones(lowerCAmelCase_	,	device=lowerCAmelCase_						)
				if token_type_ids is None:
							UpperCAmelCase_     : Any			     =					torch.zeros(lowerCAmelCase_	,	dtype=torch.long	,	device=lowerCAmelCase_						)

				# 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(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)

				# 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_     : List[Any]			     =					encoder_attention_mask[:, None, :, :]
				if encoder_attention_mask.dim() == 2:
							UpperCAmelCase_     : List[Any]			     =					encoder_attention_mask[:, None, None, :]

				UpperCAmelCase_     : Tuple			     =					encoder_extended_attention_mask.to(
				    dtype=next(self.parameters()						).dtype						)  # fp16 compatibility
				UpperCAmelCase_     : Optional[Any]			     =					(1.0 - encoder_extended_attention_mask) * -1_0_0_0_0.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[Any]			     =					self.get_head_mask(lowerCAmelCase_	,	self.config.num_hidden_layers						)

				UpperCAmelCase_     : List[Any]			     =					self.embeddings(
				    input_ids=lowerCAmelCase_	,	position_ids=lowerCAmelCase_	,	token_type_ids=lowerCAmelCase_	,	inputs_embeds=lowerCAmelCase_						)
				UpperCAmelCase_     : str			     =					self.encoder(
				    lowerCAmelCase_	,	attention_mask=lowerCAmelCase_	,	head_mask=lowerCAmelCase_	,	encoder_hidden_states=lowerCAmelCase_	,	encoder_attention_mask=lowerCAmelCase_	,	)
				UpperCAmelCase_     : Any			     =					encoder_outputs[0]
				UpperCAmelCase_     : Dict			     =					self.pooler(lowerCAmelCase_						)

				UpperCAmelCase_     : Union[str, Any]			     =					(
				    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 			UpperCamelCase_       (__A     ):





	def __init__(      self					: List[str]	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: List[Any]						)						->			List[Any]:
				UpperCAmelCase_     : List[str]			     =					message
				UpperCAmelCase_     : Any			     =					exit_layer  # start from 1!







class 			UpperCamelCase_       (nn.Module     ):





	def __init__(      self					: str	,	lowerCAmelCase_					: Tuple						)						->			Dict:
				super().__init__()
				UpperCAmelCase_     : Optional[int]			     =					BertPooler(lowerCAmelCase_						)
				UpperCAmelCase_     : Union[str, Any]			     =					nn.Dropout(config.hidden_dropout_prob						)
				UpperCAmelCase_     : Tuple			     =					nn.Linear(config.hidden_size	,	config.num_labels						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[Any]	,	lowerCAmelCase_					: Optional[Any]						)						->			Optional[int]:
				# Pooler
				UpperCAmelCase_     : Optional[int]			     =					encoder_outputs[0]
				UpperCAmelCase_     : Any			     =					self.pooler(lowerCAmelCase_						)
				# "return" pooler_output

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

				# Dropout and classification
				UpperCAmelCase_     : Tuple			     =					bmodel_output[1]

				UpperCAmelCase_     : Union[str, Any]			     =					self.dropout(lowerCAmelCase_						)
				UpperCAmelCase_     : Optional[Any]			     =					self.classifier(lowerCAmelCase_						)

				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. '''				,						__A				,						)
class 			UpperCamelCase_       (__A     ):





	def __init__(      self					: List[Any]	,	lowerCAmelCase_					: List[str]						)						->			List[Any]:
				super().__init__(lowerCAmelCase_						)
				UpperCAmelCase_     : int			     =					config.num_labels
				UpperCAmelCase_     : List[Any]			     =					config.num_hidden_layers

				UpperCAmelCase_     : Dict			     =					DeeBertModel(lowerCAmelCase_						)
				UpperCAmelCase_     : Union[str, Any]			     =					nn.Dropout(config.hidden_dropout_prob						)
				UpperCAmelCase_     : Dict			     =					nn.Linear(config.hidden_size	,	self.config.num_labels						)

				self.init_weights()





	@add_start_docstrings_to_model_forward(lowerCAmelCase_						)
	def      _SCREAMING_SNAKE_CASE      (      self					: int	,	lowerCAmelCase_					: List[str]=None	,	lowerCAmelCase_					: Union[str, Any]=None	,	lowerCAmelCase_					: Tuple=None	,	lowerCAmelCase_					: List[str]=None	,	lowerCAmelCase_					: int=None	,	lowerCAmelCase_					: str=None	,	lowerCAmelCase_					: Optional[Any]=None	,	lowerCAmelCase_					: Optional[Any]=-1	,	lowerCAmelCase_					: List[str]=False	,	)						->			Tuple:
				UpperCAmelCase_     : Dict			     =					self.num_layers
				try:
							UpperCAmelCase_     : Union[str, Any]			     =					self.bert(
							    lowerCAmelCase_	,	attention_mask=lowerCAmelCase_	,	token_type_ids=lowerCAmelCase_	,	position_ids=lowerCAmelCase_	,	head_mask=lowerCAmelCase_	,	inputs_embeds=lowerCAmelCase_	,	)
							# sequence_output, pooled_output, (hidden_states), (attentions), highway exits

							UpperCAmelCase_     : Union[str, Any]			     =					outputs[1]

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

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

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

							if train_highway:
										UpperCAmelCase_     : List[str]			     =					(sum(highway_losses[:-1]						),) + outputs
										# exclude the final highway, of course
							else:
										UpperCAmelCase_     : Dict			     =					(loss,) + outputs
				if not self.training:
							UpperCAmelCase_     : Dict			     =					outputs + ((original_entropy, highway_entropy), exit_layer)
							if output_layer >= 0:
										UpperCAmelCase_     : Optional[Any]			     =					(
										    (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"""
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import flax
import jax.numpy as jnp
from jax import random

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .scheduling_utils_flax import FlaxSchedulerMixin







@flax.struct.dataclass
class 			UpperCamelCase_       :
	# setable values
	__magic_name__	      =				None
	__magic_name__	      =				None
	__magic_name__	      =				None  # sigma(t_i)





	@classmethod
	def      _SCREAMING_SNAKE_CASE      (      cls					: List[str]						)						->			Optional[Any]:
				return cls()







@dataclass
class 			UpperCamelCase_       (__A     ):
	__magic_name__	      =				42
	__magic_name__	      =				42
	__magic_name__	      =				42







class 			UpperCamelCase_       (__A				,						__A     ):





	@property
	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple						)						->			str:
				return True





	@register_to_config
	def __init__(      self					: List[str]	,	lowerCAmelCase_					: float = 0.0_2	,	lowerCAmelCase_					: float = 100	,	lowerCAmelCase_					: float = 1.0_0_7	,	lowerCAmelCase_					: float = 80	,	lowerCAmelCase_					: float = 0.0_5	,	lowerCAmelCase_					: float = 50	,	)						->			Union[str, Any]:
				pass





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]						)						->			Tuple:
				return KarrasVeSchedulerState.create()





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]	,	lowerCAmelCase_					: KarrasVeSchedulerState	,	lowerCAmelCase_					: int	,	lowerCAmelCase_					: Tuple = ()						)						->			KarrasVeSchedulerState:
				UpperCAmelCase_     : Dict			     =					jnp.arange(0	,	lowerCAmelCase_						)[::-1].copy()
				UpperCAmelCase_     : Dict			     =					[
				    (
				        self.config.sigma_max**2
				        * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
				    )
				    for i in timesteps
				]

				return state.replace(
				    num_inference_steps=lowerCAmelCase_	,	schedule=jnp.array(lowerCAmelCase_	,	dtype=jnp.floataa						)	,	timesteps=lowerCAmelCase_	,	)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]	,	lowerCAmelCase_					: KarrasVeSchedulerState	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: random.KeyArray	,	)						->			Tuple[jnp.ndarray, float]:
				if self.config.s_min <= sigma <= self.config.s_max:
							UpperCAmelCase_     : Any			     =					min(self.config.s_churn / state.num_inference_steps	,	2**0.5 - 1						)
				else:
							UpperCAmelCase_     : Optional[int]			     =					0

				# sample eps ~ N(0, S_noise^2 * I)
				UpperCAmelCase_     : List[Any]			     =					random.split(lowerCAmelCase_	,	num=1						)
				UpperCAmelCase_     : List[str]			     =					self.config.s_noise * random.normal(key=lowerCAmelCase_	,	shape=sample.shape						)
				UpperCAmelCase_     : Optional[Any]			     =					sigma + gamma * sigma
				UpperCAmelCase_     : Any			     =					sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)

				return sample_hat, sigma_hat





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]	,	lowerCAmelCase_					: KarrasVeSchedulerState	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: bool = True	,	)						->			Union[FlaxKarrasVeOutput, Tuple]:
				UpperCAmelCase_     : Union[str, Any]			     =					sample_hat + sigma_hat * model_output
				UpperCAmelCase_     : List[Any]			     =					(sample_hat - pred_original_sample) / sigma_hat
				UpperCAmelCase_     : Union[str, Any]			     =					sample_hat + (sigma_prev - sigma_hat) * derivative

				if not return_dict:
							return (sample_prev, derivative, state)

				return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase_	,	derivative=lowerCAmelCase_	,	state=lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]	,	lowerCAmelCase_					: KarrasVeSchedulerState	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: float	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: jnp.ndarray	,	lowerCAmelCase_					: bool = True	,	)						->			Union[FlaxKarrasVeOutput, Tuple]:
				UpperCAmelCase_     : str			     =					sample_prev + sigma_prev * model_output
				UpperCAmelCase_     : Any			     =					(sample_prev - pred_original_sample) / sigma_prev
				UpperCAmelCase_     : int			     =					sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)

				if not return_dict:
							return (sample_prev, derivative, state)

				return FlaxKarrasVeOutput(prev_sample=lowerCAmelCase_	,	derivative=lowerCAmelCase_	,	state=lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]	,	lowerCAmelCase_					: KarrasVeSchedulerState	,	lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: List[str]	,	lowerCAmelCase_					: Optional[Any]						)						->			Dict:
				raise NotImplementedError()



