

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,
)


SCREAMING_SNAKE_CASE_						=					logging.getLogger(__name__)

class  a     (		UpperCAmelCase ):


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_=None  ,    A_=None		):







										'''simple docstring'''


										if current_layer == 0:
														_UpperCAmelCase				:						Tuple       						=			self.embedding_hidden_mapping_in(A_		)
										else:
														_UpperCAmelCase				:						int       						=			hidden_states[0]

										_UpperCAmelCase				:						int       						=			int(self.config.num_hidden_layers / self.config.num_hidden_groups		)

										# Index of the hidden group
										_UpperCAmelCase				:						Union[str, Any]       						=			int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)		)

										_UpperCAmelCase				:						Dict       						=			self.albert_layer_groups[group_idx](
										    A_  ,    A_  ,    head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group]  ,    )
										_UpperCAmelCase				:						List[str]       						=			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."							,       UpperCAmelCase							,       )
class  a     (		UpperCAmelCase ):


						def __init__(				self  ,    A_		):







										'''simple docstring'''


										super().__init__(A_		)

										_UpperCAmelCase				:						Optional[Any]       						=			AlbertTransformerWithPabee(A_		)

										self.init_weights()
										_UpperCAmelCase				:						List[str]       						=			0
										_UpperCAmelCase				:						str       						=			0
										_UpperCAmelCase				:						Union[str, Any]       						=			0

										_UpperCAmelCase				:						Dict       						=			0


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Optional[int]       						=			threshold


						def 				_UpperCAmelCase (				self  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			patience


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			0
										_UpperCAmelCase				:						Union[str, Any]       						=			0


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			self.inference_layers_num / self.inference_instances_num
										_UpperCAmelCase				:						Optional[Any]       						=			(
										    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(A_		)





						@add_start_docstrings_to_model_forward(A_		)
						def 				_UpperCAmelCase (				self  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=False  ,    ):







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

										_UpperCAmelCase				:						Optional[int]       						=			input_ids.device if input_ids is not None else inputs_embeds.device

										if attention_mask is None:
														_UpperCAmelCase				:						List[str]       						=			torch.ones(A_  ,    device=A_		)
										if token_type_ids is None:
														_UpperCAmelCase				:						List[str]       						=			torch.zeros(A_  ,    dtype=torch.long  ,    device=A_		)

										_UpperCAmelCase				:						Optional[int]       						=			attention_mask.unsqueeze(1		).unsqueeze(2		)
										_UpperCAmelCase				:						Optional[int]       						=			extended_attention_mask.to(dtype=self.dtype		)  # fp16 compatibility
										_UpperCAmelCase				:						List[str]       						=			(1.0 - extended_attention_mask) * -1_00_00.0
										_UpperCAmelCase				:						str       						=			self.get_head_mask(A_  ,    self.config.num_hidden_layers		)

										_UpperCAmelCase				:						List[Any]       						=			self.embeddings(
										    A_  ,    position_ids=A_  ,    token_type_ids=A_  ,    inputs_embeds=A_		)
										_UpperCAmelCase				:						str       						=			embedding_output

										if self.training:
														_UpperCAmelCase				:						Any       						=			[]
														for i in range(self.config.num_hidden_layers		):
																		_UpperCAmelCase				:						Tuple       						=			self.encoder.adaptive_forward(
																		    A_  ,    current_layer=A_  ,    attention_mask=A_  ,    head_mask=A_  ,    )

																		_UpperCAmelCase				:						Any       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																		_UpperCAmelCase				:						List[Any]       						=			output_layers[i](output_dropout(A_		)		)
																		res.append(A_		)
										elif self.patience == 0:  # Use all layers for inference
														_UpperCAmelCase				:						List[str]       						=			self.encoder(A_  ,    A_  ,    head_mask=A_		)
														_UpperCAmelCase				:						Optional[Any]       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
														_UpperCAmelCase				:						Union[str, Any]       						=			[output_layers[self.config.num_hidden_layers - 1](A_		)]
										else:
														_UpperCAmelCase				:						int       						=			0
														_UpperCAmelCase				:						List[Any]       						=			None
														_UpperCAmelCase				:						Dict       						=			0
														for i in range(self.config.num_hidden_layers		):
																		calculated_layer_num += 1
																		_UpperCAmelCase				:						Any       						=			self.encoder.adaptive_forward(
																		    A_  ,    current_layer=A_  ,    attention_mask=A_  ,    head_mask=A_  ,    )

																		_UpperCAmelCase				:						Optional[Any]       						=			self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]		)		)
																		_UpperCAmelCase				:						Union[str, Any]       						=			output_layers[i](A_		)
																		if regression:
																						_UpperCAmelCase				:						Tuple       						=			logits.detach()
																						if patient_result is not None:
																										_UpperCAmelCase				:						str       						=			patient_result.detach()
																						if (patient_result is not None) and torch.abs(patient_result - labels		) < self.regression_threshold:
																										patient_counter += 1
																						else:
																										_UpperCAmelCase				:						Union[str, Any]       						=			0
																		else:
																						_UpperCAmelCase				:						int       						=			logits.detach().argmax(dim=1		)
																						if patient_result is not None:
																										_UpperCAmelCase				:						Any       						=			patient_result.detach().argmax(dim=1		)
																						if (patient_result is not None) and torch.all(labels.eq(A_		)		):
																										patient_counter += 1
																						else:
																										_UpperCAmelCase				:						Tuple       						=			0

																		_UpperCAmelCase				:						Dict       						=			logits
																		if patient_counter == self.patience:
																						break
														_UpperCAmelCase				:						List[str]       						=			[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. "							,       UpperCAmelCase							,       )
class  a     (		UpperCAmelCase ):


						def __init__(				self  ,    A_		):







										'''simple docstring'''


										super().__init__(A_		)
										_UpperCAmelCase				:						Optional[int]       						=			config.num_labels

										_UpperCAmelCase				:						str       						=			AlbertModelWithPabee(A_		)
										_UpperCAmelCase				:						Dict       						=			nn.Dropout(config.classifier_dropout_prob		)
										_UpperCAmelCase				:						Optional[Any]       						=			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(A_		)
						def 				_UpperCAmelCase (				self  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    A_=None  ,    ):







										'''simple docstring'''


										_UpperCAmelCase				:						str       						=			self.albert(
										    input_ids=A_  ,    attention_mask=A_  ,    token_type_ids=A_  ,    position_ids=A_  ,    head_mask=A_  ,    inputs_embeds=A_  ,    output_dropout=self.dropout  ,    output_layers=self.classifiers  ,    regression=self.num_labels == 1  ,    )

										_UpperCAmelCase				:						Optional[Any]       						=			(logits[-1],)

										if labels is not None:
														_UpperCAmelCase				:						Tuple       						=			None
														_UpperCAmelCase				:						Tuple       						=			0
														for ix, logits_item in enumerate(A_		):
																		if self.num_labels == 1:
																						#  We are doing regression
																						_UpperCAmelCase				:						List[Any]       						=			MSELoss()
																						_UpperCAmelCase				:						List[str]       						=			loss_fct(logits_item.view(-1		)  ,    labels.view(-1		)		)
																		else:
																						_UpperCAmelCase				:						str       						=			CrossEntropyLoss()
																						_UpperCAmelCase				:						int       						=			loss_fct(logits_item.view(-1  ,    self.num_labels		)  ,    labels.view(-1		)		)
																		if total_loss is None:
																						_UpperCAmelCase				:						Dict       						=			loss
																		else:
																						total_loss += loss * (ix + 1)
																		total_weights += ix + 1
														_UpperCAmelCase				:						List[str]       						=			(total_loss / total_weights,) + outputs

										return outputs









'''simple docstring'''







import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp





def    _lowerCAmelCase						(						)					->					List[str]:
			__lowerCAmelCase											=				ArgumentParser(
			    description=(
			        """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"""
			    )	)

			# Optional arguments for the launch helper
			parser.add_argument("""--num_cores"""					,	type=lowercase					,	default=1					,	help="""Number of TPU cores to use (1 or 8)."""	)

			# positional
			parser.add_argument(
			    """training_script"""					,	type=lowercase					,	help=(
			        """The full path to the single TPU training """
			        """program/script to be launched in parallel, """
			        """followed by all the arguments for the """
			        """training script"""
			    )					,	)

			# rest from the training program
			parser.add_argument("""training_script_args"""					,	nargs=lowercase	)

			return parser.parse_args()





def    _lowerCAmelCase						(						)					->					Any:
			__lowerCAmelCase											=				parse_args()

			# Import training_script as a module.
			__lowerCAmelCase											=				Path(args.training_script	)
			sys.path.append(str(script_fpath.parent.resolve()	)	)
			__lowerCAmelCase											=				script_fpath.stem
			__lowerCAmelCase											=				importlib.import_module(lowercase	)

			# Patch sys.argv
			__lowerCAmelCase											=				[args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores	)]

			xmp.spawn(mod._mp_fn					,	args=()					,	nprocs=args.num_cores	)


if __name__ == "__main__":
	main()

