





'''simple docstring'''







import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union


class        __a   (enum.Enum  ):
							__a       : Tuple          =							"timm"
							__a       : Tuple          =							"transformers"





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[int]],      SCREAMING_SNAKE_CASE__   :      Optional[Iterable[str]] )			->						int:
						if stage_names is None:
												raise ValueError('''Stage_names must be set for transformers backbones''' )

						if out_features is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list,) ):
																		raise ValueError(F"""out_features must be a list {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(feat not in stage_names for feat in out_features ):
																		raise ValueError(F"""out_features must be a subset of stage_names: {stage_names} got {out_features}""" )

						if out_indices is not None:
												if not isinstance(SCREAMING_SNAKE_CASE__,      (list, tuple) ):
																		raise ValueError(F"""out_indices must be a list or tuple, got {type(SCREAMING_SNAKE_CASE__ )}""" )
												if any(idx >= len(SCREAMING_SNAKE_CASE__ ) for idx in out_indices ):
																		raise ValueError('''out_indices must be valid indices for stage_names {stage_names}, got {out_indices}''' )

						if out_features is not None and out_indices is not None:
												if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ):
																		raise ValueError('''out_features and out_indices should have the same length if both are set''' )
												if out_features != [stage_names[idx] for idx in out_indices]:
																		raise ValueError('''out_features and out_indices should correspond to the same stages if both are set''' )





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Optional[Any]:
						if out_indices is None and out_features is None:
												UpperCAmelCase_      :   Union[str, Any]      =	[len(SCREAMING_SNAKE_CASE__ ) - 1]
												UpperCAmelCase_      :   str      =	[stage_names[-1]]
						elif out_indices is None and out_features is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names.index(SCREAMING_SNAKE_CASE__ ) for layer in out_features]
						elif out_features is None and out_indices is not None:
												UpperCAmelCase_      :   List[str]      =	[stage_names[idx] for idx in out_indices]
						return out_features, out_indices





def 							lowerCamelCase_   (	SCREAMING_SNAKE_CASE__   :      Optional[List[str]],      SCREAMING_SNAKE_CASE__   :      Optional[Union[List[int], Tuple[int]]],      SCREAMING_SNAKE_CASE__   :      List[str],      )			->						Tuple[List[str], List[int]]:
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_    ,							UpperCAmelCase_      :   Dict      =	_align_output_features_output_indices(
						    out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						# Verify that the aligned out_features and out_indices are valid
						verify_out_features_out_indices(out_features=SCREAMING_SNAKE_CASE__,      out_indices=SCREAMING_SNAKE_CASE__,      stage_names=SCREAMING_SNAKE_CASE__ )
						return output_features, output_indices


class        __a   :
							__a       : Optional[BackboneType]          =							None

							def      UpperCAmelCase__						(				self				:  Dict							,  __magic_name__				:  List[Any] )       ->							None:







													"""simple docstring"""
													if getattr(self							,  '''_backbone'''							,  __magic_name__ ) is None:
																			raise ValueError('''self._backbone must be set before calling _init_timm_backbone''' )

													# These will diagree with the defaults for the transformers models e.g. for resnet50
													# the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
													# the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
													UpperCAmelCase_      :   int      =	[stage['''module'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   Tuple      =	[stage['''num_chs'''] for stage in self._backbone.feature_info.info]
													UpperCAmelCase_      :   List[Any]      =	self._backbone.feature_info.out_indices
													UpperCAmelCase_      :   Any      =	self._backbone.feature_info.module_name()

													# We verify the out indices and out features are valid
													verify_out_features_out_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Optional[Any]      =	out_features, out_indices

							def      UpperCAmelCase__						(				self				:  str							,  __magic_name__				:  Dict )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''stage_names''' )
													UpperCAmelCase_      :   Tuple      =	getattr(__magic_name__							,  '''out_features'''							,  __magic_name__ )
													UpperCAmelCase_      :   Union[str, Any]      =	getattr(__magic_name__							,  '''out_indices'''							,  __magic_name__ )

													UpperCAmelCase_      :   List[str]      =	stage_names
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=__magic_name__ )
													# Number of channels for each stage. This is set in the transformer backbone model init
													UpperCAmelCase_      :   List[str]      =	None

							def      UpperCAmelCase__						(				self				:  Any							,  __magic_name__				:  Tuple )       ->							None:







													"""simple docstring"""
													UpperCAmelCase_      :   int      =	config

													UpperCAmelCase_      :   str      =	getattr(__magic_name__							,  '''use_timm_backbone'''							,  __magic_name__ )
													UpperCAmelCase_      :   str      =	BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

													if self.backbone_type == BackboneType.TIMM:
																			self._init_timm_backbone(__magic_name__ )
													elif self.backbone_type == BackboneType.TRANSFORMERS:
																			self._init_transformers_backbone(__magic_name__ )
													else:
																			raise ValueError(F"""backbone_type {self.backbone_type} not supported.""" )

							@property
							def      UpperCAmelCase__						(				self				:  List[Any] )       ->							Optional[Any]:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							List[str]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   Union[str, Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							List[Any]:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   int      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  int )       ->							Optional[int]:







													"""simple docstring"""
													# the current backbones will output the number of channels for each stage
													# even if that stage is not in the out_features list.
													return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names )}

							@property
							def      UpperCAmelCase__						(				self				:  Tuple )       ->							Optional[Any]:







													"""simple docstring"""
													return [self.out_feature_channels[name] for name in self.out_features]

							def      UpperCAmelCase__						(				self				:  Any							,  *__magic_name__				:  Optional[int]							,  **__magic_name__				:  Dict )       ->							int:







													"""simple docstring"""
													UpperCAmelCase_      :   Tuple      =	dict(inspect.signature(self.forward ).parameters )
													UpperCAmelCase_      :   Optional[Any]      =	{k: v for k, v in kwargs.items() if k in signature}
													return self(*__magic_name__							,  **__magic_name__ )

							def      UpperCAmelCase__						(				self				:  Union[str, Any]							,  __magic_name__				:  List[str]							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  __magic_name__				:  Optional[bool] = None							,  )       ->							List[Any]:







													"""simple docstring"""
													raise NotImplementedError('''This method should be implemented by the derived class.''' )



							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_      :   List[Any]      =	super().to_dict()
													UpperCAmelCase_      :   List[Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Tuple      =	output.pop('''_out_indices''' )
													return output





class        __a   :

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							str:







													"""simple docstring"""
													return self._out_features

							@out_features.setter
							def      UpperCAmelCase__						(				self				:  int							,  __magic_name__				:  List[str] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   List[Any]      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )

							@property
							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							int:







													"""simple docstring"""
													return self._out_indices

							@out_indices.setter
							def      UpperCAmelCase__						(				self				:  List[Any]							,  __magic_name__				:  Union[Tuple[int], List[int]] )       ->							str:







													"""simple docstring"""
													UpperCAmelCase_    ,							UpperCAmelCase_      :   str      =	get_aligned_output_features_output_indices(
													    out_features=__magic_name__							,  out_indices=__magic_name__							,  stage_names=self.stage_names )



							def      UpperCAmelCase__						(				self				:  Union[str, Any] )       ->							int:







													"""simple docstring"""
													UpperCAmelCase_      :   str      =	super().to_dict()
													UpperCAmelCase_      :   Union[str, Any]      =	output.pop('''_out_features''' )
													UpperCAmelCase_      :   Any      =	output.pop('''_out_indices''' )
													return output









'''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

