


'''simple docstring'''

from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder


# @@protoc_insertion_point(imports)

_UpperCAmelCase				: List[str]							    =				_symbol_database.Default()


_UpperCAmelCase				: List[Any]							    =				_descriptor_pool.Default().AddSerializedFile(
    b"""\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18  \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03"""
)

_UpperCAmelCase				: Optional[Any]							    =				globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, """sentencepiece_model_pb2""", _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
	_UpperCAmelCase				: int							    =				None
	_UpperCAmelCase				: Tuple							    =				b"""H\003"""
	# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
	# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
	# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
	# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
	# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
	_UpperCAmelCase				: Any							    =				4_5
	_UpperCAmelCase				: Tuple							    =				1_5_8_1
	_UpperCAmelCase				: Optional[int]							    =				1_5_1_7
	_UpperCAmelCase				: Optional[int]							    =				1_5_7_0
	_UpperCAmelCase				: Optional[int]							    =				1_5_8_4
	_UpperCAmelCase				: Optional[Any]							    =				1_7_9_3
	_UpperCAmelCase				: Union[str, Any]							    =				1_7_9_5
	_UpperCAmelCase				: Dict							    =				1_9_1_6
	_UpperCAmelCase				: List[Any]							    =				1_8_6_4
	_UpperCAmelCase				: Optional[Any]							    =				1_9_0_5
	_UpperCAmelCase				: Tuple							    =				1_9_1_9
	_UpperCAmelCase				: Dict							    =				2_4_2_9
	_UpperCAmelCase				: Optional[int]							    =				2_2_0_8
	_UpperCAmelCase				: Union[str, Any]							    =				2_4_1_8
	_UpperCAmelCase				: List[str]							    =				2_3_2_3
	_UpperCAmelCase				: Optional[Any]							    =				2_4_0_7
# @@protoc_insertion_point(module_scope)





'''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.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


_UpperCAmelCase				: Optional[Any]							    =				logging.getLogger(__name__)


class       a__				( __A      ):







				"""simple docstring"""



				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase       ,			__lowercase=None       ,			__lowercase=None		):
										__lowerCAmelCase							       =				self.layer[current_layer](__lowercase       ,			__lowercase       ,			head_mask[current_layer]		)

										__lowerCAmelCase							       =				layer_outputs[0]

										return hidden_states


@add_start_docstrings(
    'The bare Bert 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							       =				BertEncoderWithPabee(__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=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		)

										# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
										# ourselves in which case we just need to make it broadcastable to all heads.
										__lowerCAmelCase							       =				self.get_extended_attention_mask(__lowercase       ,			__lowercase       ,			__lowercase		)

										# If a 2D ou 3D attention mask is provided for the cross-attention
										# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
										if self.config.is_decoder and encoder_hidden_states is not None:
																__lowerCAmelCase       ,					__lowerCAmelCase       ,					__lowerCAmelCase							       =				encoder_hidden_states.size()
																__lowerCAmelCase							       =				(encoder_batch_size, encoder_sequence_length)
																if encoder_attention_mask is None:
																						__lowerCAmelCase							       =				torch.ones(__lowercase       ,			device=__lowercase		)
																__lowerCAmelCase							       =				self.invert_attention_mask(__lowercase		)
										else:
																__lowerCAmelCase							       =				None

										# Prepare head mask if needed
										# 1.0 in head_mask indicate we keep the head
										# attention_probs has shape bsz x n_heads x N x N
										# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
										# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
										__lowerCAmelCase							       =				self.get_head_mask(__lowercase       ,			self.config.num_hidden_layers		)

										__lowerCAmelCase							       =				self.embeddings(
										    input_ids=__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(__lowercase		)
																						__lowerCAmelCase							       =				output_layers[i](output_dropout(__lowercase		)		)
																						res.append(__lowercase		)
										elif self.patience == 0:  # Use all layers for inference
																__lowerCAmelCase							       =				self.encoder(
																    __lowercase       ,			attention_mask=__lowercase       ,			head_mask=__lowercase       ,			encoder_hidden_states=__lowercase       ,			encoder_attention_mask=__lowercase       ,			)
																__lowerCAmelCase							       =				self.pooler(encoder_outputs[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(__lowercase		)
																						__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(
    'Bert 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							       =				BertModelWithPabee(__lowercase		)
										__lowerCAmelCase							       =				nn.Dropout(config.hidden_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.bert(
										    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

