



import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


_snake_case						=    logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt")






def 							A							(   _lowerCamelCase							,					_lowerCamelCase							,					_lowerCamelCase = 16_000    ):





							'''simple docstring'''




							_lowerCAmelCase	:				Optional[Any]					  =       int(round(sample_rate * max_length    )    )
							if len(_A    ) <= sample_length:
														return wav
							_lowerCAmelCase	:				Any					  =       randint(0							,					len(_A    ) - sample_length - 1    )
							return wav[random_offset : random_offset + sample_length]



@dataclass
class     UpperCAmelCase_       :
							lowerCamelCase__       =						field(default=UpperCAmelCase__  ,   metadata={'help': 'Name of a dataset from the datasets package'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'A file containing the training audio paths and labels.'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'A file containing the validation audio paths and labels.'})
							lowerCamelCase__       =						field(
							    default='train'  ,   metadata={
							        'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
							    }  ,   )
							lowerCamelCase__       =						field(
							    default='validation'  ,   metadata={
							        'help': (
							            'The name of the training data set split to use (via the datasets library). Defaults to \'validation\''
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default='audio'  ,   metadata={'help': 'The name of the dataset column containing the audio data. Defaults to \'audio\''}  ,   )
							lowerCamelCase__       =						field(
							    default='label'  ,   metadata={'help': 'The name of the dataset column containing the labels. Defaults to \'label\''})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={
							        'help': (
							            'For debugging purposes or quicker training, truncate the number of training examples to this '
							            'value if set.'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={
							        'help': (
							            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
							            'value if set.'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default=20  ,   metadata={'help': 'Audio clips will be randomly cut to this length during training if the value is set.'}  ,   )



@dataclass
class     UpperCAmelCase_       :
							lowerCamelCase__       =						field(
							    default='facebook/wav2vec2-base'  ,   metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}  ,   )
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Pretrained config name or path if not the same as model_name'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Where do you want to store the pretrained models downloaded from the Hub'})
							lowerCamelCase__       =						field(
							    default='main'  ,   metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}  ,   )
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Name or path of preprocessor config.'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Whether to freeze the feature encoder layers of the model.'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Whether to generate an attention mask in the feature extractor.'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={
							        'help': (
							            'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
							            'with private models).'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Whether to freeze the feature extractor layers of the model.'})
							lowerCamelCase__       =						field(
							    default=UpperCAmelCase__  ,   metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}  ,   )







							def   snake_case__ (  self):

														'''simple docstring'''

														if not self.freeze_feature_extractor and self.freeze_feature_encoder:
																					warnings.warn(
																					    "The argument `--freeze_feature_extractor` is deprecated and "
																					    "will be removed in a future version. Use `--freeze_feature_encoder`"
																					    "instead. Setting `freeze_feature_encoder==True`.",     __lowercase,     )
														if self.freeze_feature_extractor and not self.freeze_feature_encoder:
																					raise ValueError(
																					    "The argument `--freeze_feature_extractor` is deprecated and "
																					    "should not be used in combination with `--freeze_feature_encoder`."
																					    "Only make use of `--freeze_feature_encoder`.")






def 							A							(   ):





							'''simple docstring'''




							_lowerCAmelCase	:				int					  =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
							if len(sys.argv    ) == 2 and sys.argv[1].endswith(".json"    ):
														# If we pass only one argument to the script and it's the path to a json file,
														# let's parse it to get our arguments.
														_lowerCAmelCase  ,       _lowerCAmelCase  ,       _lowerCAmelCase	:				Optional[Any]					  =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]    )    )
							else:
														_lowerCAmelCase  ,       _lowerCAmelCase  ,       _lowerCAmelCase	:				Any					  =       parser.parse_args_into_dataclasses()

							# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
							# information sent is the one passed as arguments along with your Python/PyTorch versions.
							send_example_telemetry("run_audio_classification"							,					_A							,					_A    )

							# Setup logging
							logging.basicConfig(
							    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"							,					datefmt="%m/%d/%Y %H:%M:%S"							,					handlers=[logging.StreamHandler(sys.stdout    )]							,					)

							if training_args.should_log:
														# The default of training_args.log_level is passive, so we set log level at info here to have that default.
														transformers.utils.logging.set_verbosity_info()

							_lowerCAmelCase	:				Tuple					  =       training_args.get_process_log_level()
							logger.setLevel(_A    )
							transformers.utils.logging.set_verbosity(_A    )
							transformers.utils.logging.enable_default_handler()
							transformers.utils.logging.enable_explicit_format()

							# Log on each process the small summary:
							logger.warning(
							    F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} "
							    + F"distributed training: {bool(training_args.local_rank != -1    )}, 16-bits training: {training_args.fpaa}"    )
							logger.info(F"Training/evaluation parameters {training_args}"    )

							# Set seed before initializing model.
							set_seed(training_args.seed    )

							# Detecting last checkpoint.
							_lowerCAmelCase	:				Union[str, Any]					  =       None
							if os.path.isdir(training_args.output_dir    ) and training_args.do_train and not training_args.overwrite_output_dir:
														_lowerCAmelCase	:				Any					  =       get_last_checkpoint(training_args.output_dir    )
														if last_checkpoint is None and len(os.listdir(training_args.output_dir    )    ) > 0:
																					raise ValueError(
																					    F"Output directory ({training_args.output_dir}) already exists and is not empty. "
																					    "Use --overwrite_output_dir to train from scratch."    )
														elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																					logger.info(
																					    F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
																					    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."    )

    # Initialize our dataset and prepare it for the audio classification task.
							_lowerCAmelCase	:				Dict					  =       DatasetDict()
							_lowerCAmelCase	:				Tuple					  =       load_dataset(
							    data_args.dataset_name							,					data_args.dataset_config_name							,					split=data_args.train_split_name							,					use_auth_token=True if model_args.use_auth_token else None							,					)
							_lowerCAmelCase	:				List[str]					  =       load_dataset(
							    data_args.dataset_name							,					data_args.dataset_config_name							,					split=data_args.eval_split_name							,					use_auth_token=True if model_args.use_auth_token else None							,					)

							if data_args.audio_column_name not in raw_datasets["train"].column_names:
														raise ValueError(
														    F"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
														    "Make sure to set `--audio_column_name` to the correct audio column - one of "
														    F"{', '.join(raw_datasets['train'].column_names    )}."    )

							if data_args.label_column_name not in raw_datasets["train"].column_names:
														raise ValueError(
														    F"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
														    "Make sure to set `--label_column_name` to the correct text column - one of "
														    F"{', '.join(raw_datasets['train'].column_names    )}."    )

							# Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
							# transformer outputs in the classifier, but it doesn't always lead to better accuracy
							_lowerCAmelCase	:				str					  =       AutoFeatureExtractor.from_pretrained(
							    model_args.feature_extractor_name or model_args.model_name_or_path							,					return_attention_mask=model_args.attention_mask							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					)

							# `datasets` takes care of automatically loading and resampling the audio,
							# so we just need to set the correct target sampling rate.
							_lowerCAmelCase	:				Tuple					  =       raw_datasets.cast_column(
							    data_args.audio_column_name							,					datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate    )    )

							_lowerCAmelCase	:				Union[str, Any]					  =       feature_extractor.model_input_names[0]

							def train_transforms(_lowerCamelCase    ):
														_lowerCAmelCase	:				Dict					  =       []
														for audio in batch[data_args.audio_column_name]:
																					_lowerCAmelCase	:				Optional[int]					  =       random_subsample(
																					    audio["array"]							,					max_length=data_args.max_length_seconds							,					sample_rate=feature_extractor.sampling_rate    )
																					subsampled_wavs.append(_A    )
														_lowerCAmelCase	:				Optional[Any]					  =       feature_extractor(_A							,					sampling_rate=feature_extractor.sampling_rate    )
														_lowerCAmelCase	:				Any					  =       {model_input_name: inputs.get(_A    )}
														_lowerCAmelCase	:				int					  =       list(batch[data_args.label_column_name]    )

														return output_batch

							def val_transforms(_lowerCamelCase    ):
														_lowerCAmelCase	:				Any					  =       [audio["array"] for audio in batch[data_args.audio_column_name]]
														_lowerCAmelCase	:				int					  =       feature_extractor(_A							,					sampling_rate=feature_extractor.sampling_rate    )
														_lowerCAmelCase	:				Optional[Any]					  =       {model_input_name: inputs.get(_A    )}
														_lowerCAmelCase	:				List[str]					  =       list(batch[data_args.label_column_name]    )

														return output_batch

							# Prepare label mappings.
							# We'll include these in the model's config to get human readable labels in the Inference API.
							_lowerCAmelCase	:				List[Any]					  =       raw_datasets["train"].features[data_args.label_column_name].names
							_lowerCAmelCase  ,       _lowerCAmelCase	:				Union[str, Any]					  =       {}, {}
							for i, label in enumerate(_A    ):
														_lowerCAmelCase	:				Optional[Any]					  =       str(_A    )
														_lowerCAmelCase	:				int					  =       label

							# Load the accuracy metric from the datasets package
							_lowerCAmelCase	:				Tuple					  =       evaluate.load("accuracy"    )

							# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
							# `predictions` and `label_ids` fields) and has to return a dictionary string to float.
							def compute_metrics(_lowerCamelCase    ):
														_lowerCAmelCase	:				Union[str, Any]					  =       np.argmax(eval_pred.predictions							,					axis=1    )
														return metric.compute(predictions=_A							,					references=eval_pred.label_ids    )

							_lowerCAmelCase	:				Any					  =       AutoConfig.from_pretrained(
							    model_args.config_name or model_args.model_name_or_path							,					num_labels=len(_A    )							,					labelaid=_A							,					idalabel=_A							,					finetuning_task="audio-classification"							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					)
							_lowerCAmelCase	:				List[Any]					  =       AutoModelForAudioClassification.from_pretrained(
							    model_args.model_name_or_path							,					from_tf=bool(".ckpt" in model_args.model_name_or_path    )							,					config=_A							,					cache_dir=model_args.cache_dir							,					revision=model_args.model_revision							,					use_auth_token=True if model_args.use_auth_token else None							,					ignore_mismatched_sizes=model_args.ignore_mismatched_sizes							,					)

							# freeze the convolutional waveform encoder
							if model_args.freeze_feature_encoder:
														model.freeze_feature_encoder()

							if training_args.do_train:
														if data_args.max_train_samples is not None:
																					_lowerCAmelCase	:				str					  =       (
																					    raw_datasets["train"].shuffle(seed=training_args.seed    ).select(range(data_args.max_train_samples    )    )
																					)
														# Set the training transforms
														raw_datasets["train"].set_transform(_A							,					output_all_columns=_A    )

							if training_args.do_eval:
														if data_args.max_eval_samples is not None:
																					_lowerCAmelCase	:				str					  =       (
																					    raw_datasets["eval"].shuffle(seed=training_args.seed    ).select(range(data_args.max_eval_samples    )    )
																					)
														# Set the validation transforms
														raw_datasets["eval"].set_transform(_A							,					output_all_columns=_A    )

							# Initialize our trainer
							_lowerCAmelCase	:				List[str]					  =       Trainer(
							    model=_A							,					args=_A							,					train_dataset=raw_datasets["train"] if training_args.do_train else None							,					eval_dataset=raw_datasets["eval"] if training_args.do_eval else None							,					compute_metrics=_A							,					tokenizer=_A							,					)

							# Training
							if training_args.do_train:
														_lowerCAmelCase	:				Tuple					  =       None
														if training_args.resume_from_checkpoint is not None:
																					_lowerCAmelCase	:				Tuple					  =       training_args.resume_from_checkpoint
														elif last_checkpoint is not None:
																					_lowerCAmelCase	:				Optional[int]					  =       last_checkpoint
														_lowerCAmelCase	:				Optional[int]					  =       trainer.train(resume_from_checkpoint=_A    )
														trainer.save_model()
														trainer.log_metrics("train"							,					train_result.metrics    )
														trainer.save_metrics("train"							,					train_result.metrics    )
														trainer.save_state()

							# Evaluation
							if training_args.do_eval:
														_lowerCAmelCase	:				List[str]					  =       trainer.evaluate()
														trainer.log_metrics("eval"							,					_A    )
														trainer.save_metrics("eval"							,					_A    )

							# Write model card and (optionally) push to hub
							_lowerCAmelCase	:				Any					  =       {
							    "finetuned_from": model_args.model_name_or_path,
							    "tasks": "audio-classification",
							    "dataset": data_args.dataset_name,
							    "tags": ["audio-classification"],
							}
							if training_args.push_to_hub:
														trainer.push_to_hub(**_A    )
							else:
														trainer.create_model_card(**_A    )


if __name__ == "__main__":
						main()






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 		lowerCamelCase__       (						_A				):







	'''simple docstring'''





	snake_case_						       =	torch.exp(_A				)
	snake_case_						       =	torch.sum(_A	,      dim=1				)  # sum of exp(x_i)
	snake_case_						       =	torch.sum(x * exp_x	,      dim=1				)  # sum of x_i * exp(x_i)
	return torch.log(_A				) - B / A
class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





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






							"""simple docstring"""






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

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






						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	Optional[int]		):






							"""simple docstring"""






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






						def 			snake_case__		(		self				:	int			,      __lowercase				:	Tuple		):






							"""simple docstring"""






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






						def 			snake_case__		(		self				:	List[Any]			,      __lowercase				:	List[str]			,      __lowercase				:	List[Any]=None			,      __lowercase				:	Optional[int]=None			,      __lowercase				:	Optional[Any]=None			,      __lowercase				:	List[str]=None			,      ):






							"""simple docstring"""






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

								snake_case_						       =	layer_module(
								    __lowercase			,      __lowercase			,      head_mask[i]			,      __lowercase			,      __lowercase		)
								snake_case_						       =	layer_outputs[0]

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

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

								snake_case_						       =	self.highway[i](__lowercase		)
								# logits, pooled_output

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

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

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

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

							snake_case_						       =	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 						UpperCAmelCase  (							UpperCAmelCase__     ):







						'''simple docstring'''





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






							"""simple docstring"""






							super().__init__(__lowercase		)
							snake_case_						       =	config

							snake_case_						       =	BertEmbeddings(__lowercase		)
							snake_case_						       =	DeeBertEncoder(__lowercase		)
							snake_case_						       =	BertPooler(__lowercase		)

							self.init_weights()






						def 			snake_case__		(		self				:	Tuple		):






							"""simple docstring"""






							self.encoder.init_highway_pooler(self.pooler		)






						def 			snake_case__		(		self				:	Tuple		):






							"""simple docstring"""






							return self.embeddings.word_embeddings






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	Any		):






							"""simple docstring"""






							snake_case_						       =	value






						def 			snake_case__		(		self				:	List[Any]			,      __lowercase				:	Optional[int]		):






							"""simple docstring"""






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






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

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

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

							# 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.
							snake_case_						       =	self.get_extended_attention_mask(__lowercase			,      __lowercase			,      __lowercase		)

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

							snake_case_						       =	encoder_extended_attention_mask.to(
							    dtype=next(self.parameters()		).dtype		)  # fp16 compatibility
							snake_case_						       =	(1.0 - encoder_extended_attention_mask) * -1_0000.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]
							snake_case_						       =	self.get_head_mask(__lowercase			,      self.config.num_hidden_layers		)

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

							snake_case_						       =	(
							    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  (							UpperCAmelCase__     ):







						'''simple docstring'''





						def __init__(		self				:	Dict			,      __lowercase				:	Tuple			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	message
							snake_case_						       =	exit_layer  # start from 1!







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	int			,      __lowercase				:	Optional[int]		):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	BertPooler(__lowercase		)
							snake_case_						       =	nn.Dropout(config.hidden_dropout_prob		)
							snake_case_						       =	nn.Linear(config.hidden_size			,      config.num_labels		)






						def 			snake_case__		(		self				:	List[str]			,      __lowercase				:	str		):






							"""simple docstring"""






							snake_case_						       =	encoder_outputs[0]
							snake_case_						       =	self.pooler(__lowercase		)
							# "return" pooler_output

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

							# Dropout and classification
							snake_case_						       =	bmodel_output[1]

							snake_case_						       =	self.dropout(__lowercase		)
							snake_case_						       =	self.classifier(__lowercase		)

							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 						UpperCAmelCase  (							UpperCAmelCase__     ):







						'''simple docstring'''





						def __init__(		self				:	Union[str, Any]			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							super().__init__(__lowercase		)
							snake_case_						       =	config.num_labels
							snake_case_						       =	config.num_hidden_layers

							snake_case_						       =	DeeBertModel(__lowercase		)
							snake_case_						       =	nn.Dropout(config.hidden_dropout_prob		)
							snake_case_						       =	nn.Linear(config.hidden_size			,      self.config.num_labels		)

							self.init_weights()






						@add_start_docstrings_to_model_forward(__lowercase		)
						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	List[Any]=None			,      __lowercase				:	Dict=None			,      __lowercase				:	Optional[Any]=None			,      __lowercase				:	Optional[int]=None			,      __lowercase				:	List[Any]=None			,      __lowercase				:	Tuple=None			,      __lowercase				:	List[str]=None			,      __lowercase				:	int=-1			,      __lowercase				:	Tuple=False			,      ):






							"""simple docstring"""






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

								snake_case_						       =	outputs[1]

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

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

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

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