


import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__lowerCAmelCase     :			Dict      =logging.get_logger(__name__)


__lowerCAmelCase     :			Any      ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all MVP models at https://huggingface.co/models?filter=mvp
__lowerCAmelCase     :			int      ={
    'vocab_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json',
    },
    'added_tokens.json': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json',
    },
    'merges_file': {
        'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt',
    },
}

__lowerCAmelCase     :			Tuple      ={
    'RUCAIBox/mvp': 1_0_2_4,
}


@lru_cache()
def 	_UpperCamelCase							(				):
						__SCREAMING_SNAKE_CASE						:					List[str]		      =		(
						    list(range(ord('''!'''				)   ,	ord('''~'''				) + 1				)				) + list(range(ord('''¡'''				)   ,	ord('''¬'''				) + 1				)				) + list(range(ord('''®'''				)   ,	ord('''ÿ'''				) + 1				)				)
						)
						__SCREAMING_SNAKE_CASE						:					Dict		      =		bs[:]
						__SCREAMING_SNAKE_CASE						:					int		      =		0
						for b in range(2**8				):
												if b not in bs:
																		bs.append(lowercase__				)
																		cs.append(2**8 + n				)
																		n += 1
						__SCREAMING_SNAKE_CASE						:					Any		      =		[chr(lowercase__				) for n in cs]
						return dict(zip(lowercase__   ,	lowercase__				)				)


def 	_UpperCamelCase							(				lowercase__				):
						__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		set()
						__SCREAMING_SNAKE_CASE						:					Tuple		      =		word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)				)
												__SCREAMING_SNAKE_CASE						:					int		      =		char
						return pairs
class 	_lowercase				(      A__	):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__    :      List[str]      =		VOCAB_FILES_NAMES
				SCREAMING_SNAKE_CASE__    :      Optional[int]      =		PRETRAINED_VOCAB_FILES_MAP
				SCREAMING_SNAKE_CASE__    :      Optional[int]      =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				SCREAMING_SNAKE_CASE__    :      int      =		['''input_ids''', '''attention_mask''']


				def __init__(	self      :Tuple      ,      lowerCAmelCase__      :Optional[Any]      ,      lowerCAmelCase__      :Any      ,      lowerCAmelCase__      :Optional[Any]="replace"      ,      lowerCAmelCase__      :List[Any]="<s>"      ,      lowerCAmelCase__      :Dict="</s>"      ,      lowerCAmelCase__      :Tuple="</s>"      ,      lowerCAmelCase__      :Dict="<s>"      ,      lowerCAmelCase__      :Any="<unk>"      ,      lowerCAmelCase__      :Optional[Any]="<pad>"      ,      lowerCAmelCase__      :Optional[int]="<mask>"      ,      lowerCAmelCase__      :int=False      ,      **lowerCAmelCase__      :Tuple      ,      )		->      Dict:
										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else bos_token
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else eos_token
										__SCREAMING_SNAKE_CASE						:					List[Any]		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else sep_token
										__SCREAMING_SNAKE_CASE						:					Any		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else cls_token
										__SCREAMING_SNAKE_CASE						:					List[str]		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else unk_token
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else pad_token

										# Mask token behave like a normal word, i.e. include the space before it
										__SCREAMING_SNAKE_CASE						:					str		      =		AddedToken(lowerCAmelCase__      ,      lstrip=lowerCAmelCase__      ,      rstrip=lowerCAmelCase__     ) if isinstance(lowerCAmelCase__      ,      lowerCAmelCase__     ) else mask_token

										super().__init__(
										    errors=lowerCAmelCase__      ,      bos_token=lowerCAmelCase__      ,      eos_token=lowerCAmelCase__      ,      unk_token=lowerCAmelCase__      ,      sep_token=lowerCAmelCase__      ,      cls_token=lowerCAmelCase__      ,      pad_token=lowerCAmelCase__      ,      mask_token=lowerCAmelCase__      ,      add_prefix_space=lowerCAmelCase__      ,      **lowerCAmelCase__      ,      )
										with open(lowerCAmelCase__      ,      encoding='''utf-8'''     ) as vocab_handle:
																__SCREAMING_SNAKE_CASE						:					Tuple		      =		json.load(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		{v: k for k, v in self.encoder.items()}
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		errors  # how to handle errors in decoding
										__SCREAMING_SNAKE_CASE						:					Dict		      =		bytes_to_unicode()
										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		{v: k for k, v in self.byte_encoder.items()}
										with open(lowerCAmelCase__      ,      encoding='''utf-8'''     ) as merges_handle:
																__SCREAMING_SNAKE_CASE						:					Tuple		      =		merges_handle.read().split('''\n'''     )[1:-1]
										__SCREAMING_SNAKE_CASE						:					str		      =		[tuple(merge.split()     ) for merge in bpe_merges]
										__SCREAMING_SNAKE_CASE						:					List[Any]		      =		dict(zip(lowerCAmelCase__      ,      range(len(lowerCAmelCase__     )     )     )     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		{}
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		add_prefix_space

										# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'''     )


				@property
				def 		__magic_name__(	self      :List[str]     )		->      Dict:
										return len(self.encoder     )


				def 		__magic_name__(	self      :List[str]     )		->      Any:
										return dict(self.encoder      ,      **self.added_tokens_encoder     )


				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :Dict     )		->      Optional[int]:
										if token in self.cache:
																return self.cache[token]
										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		tuple(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		get_pairs(lowerCAmelCase__     )

										if not pairs:
																return token

										while True:
																__SCREAMING_SNAKE_CASE						:					List[Any]		      =		min(lowerCAmelCase__      ,      key=lambda lowerCAmelCase__     : self.bpe_ranks.get(lowerCAmelCase__      ,      float('''inf'''     )     )     )
																if bigram not in self.bpe_ranks:
																						break
																__SCREAMING_SNAKE_CASE      ,      __SCREAMING_SNAKE_CASE						:					Dict		      =		bigram
																__SCREAMING_SNAKE_CASE						:					Any		      =		[]
																__SCREAMING_SNAKE_CASE						:					Any		      =		0
																while i < len(lowerCAmelCase__     ):
																						try:
																												__SCREAMING_SNAKE_CASE						:					Tuple		      =		word.index(lowerCAmelCase__      ,      lowerCAmelCase__     )
																						except ValueError:
																												new_word.extend(word[i:]     )
																												break
																						else:
																												new_word.extend(word[i:j]     )
																												__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		j

																						if word[i] == first and i < len(lowerCAmelCase__     ) - 1 and word[i + 1] == second:
																												new_word.append(first + second     )
																												i += 2
																						else:
																												new_word.append(word[i]     )
																												i += 1
																__SCREAMING_SNAKE_CASE						:					Dict		      =		tuple(lowerCAmelCase__     )
																__SCREAMING_SNAKE_CASE						:					Any		      =		new_word
																if len(lowerCAmelCase__     ) == 1:
																						break
																else:
																						__SCREAMING_SNAKE_CASE						:					str		      =		get_pairs(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Any		      =		''' '''.join(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		word
										return word


				def 		__magic_name__(	self      :List[str]      ,      lowerCAmelCase__      :List[Any]     )		->      Union[str, Any]:
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		[]
										for token in re.findall(self.pat      ,      lowerCAmelCase__     ):
																__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		''''''.join(
																    self.byte_encoder[b] for b in token.encode('''utf-8'''     )     )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
																bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase__     ).split(''' '''     )     )
										return bpe_tokens


				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :str     )		->      str:
										return self.encoder.get(lowerCAmelCase__      ,      self.encoder.get(self.unk_token     )     )


				def 		__magic_name__(	self      :List[str]      ,      lowerCAmelCase__      :List[str]     )		->      Optional[int]:
										return self.decoder.get(lowerCAmelCase__     )


				def 		__magic_name__(	self      :Tuple      ,      lowerCAmelCase__      :Any     )		->      Union[str, Any]:
										__SCREAMING_SNAKE_CASE						:					Dict		      =		''''''.join(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		bytearray([self.byte_decoder[c] for c in text]     ).decode('''utf-8'''      ,      errors=self.errors     )
										return text


				def 		__magic_name__(	self      :str      ,      lowerCAmelCase__      :str      ,      lowerCAmelCase__      :Optional[str] = None     )		->      Tuple[str]:
										if not os.path.isdir(lowerCAmelCase__     ):
																logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''     )
																return
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		os.path.join(
										    lowerCAmelCase__      ,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']     )
										__SCREAMING_SNAKE_CASE						:					Dict		      =		os.path.join(
										    lowerCAmelCase__      ,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']     )

										with open(lowerCAmelCase__      ,      '''w'''      ,      encoding='''utf-8'''     ) as f:
																f.write(json.dumps(self.encoder      ,      indent=2      ,      sort_keys=lowerCAmelCase__      ,      ensure_ascii=lowerCAmelCase__     ) + '''\n'''     )

										__SCREAMING_SNAKE_CASE						:					str		      =		0
										with open(lowerCAmelCase__      ,      '''w'''      ,      encoding='''utf-8'''     ) as writer:
																writer.write('''#version: 0.2\n'''     )
																for bpe_tokens, token_index in sorted(self.bpe_ranks.items()      ,      key=lambda lowerCAmelCase__     : kv[1]     ):
																						if index != token_index:
																												logger.warning(
																												    f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
																												    ''' Please check that the tokenizer is not corrupted!'''     )
																												__SCREAMING_SNAKE_CASE						:					Dict		      =		token_index
																						writer.write(''' '''.join(lowerCAmelCase__     ) + '''\n'''     )
																						index += 1

										return vocab_file, merge_file


				def 		__magic_name__(	self      :str      ,      lowerCAmelCase__      :List[int]      ,      lowerCAmelCase__      :Optional[List[int]] = None     )		->      List[int]:
										if token_ids_a is None:
																return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
										__SCREAMING_SNAKE_CASE						:					List[str]		      =		[self.cls_token_id]
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		[self.sep_token_id]
										return cls + token_ids_a + sep + sep + token_ids_a + sep


				def 		__magic_name__(	self      :List[str]      ,      lowerCAmelCase__      :List[int]      ,      lowerCAmelCase__      :Optional[List[int]] = None      ,      lowerCAmelCase__      :bool = False     )		->      List[int]:
										if already_has_special_tokens:
																return super().get_special_tokens_mask(
																    token_ids_a=lowerCAmelCase__      ,      token_ids_a=lowerCAmelCase__      ,      already_has_special_tokens=lowerCAmelCase__     )

										if token_ids_a is None:
																return [1] + ([0] * len(lowerCAmelCase__     )) + [1]
										return [1] + ([0] * len(lowerCAmelCase__     )) + [1, 1] + ([0] * len(lowerCAmelCase__     )) + [1]


				def 		__magic_name__(	self      :str      ,      lowerCAmelCase__      :List[int]      ,      lowerCAmelCase__      :Optional[List[int]] = None     )		->      List[int]:
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		[self.sep_token_id]
										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		[self.cls_token_id]

										if token_ids_a is None:
																return len(cls + token_ids_a + sep     ) * [0]
										return len(cls + token_ids_a + sep + sep + token_ids_a + sep     ) * [0]



				def 		__magic_name__(	self      :int      ,      lowerCAmelCase__      :List[Any]      ,      lowerCAmelCase__      :List[Any]=False      ,      **lowerCAmelCase__      :List[str]     )		->      List[Any]:
										__SCREAMING_SNAKE_CASE						:					Any		      =		kwargs.pop('''add_prefix_space'''      ,      self.add_prefix_space     )
										if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase__     ) > 0 and not text[0].isspace()):
																__SCREAMING_SNAKE_CASE						:					Dict		      =		''' ''' + text
										return (text, kwargs)




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     :			Any      =logging.getLogger(__name__)
class 	_lowercase				(      A__	):






				'''simple docstring'''



				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :Dict      ,      lowerCAmelCase__      :List[str]      ,      lowerCAmelCase__      :List[Any]=None      ,      lowerCAmelCase__      :Optional[Any]=None     )		->      List[Any]:
										if current_layer == 0:
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.embedding_hidden_mapping_in(lowerCAmelCase__     )
										else:
																__SCREAMING_SNAKE_CASE						:					Tuple		      =		hidden_states[0]

										__SCREAMING_SNAKE_CASE						:					Tuple		      =		int(self.config.num_hidden_layers / self.config.num_hidden_groups     )

										# Index of the hidden group
										__SCREAMING_SNAKE_CASE						:					List[str]		      =		int(current_layer / (self.config.num_hidden_layers / self.config.num_hidden_groups)     )

										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		self.albert_layer_groups[group_idx](
										    lowerCAmelCase__      ,      lowerCAmelCase__      ,      head_mask[group_idx * layers_per_group : (group_idx + 1) * layers_per_group]      ,      )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		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 	_lowercase				(      A__	):






				'''simple docstring'''



				def __init__(	self      :int      ,      lowerCAmelCase__      :List[str]     )		->      List[Any]:
										super().__init__(lowerCAmelCase__     )

										__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		AlbertTransformerWithPabee(lowerCAmelCase__     )

										self.init_weights()
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		0

										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		0


				def 		__magic_name__(	self      :int      ,      lowerCAmelCase__      :Optional[int]     )		->      str:
										__SCREAMING_SNAKE_CASE						:					Optional[int]		      =		threshold


				def 		__magic_name__(	self      :List[Any]      ,      lowerCAmelCase__      :Optional[int]     )		->      List[Any]:
										__SCREAMING_SNAKE_CASE						:					Dict		      =		patience


				def 		__magic_name__(	self      :Union[str, Any]     )		->      str:
										__SCREAMING_SNAKE_CASE						:					Any		      =		0
										__SCREAMING_SNAKE_CASE						:					int		      =		0


				def 		__magic_name__(	self      :Optional[int]     )		->      Dict:
										__SCREAMING_SNAKE_CASE						:					List[Any]		      =		self.inference_layers_num / self.inference_instances_num
										__SCREAMING_SNAKE_CASE						:					Union[str, 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(lowerCAmelCase__     )



				@add_start_docstrings_to_model_forward(lowerCAmelCase__     )
				def 		__magic_name__(	self      :Dict      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :Optional[Any]=None      ,      lowerCAmelCase__      :Any=None      ,      lowerCAmelCase__      :Dict=None      ,      lowerCAmelCase__      :Optional[int]=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :str=False      ,      )		->      Union[str, Any]:

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

										__SCREAMING_SNAKE_CASE						:					List[str]		      =		input_ids.device if input_ids is not None else inputs_embeds.device

										if attention_mask is None:
																__SCREAMING_SNAKE_CASE						:					List[str]		      =		torch.ones(lowerCAmelCase__      ,      device=lowerCAmelCase__     )
										if token_type_ids is None:
																__SCREAMING_SNAKE_CASE						:					Union[str, Any]		      =		torch.zeros(lowerCAmelCase__      ,      dtype=torch.long      ,      device=lowerCAmelCase__     )

										__SCREAMING_SNAKE_CASE						:					Any		      =		attention_mask.unsqueeze(1     ).unsqueeze(2     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		extended_attention_mask.to(dtype=self.dtype     )  # fp16 compatibility
										__SCREAMING_SNAKE_CASE						:					Dict		      =		(1.0 - extended_attention_mask) * -1_0000.0
										__SCREAMING_SNAKE_CASE						:					str		      =		self.get_head_mask(lowerCAmelCase__      ,      self.config.num_hidden_layers     )

										__SCREAMING_SNAKE_CASE						:					List[str]		      =		self.embeddings(
										    lowerCAmelCase__      ,      position_ids=lowerCAmelCase__      ,      token_type_ids=lowerCAmelCase__      ,      inputs_embeds=lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		embedding_output

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

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

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

																						__SCREAMING_SNAKE_CASE						:					str		      =		logits
																						if patient_counter == self.patience:
																												break
																__SCREAMING_SNAKE_CASE						:					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 	_lowercase				(      A__	):






				'''simple docstring'''



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

										__SCREAMING_SNAKE_CASE						:					str		      =		AlbertModelWithPabee(lowerCAmelCase__     )
										__SCREAMING_SNAKE_CASE						:					Tuple		      =		nn.Dropout(config.classifier_dropout_prob     )
										__SCREAMING_SNAKE_CASE						:					Dict		      =		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(lowerCAmelCase__     )
				def 		__magic_name__(	self      :Optional[int]      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :List[str]=None      ,      lowerCAmelCase__      :Dict=None      ,      lowerCAmelCase__      :str=None      ,      lowerCAmelCase__      :Tuple=None      ,      lowerCAmelCase__      :int=None      ,      lowerCAmelCase__      :Any=None      ,      )		->      Dict:
										__SCREAMING_SNAKE_CASE						:					Optional[Any]		      =		self.albert(
										    input_ids=lowerCAmelCase__      ,      attention_mask=lowerCAmelCase__      ,      token_type_ids=lowerCAmelCase__      ,      position_ids=lowerCAmelCase__      ,      head_mask=lowerCAmelCase__      ,      inputs_embeds=lowerCAmelCase__      ,      output_dropout=self.dropout      ,      output_layers=self.classifiers      ,      regression=self.num_labels == 1      ,      )

										__SCREAMING_SNAKE_CASE						:					int		      =		(logits[-1],)

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

										return outputs
