



"""simple docstring"""
from sklearn.metrics import roc_auc_score

import datasets


_lowerCAmelCase					:Optional[int]  =      '\nThis metric computes the area under the curve (AUC) for the Receiver Operating Characteristic Curve (ROC). The return values represent how well the model used is predicting the correct classes, based on the input data. A score of `0.5` means that the model is predicting exactly at chance, i.e. the model\'s predictions are correct at the same rate as if the predictions were being decided by the flip of a fair coin or the roll of a fair die. A score above `0.5` indicates that the model is doing better than chance, while a score below `0.5` indicates that the model is doing worse than chance.\n\nThis metric has three separate use cases:\n    - binary: The case in which there are only two different label classes, and each example gets only one label. This is the default implementation.\n    - multiclass: The case in which there can be more than two different label classes, but each example still gets only one label.\n    - multilabel: The case in which there can be more than two different label classes, and each example can have more than one label.\n'

_lowerCAmelCase					:List[str]  =      '\nArgs:\n- references (array-like of shape (n_samples,) or (n_samples, n_classes)): Ground truth labels. Expects different input based on use case:\n    - binary: expects an array-like of shape (n_samples,)\n    - multiclass: expects an array-like of shape (n_samples,)\n    - multilabel: expects an array-like of shape (n_samples, n_classes)\n- prediction_scores (array-like of shape (n_samples,) or (n_samples, n_classes)): Model predictions. Expects different inputs based on use case:\n    - binary: expects an array-like of shape (n_samples,)\n    - multiclass: expects an array-like of shape (n_samples, n_classes)\n    - multilabel: expects an array-like of shape (n_samples, n_classes)\n- average (`str`): Type of average, and is ignored in the binary use case. Defaults to \'macro\'. Options are:\n    - `\'micro\'`: Calculates metrics globally by considering each element of the label indicator matrix as a label. Only works with the multilabel use case.\n    - `\'macro\'`: Calculate metrics for each label, and find their unweighted mean.  This does not take label imbalance into account.\n    - `\'weighted\'`: Calculate metrics for each label, and find their average, weighted by support (i.e. the number of true instances for each label).\n    - `\'samples\'`: Calculate metrics for each instance, and find their average. Only works with the multilabel use case.\n    - `None`:  No average is calculated, and scores for each class are returned. Only works with the multilabels use case.\n- sample_weight (array-like of shape (n_samples,)): Sample weights. Defaults to None.\n- max_fpr (`float`): If not None, the standardized partial AUC over the range [0, `max_fpr`] is returned. Must be greater than `0` and less than or equal to `1`. Defaults to `None`. Note: For the multiclass use case, `max_fpr` should be either `None` or `1.0` as ROC AUC partial computation is not currently supported for `multiclass`.\n- multi_class (`str`): Only used for multiclass targets, where it is required. Determines the type of configuration to use. Options are:\n    - `\'ovr\'`: Stands for One-vs-rest. Computes the AUC of each class against the rest. This treats the multiclass case in the same way as the multilabel case. Sensitive to class imbalance even when `average == \'macro\'`, because class imbalance affects the composition of each of the \'rest\' groupings.\n    - `\'ovo\'`: Stands for One-vs-one. Computes the average AUC of all possible pairwise combinations of classes. Insensitive to class imbalance when `average == \'macro\'`.\n- labels (array-like of shape (n_classes,)): Only used for multiclass targets. List of labels that index the classes in\n    `prediction_scores`. If `None`, the numerical or lexicographical order of the labels in\n    `prediction_scores` is used. Defaults to `None`.\nReturns:\n    roc_auc (`float` or array-like of shape (n_classes,)): Returns array if in multilabel use case and `average=\'None\'`. Otherwise, returns `float`.\nExamples:\n    Example 1:\n        >>> roc_auc_score = datasets.load_metric("roc_auc")\n        >>> refs = [1, 0, 1, 1, 0, 0]\n        >>> pred_scores = [0.5, 0.2, 0.99, 0.3, 0.1, 0.7]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores)\n        >>> print(round(results[\'roc_auc\'], 2))\n        0.78\n\n    Example 2:\n        >>> roc_auc_score = datasets.load_metric("roc_auc", "multiclass")\n        >>> refs = [1, 0, 1, 2, 2, 0]\n        >>> pred_scores = [[0.3, 0.5, 0.2],\n        ...                 [0.7, 0.2, 0.1],\n        ...                 [0.005, 0.99, 0.005],\n        ...                 [0.2, 0.3, 0.5],\n        ...                 [0.1, 0.1, 0.8],\n        ...                 [0.1, 0.7, 0.2]]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, multi_class=\'ovr\')\n        >>> print(round(results[\'roc_auc\'], 2))\n        0.85\n\n    Example 3:\n        >>> roc_auc_score = datasets.load_metric("roc_auc", "multilabel")\n        >>> refs = [[1, 1, 0],\n        ...         [1, 1, 0],\n        ...         [0, 1, 0],\n        ...         [0, 0, 1],\n        ...         [0, 1, 1],\n        ...         [1, 0, 1]]\n        >>> pred_scores = [[0.3, 0.5, 0.2],\n        ...                 [0.7, 0.2, 0.1],\n        ...                 [0.005, 0.99, 0.005],\n        ...                 [0.2, 0.3, 0.5],\n        ...                 [0.1, 0.1, 0.8],\n        ...                 [0.1, 0.7, 0.2]]\n        >>> results = roc_auc_score.compute(references=refs, prediction_scores=pred_scores, average=None)\n        >>> print([round(res, 2) for res in results[\'roc_auc\']])\n        [0.83, 0.38, 0.94]\n'

_lowerCAmelCase					:Optional[Any]  =      '\\n@article{doi:10.1177/0272989X8900900307,\nauthor = {Donna Katzman McClish},\ntitle ={Analyzing a Portion of the ROC Curve},\njournal = {Medical Decision Making},\nvolume = {9},\nnumber = {3},\npages = {190-195},\nyear = {1989},\ndoi = {10.1177/0272989X8900900307},\n    note ={PMID: 2668680},\nURL = {https://doi.org/10.1177/0272989X8900900307},\neprint = {https://doi.org/10.1177/0272989X8900900307}\n}\n\n\n@article{10.1023/A:1010920819831,\nauthor = {Hand, David J. and Till, Robert J.},\ntitle = {A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems},\nyear = {2001},\nissue_date = {November 2001},\npublisher = {Kluwer Academic Publishers},\naddress = {USA},\nvolume = {45},\nnumber = {2},\nissn = {0885-6125},\nurl = {https://doi.org/10.1023/A:1010920819831},\ndoi = {10.1023/A:1010920819831},\njournal = {Mach. Learn.},\nmonth = {oct},\npages = {171–186},\nnumpages = {16},\nkeywords = {Gini index, AUC, error rate, ROC curve, receiver operating characteristic}\n}\n\n\n@article{scikit-learn,\ntitle={Scikit-learn: Machine Learning in {P}ython},\nauthor={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\njournal={Journal of Machine Learning Research},\nvolume={12},\npages={2825--2830},\nyear={2011}\n}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,_KWARGS_DESCRIPTION   )
class 							_UpperCAmelCase							(				datasets.Metric   ):





     '''simple docstring'''



     def 				__lowerCAmelCase			(      self	)							->      int:
         return datasets.MetricInfo(
             description=_DESCRIPTION ,			citation=_CITATION ,			inputs_description=_KWARGS_DESCRIPTION ,			features=datasets.Features(
                 {
                     '''prediction_scores''': datasets.Sequence(datasets.Value('''float'''	)	),
                     '''references''': datasets.Value('''int32'''	),
                 }
                 if self.config_name == '''multiclass'''
                 else {
                     '''references''': datasets.Sequence(datasets.Value('''int32'''	)	),
                     '''prediction_scores''': datasets.Sequence(datasets.Value('''float'''	)	),
                 }
                 if self.config_name == '''multilabel'''
                 else {
                     '''references''': datasets.Value('''int32'''	),
                     '''prediction_scores''': datasets.Value('''float'''	),
                 }	) ,			reference_urls=['''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html'''] ,			)





     def 				__lowerCAmelCase			(      self ,			A ,			A ,			A="macro" ,			A=None ,			A=None ,			A="raise" ,			A=None ,			)							->      int:
         return {
             "roc_auc": roc_auc_score(
                 A ,			A ,			average=A ,			sample_weight=A ,			max_fpr=A ,			multi_class=A ,			labels=A ,			)
         }







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


_lowerCAmelCase					:Union[str, Any]  =      logging.getLogger(__name__)
class 							_UpperCAmelCase							(				a   ):





     '''simple docstring'''



     def 				__lowerCAmelCase			(      self ,			A ,			A ,			A=None ,			A=None	)							->      Tuple:
         if current_layer == 0:
             _UpperCAmelCase							:						Optional[Any]       							=					self.embedding_hidden_mapping_in(A	)
         else:
             _UpperCAmelCase							:						Union[str, Any]       							=					hidden_states[0]

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

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

         _UpperCAmelCase							:						List[Any]       							=					self.albert_layer_groups[group_idx](
             A ,			A ,			head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group] ,			)
         _UpperCAmelCase							:						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.'''	,a	,)
class 							_UpperCAmelCase							(				a   ):





     '''simple docstring'''



     def __init__(      self ,			A	)							->      str:
         super().__init__(A	)

         _UpperCAmelCase							:						Dict       							=					AlbertTransformerWithPabee(A	)

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

         _UpperCAmelCase							:						str       							=					0





     def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[int]:
         _UpperCAmelCase							:						List[Any]       							=					threshold





     def 				__lowerCAmelCase			(      self ,			A	)							->      Optional[Any]:
         _UpperCAmelCase							:						int       							=					patience





     def 				__lowerCAmelCase			(      self	)							->      Any:
         _UpperCAmelCase							:						Dict       							=					0
         _UpperCAmelCase							:						List[str]       							=					0





     def 				__lowerCAmelCase			(      self	)							->      List[Any]:
         _UpperCAmelCase							:						Union[str, Any]       							=					self.inference_layers_num / self.inference_instances_num
         _UpperCAmelCase							:						str       							=					(
             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 				__lowerCAmelCase			(      self ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=False ,			)							->      int:

         if input_ids is not None and inputs_embeds is not None:
             raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time'''	)
         elif input_ids is not None:
             _UpperCAmelCase							:						Optional[Any]       							=					input_ids.size()
         elif inputs_embeds is not None:
             _UpperCAmelCase							:						Optional[Any]       							=					inputs_embeds.size()[:-1]
         else:
             raise ValueError('''You have to specify either input_ids or inputs_embeds'''	)

         _UpperCAmelCase							:						Tuple       							=					input_ids.device if input_ids is not None else inputs_embeds.device

         if attention_mask is None:
             _UpperCAmelCase							:						Union[str, Any]       							=					torch.ones(A ,			device=A	)
         if token_type_ids is None:
             _UpperCAmelCase							:						Tuple       							=					torch.zeros(A ,			dtype=torch.long ,			device=A	)

         _UpperCAmelCase							:						Optional[Any]       							=					attention_mask.unsqueeze(1	).unsqueeze(2	)
         _UpperCAmelCase							:						Union[str, Any]       							=					extended_attention_mask.to(dtype=self.dtype	)  # fp16 compatibility
         _UpperCAmelCase							:						Dict       							=					(1.0 - extended_attention_mask) * -10_000.0
         _UpperCAmelCase							:						Any       							=					self.get_head_mask(A ,			self.config.num_hidden_layers	)

         _UpperCAmelCase							:						int       							=					self.embeddings(
             A ,			position_ids=A ,			token_type_ids=A ,			inputs_embeds=A	)
         _UpperCAmelCase							:						Any       							=					embedding_output

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

                 _UpperCAmelCase							:						List[str]       							=					self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]	)	)
                 _UpperCAmelCase							:						Dict       							=					output_layers[i](output_dropout(A	)	)
                 res.append(A	)
         elif self.patience == 0:  # Use all layers for inference
             _UpperCAmelCase							:						Dict       							=					self.encoder(A ,			A ,			head_mask=A	)
             _UpperCAmelCase							:						Tuple       							=					self.pooler_activation(self.pooler(encoder_outputs[0][:, 0]	)	)
             _UpperCAmelCase							:						Optional[int]       							=					[output_layers[self.config.num_hidden_layers - 1](A	)]
         else:
             _UpperCAmelCase							:						List[Any]       							=					0
             _UpperCAmelCase							:						int       							=					None
             _UpperCAmelCase							:						int       							=					0
             for i in range(self.config.num_hidden_layers	):
                 calculated_layer_num += 1
                 _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							:						Optional[Any]       							=					output_layers[i](A	)
                 if regression:
                     _UpperCAmelCase							:						str       							=					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							:						List[Any]       							=					0
                 else:
                     _UpperCAmelCase							:						List[str]       							=					logits.detach().argmax(dim=1	)
                     if patient_result is not None:
                         _UpperCAmelCase							:						Optional[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							:						Any       							=					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
    the pooled output) e.g. for GLUE tasks. '''	,a	,)
class 							_UpperCAmelCase							(				a   ):





     '''simple docstring'''



     def __init__(      self ,			A	)							->      Optional[int]:
         super().__init__(A	)
         _UpperCAmelCase							:						List[Any]       							=					config.num_labels

         _UpperCAmelCase							:						Optional[int]       							=					AlbertModelWithPabee(A	)
         _UpperCAmelCase							:						List[str]       							=					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 				__lowerCAmelCase			(      self ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			A=None ,			)							->      List[str]:
         _UpperCAmelCase							:						Optional[Any]       							=					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							:						int       							=					(logits[-1],)

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

         return outputs


