


'''simple docstring'''

from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


_UpperCAmelCase					:			str				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			Union[str, Any]				     =					{
    """facebook/blenderbot-3B""": """https://huggingface.co/facebook/blenderbot-3B/resolve/main/config.json""",
    # See all Blenderbot models at https://huggingface.co/models?filter=blenderbot
}


class    a__					(			__A   ):







				"""simple docstring"""



				__UpperCamelCase     :		Optional[Any]						=						'blenderbot'
				__UpperCamelCase     :		Any						=						['past_key_values']
				__UpperCamelCase     :		List[Any]						=						{'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}




				def __init__(self							,      __lowercase=80_08							,      __lowercase=1_28							,      __lowercase=2							,      __lowercase=1_02_40							,      __lowercase=32							,      __lowercase=24							,      __lowercase=1_02_40							,      __lowercase=32							,      __lowercase=0.0							,      __lowercase=0.0							,      __lowercase=True							,      __lowercase=True							,      __lowercase="gelu"							,      __lowercase=25_60							,      __lowercase=0.1							,      __lowercase=0.0							,      __lowercase=0.0							,      __lowercase=0.0_2							,      __lowercase=1							,      __lowercase=False							,      __lowercase=0							,      __lowercase=1							,      __lowercase=2							,      __lowercase=3							,      __lowercase=2							,      **__lowercase							,      ):
										__lowerCAmelCase											=					vocab_size
										__lowerCAmelCase											=					max_position_embeddings
										__lowerCAmelCase											=					d_model
										__lowerCAmelCase											=					encoder_ffn_dim
										__lowerCAmelCase											=					encoder_layers
										__lowerCAmelCase											=					encoder_attention_heads
										__lowerCAmelCase											=					decoder_ffn_dim
										__lowerCAmelCase											=					decoder_layers
										__lowerCAmelCase											=					decoder_attention_heads
										__lowerCAmelCase											=					dropout
										__lowerCAmelCase											=					attention_dropout
										__lowerCAmelCase											=					activation_dropout
										__lowerCAmelCase											=					activation_function
										__lowerCAmelCase											=					init_std
										__lowerCAmelCase											=					encoder_layerdrop
										__lowerCAmelCase											=					decoder_layerdrop
										__lowerCAmelCase											=					use_cache
										__lowerCAmelCase											=					encoder_layers
										__lowerCAmelCase											=					scale_embedding  # scale factor will be sqrt(d_model) if True

										super().__init__(
										    pad_token_id=__lowercase							,      bos_token_id=__lowercase							,      eos_token_id=__lowercase							,      is_encoder_decoder=__lowercase							,      decoder_start_token_id=__lowercase							,      encoder_no_repeat_ngram_size=__lowercase							,      forced_eos_token_id=__lowercase							,      **__lowercase							,      )


class    a__					(			__A   ):







				"""simple docstring"""



				@property
				def        _snake_case	(self		):
										if self.task in ["default", "seq2seq-lm"]:
																__lowerCAmelCase											=					OrderedDict(
																    [
																        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																    ]		)
																if self.use_past:
																						__lowerCAmelCase											=					{0: '''batch'''}
																						__lowerCAmelCase											=					{0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
																else:
																						__lowerCAmelCase											=					{0: '''batch''', 1: '''decoder_sequence'''}
																						__lowerCAmelCase											=					{0: '''batch''', 1: '''decoder_sequence'''}
																if self.use_past:
																						self.fill_with_past_key_values_(__lowercase							,      direction='''inputs'''		)
										elif self.task == "causal-lm":
																__lowerCAmelCase											=					OrderedDict(
																    [
																        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																    ]		)
																if self.use_past:
																						__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_layers
																						for i in range(__lowercase		):
																												__lowerCAmelCase											=					{0: '''batch''', 2: '''past_sequence + sequence'''}
																												__lowerCAmelCase											=					{0: '''batch''', 2: '''past_sequence + sequence'''}
										else:
																__lowerCAmelCase											=					OrderedDict(
																    [
																        ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
																        ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
																        ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}),
																        ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}),
																    ]		)

										return common_inputs




				@property
				# Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs
				def        _snake_case	(self		):
										if self.task in ["default", "seq2seq-lm"]:
																__lowerCAmelCase											=					super().outputs
										else:
																__lowerCAmelCase											=					super(__lowercase							,      self		).outputs
																if self.use_past:
																						__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_layers
																						for i in range(__lowercase		):
																												__lowerCAmelCase											=					{0: '''batch''', 2: '''past_sequence + sequence'''}
																												__lowerCAmelCase											=					{0: '''batch''', 2: '''past_sequence + sequence'''}
										return common_outputs




				def        _snake_case	(self							,      __lowercase							,      __lowercase = -1							,      __lowercase = -1							,      __lowercase = False							,      __lowercase = None							,      ):
										__lowerCAmelCase											=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    __lowercase							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)
										# Generate decoder inputs
										__lowerCAmelCase											=					seq_length if not self.use_past else 1
										__lowerCAmelCase											=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    __lowercase							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)
										__lowerCAmelCase											=					{F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
										__lowerCAmelCase											=					dict(**__lowercase							,      **__lowercase		)

										if self.use_past:
																if not is_torch_available():
																						raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''		)
																else:
																						import torch
																__lowerCAmelCase							,       __lowerCAmelCase											=					common_inputs['''input_ids'''].shape
																__lowerCAmelCase											=					common_inputs['''decoder_input_ids'''].shape[1]
																__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_attention_heads
																__lowerCAmelCase											=					(
																    batch,
																    num_encoder_attention_heads,
																    encoder_seq_length,
																    self._config.hidden_size // num_encoder_attention_heads,
																)
																__lowerCAmelCase											=					decoder_seq_length
																__lowerCAmelCase											=					(
																    batch,
																    num_decoder_attention_heads,
																    decoder_past_length,
																    self._config.hidden_size // num_decoder_attention_heads,
																)
																__lowerCAmelCase											=					torch.cat(
																    [common_inputs['''decoder_attention_mask'''], torch.ones(__lowercase							,      __lowercase		)]							,      dim=1		)
																__lowerCAmelCase											=					[]
																__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_layers

																for _ in range(__lowercase		):
																						common_inputs["past_key_values"].append(
																						    (
																						        torch.zeros(__lowercase		),
																						        torch.zeros(__lowercase		),
																						        torch.zeros(__lowercase		),
																						        torch.zeros(__lowercase		),
																						    )		)
										return common_inputs




				def        _snake_case	(self							,      __lowercase							,      __lowercase = -1							,      __lowercase = -1							,      __lowercase = False							,      __lowercase = None							,      ):
										__lowerCAmelCase											=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
										    __lowercase							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)

										if self.use_past:
																if not is_torch_available():
																						raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''		)
																else:
																						import torch
																__lowerCAmelCase							,       __lowerCAmelCase											=					common_inputs['''input_ids'''].shape
																__lowerCAmelCase											=					seqlen
																__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_layers
																__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_attention_heads
																__lowerCAmelCase											=					(
																    batch,
																    num_encoder_attention_heads,
																    past_key_values_length,
																    self._config.hidden_size // num_encoder_attention_heads,
																)
																__lowerCAmelCase											=					common_inputs['''attention_mask'''].dtype
																__lowerCAmelCase											=					torch.cat(
																    [common_inputs['''attention_mask'''], torch.ones(__lowercase							,      __lowercase							,      dtype=__lowercase		)]							,      dim=1		)
																__lowerCAmelCase											=					[
																    (torch.zeros(__lowercase		), torch.zeros(__lowercase		)) for _ in range(__lowercase		)
																]
										return common_inputs




				def        _snake_case	(self							,      __lowercase							,      __lowercase = -1							,      __lowercase = -1							,      __lowercase = False							,      __lowercase = None							,      ):
										# Copied from OnnxConfig.generate_dummy_inputs
										# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
										# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
										__lowerCAmelCase											=					compute_effective_axis_dimension(
										    __lowercase							,      fixed_dimension=OnnxConfig.default_fixed_batch							,      num_token_to_add=0		)

										# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
										__lowerCAmelCase											=					tokenizer.num_special_tokens_to_add(__lowercase		)
										__lowerCAmelCase											=					compute_effective_axis_dimension(
										    __lowercase							,      fixed_dimension=OnnxConfig.default_fixed_sequence							,      num_token_to_add=__lowercase		)

										# Generate dummy inputs according to compute batch and sequence
										__lowerCAmelCase											=					[''' '''.join([tokenizer.unk_token]		) * seq_length] * batch_size
										__lowerCAmelCase											=					dict(tokenizer(__lowercase							,      return_tensors=__lowercase		)		)
										return common_inputs




				def        _snake_case	(self							,      __lowercase							,      __lowercase = -1							,      __lowercase = -1							,      __lowercase = False							,      __lowercase = None							,      ):
										if self.task in ["default", "seq2seq-lm"]:
																__lowerCAmelCase											=					self._generate_dummy_inputs_for_default_and_seqaseq_lm(
																    __lowercase							,      batch_size=__lowercase							,      seq_length=__lowercase							,      is_pair=__lowercase							,      framework=__lowercase		)

										elif self.task == "causal-lm":
																__lowerCAmelCase											=					self._generate_dummy_inputs_for_causal_lm(
																    __lowercase							,      batch_size=__lowercase							,      seq_length=__lowercase							,      is_pair=__lowercase							,      framework=__lowercase		)
										else:
																__lowerCAmelCase											=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
																    __lowercase							,      batch_size=__lowercase							,      seq_length=__lowercase							,      is_pair=__lowercase							,      framework=__lowercase		)

										return common_inputs




				def        _snake_case	(self							,      __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		):
										if self.task in ["default", "seq2seq-lm"]:
																__lowerCAmelCase											=					super()._flatten_past_key_values_(__lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)
										else:
																__lowerCAmelCase											=					super(__lowercase							,      self		)._flatten_past_key_values_(
																    __lowercase							,      __lowercase							,      __lowercase							,      __lowercase		)




				def        _snake_case	(self							,      __lowercase							,      __lowercase		):
										if direction not in ["inputs", "outputs"]:
																raise ValueError(F"""direction must either be \"inputs\" or \"outputs\", but {direction} was given"""		)

										__lowerCAmelCase											=					'''past_key_values''' if direction == '''inputs''' else '''present'''
										__lowerCAmelCase							,       __lowerCAmelCase											=					self.num_layers

										__lowerCAmelCase											=					'''past_encoder_sequence'''
										__lowerCAmelCase											=					'''past_decoder_sequence''' if direction == '''inputs''' else '''past_decoder_sequence + sequence'''

										for i in range(__lowercase		):
																__lowerCAmelCase											=					{0: '''batch''', 2: decoder_sequence}
																__lowerCAmelCase											=					{0: '''batch''', 2: decoder_sequence}
																__lowerCAmelCase											=					{0: '''batch''', 2: encoder_sequence}
																__lowerCAmelCase											=					{0: '''batch''', 2: encoder_sequence}





'''simple docstring'''

import logging

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.albert.modeling_albert import (
    ALBERT_INPUTS_DOCSTRING,
    ALBERT_START_DOCSTRING,
    AlbertModel,
    AlbertPreTrainedModel,
    AlbertTransformer,
)


_UpperCAmelCase					:			List[str]				     =					logging.getLogger(__name__)


class    a__					(			__A   ):







				"""simple docstring"""



				def        _snake_case	(self							,      __lowercase							,      __lowercase							,      __lowercase=None							,      __lowercase=None		):
										if current_layer == 0:
																__lowerCAmelCase											=					self.embedding_hidden_mapping_in(__lowercase		)
										else:
																__lowerCAmelCase											=					hidden_states[0]

										__lowerCAmelCase											=					int(self.config.num_hidden_layers / self.config.num_hidden_groups		)

										# Index of the hidden group
										__lowerCAmelCase											=					int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)		)

										__lowerCAmelCase											=					self.albert_layer_groups[group_idx](
										    __lowercase							,      __lowercase							,      head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group]							,      )
										__lowerCAmelCase											=					layer_group_output[0]

										return (hidden_states,)


@add_start_docstrings(
    'The bare ALBERT Model transformer with PABEE outputting raw hidden-states without any specific head on top.'				,    __A				,    )
class    a__					(			__A   ):







				"""simple docstring"""



				def __init__(self							,      __lowercase		):
										super().__init__(__lowercase		)

										__lowerCAmelCase											=					AlbertTransformerWithPabee(__lowercase		)

										self.init_weights()
										__lowerCAmelCase											=					0
										__lowerCAmelCase											=					0
										__lowerCAmelCase											=					0

										__lowerCAmelCase											=					0




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					threshold




				def        _snake_case	(self							,      __lowercase		):
										__lowerCAmelCase											=					patience




				def        _snake_case	(self		):
										__lowerCAmelCase											=					0
										__lowerCAmelCase											=					0




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.inference_layers_num / self.inference_instances_num
										__lowerCAmelCase											=					(
										    F"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ="""
										    F""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***"""
										)
										print(__lowercase		)




				@add_start_docstrings_to_model_forward(__lowercase		)
				def        _snake_case	(self							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=False							,      ):

										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(__lowercase							,      device=__lowercase		)
										if token_type_ids is None:
																__lowerCAmelCase											=					torch.zeros(__lowercase							,      dtype=torch.long							,      device=__lowercase		)

										__lowerCAmelCase											=					attention_mask.unsqueeze(1		).unsqueeze(2		)
										__lowerCAmelCase											=					extended_attention_mask.to(dtype=self.dtype		)  # fp16 compatibility
										__lowerCAmelCase											=					(1.0 - extended_attention_mask) * -1_0_0_0_0.0
										__lowerCAmelCase											=					self.get_head_mask(__lowercase							,      self.config.num_hidden_layers		)

										__lowerCAmelCase											=					self.embeddings(
										    __lowercase							,      position_ids=__lowercase							,      token_type_ids=__lowercase							,      inputs_embeds=__lowercase		)
										__lowerCAmelCase											=					embedding_output

										if self.training:
																__lowerCAmelCase											=					[]
																for i in range(self.config.num_hidden_layers		):
																						__lowerCAmelCase											=					self.encoder.adaptive_forward(
																						    __lowercase							,      current_layer=__lowercase							,      attention_mask=__lowercase							,      head_mask=__lowercase							,      )

																						__lowerCAmelCase											=					self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																						__lowerCAmelCase											=					output_layers[i](output_dropout(__lowercase		)		)
																						res.append(__lowercase		)
										elif self.patience == 0:  # Use all layers for inference
																__lowerCAmelCase											=					self.encoder(__lowercase							,      __lowercase							,      head_mask=__lowercase		)
																__lowerCAmelCase											=					self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																__lowerCAmelCase											=					[output_layers[self.config.num_hidden_layers - 1](__lowercase		)]
										else:
																__lowerCAmelCase											=					0
																__lowerCAmelCase											=					None
																__lowerCAmelCase											=					0
																for i in range(self.config.num_hidden_layers		):
																						calculated_layer_num += 1
																						__lowerCAmelCase											=					self.encoder.adaptive_forward(
																						    __lowercase							,      current_layer=__lowercase							,      attention_mask=__lowercase							,      head_mask=__lowercase							,      )

																						__lowerCAmelCase											=					self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																						__lowerCAmelCase											=					output_layers[i](__lowercase		)
																						if regression:
																												__lowerCAmelCase											=					logits.detach()
																												if patient_result is not None:
																																		__lowerCAmelCase											=					patient_result.detach()
																												if (patient_result is not None) and torch.abs(patient_result - labels		) < self.regression_threshold:
																																		patient_counter += 1
																												else:
																																		__lowerCAmelCase											=					0
																						else:
																												__lowerCAmelCase											=					logits.detach().argmax(dim=1		)
																												if patient_result is not None:
																																		__lowerCAmelCase											=					patient_result.detach().argmax(dim=1		)
																												if (patient_result is not None) and torch.all(labels.eq(__lowercase		)		):
																																		patient_counter += 1
																												else:
																																		__lowerCAmelCase											=					0

																						__lowerCAmelCase											=					logits
																						if patient_counter == self.patience:
																												break
																__lowerCAmelCase											=					[patient_result]
																self.inference_layers_num += calculated_layer_num
																self.inference_instances_num += 1

										return res


@add_start_docstrings(
    'Albert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n    the pooled output) e.g. for GLUE tasks. '				,    __A				,    )
class    a__					(			__A   ):







				"""simple docstring"""



				def __init__(self							,      __lowercase		):
										super().__init__(__lowercase		)
										__lowerCAmelCase											=					config.num_labels

										__lowerCAmelCase											=					AlbertModelWithPabee(__lowercase		)
										__lowerCAmelCase											=					nn.Dropout(config.classifier_dropout_prob		)
										__lowerCAmelCase											=					nn.ModuleList(
										    [nn.Linear(config.hidden_size							,      self.config.num_labels		) for _ in range(config.num_hidden_layers		)]		)

										self.init_weights()




				@add_start_docstrings_to_model_forward(__lowercase		)
				def        _snake_case	(self							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      __lowercase=None							,      ):
										__lowerCAmelCase											=					self.albert(
										    input_ids=__lowercase							,      attention_mask=__lowercase							,      token_type_ids=__lowercase							,      position_ids=__lowercase							,      head_mask=__lowercase							,      inputs_embeds=__lowercase							,      output_dropout=self.dropout							,      output_layers=self.classifiers							,      regression=self.num_labels == 1							,      )

										__lowerCAmelCase											=					(logits[-1],)

										if labels is not None:
																__lowerCAmelCase											=					None
																__lowerCAmelCase											=					0
																for ix, logits_item in enumerate(__lowercase		):
																						if self.num_labels == 1:
																												#  We are doing regression
																												__lowerCAmelCase											=					MSELoss()
																												__lowerCAmelCase											=					loss_fct(logits_item.view(-1		)							,      labels.view(-1		)		)
																						else:
																												__lowerCAmelCase											=					CrossEntropyLoss()
																												__lowerCAmelCase											=					loss_fct(logits_item.view(-1							,      self.num_labels		)							,      labels.view(-1		)		)
																						if total_loss is None:
																												__lowerCAmelCase											=					loss
																						else:
																												total_loss += loss * (ix + 1)
																						total_weights += ix + 1
																__lowerCAmelCase											=					(total_loss / total_weights,) + outputs

										return outputs

