




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

import numpy as np
import regex as re

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
 if is_torch_available():
  import torch
 if is_tf_available():
  import tensorflow as tf

from ...tokenization_utils import AddedToken, PreTrainedTokenizer


SCREAMING_SNAKE_CASE_    :       str       =							logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_    :       Optional[Any]       =							{
    """vocab_file""": """vocab.json""",
    """merges_file""": """merges.txt""",
}

SCREAMING_SNAKE_CASE_    :       List[str]       =							{
    """vocab_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt""",
    },
}

SCREAMING_SNAKE_CASE_    :       Optional[Any]       =							{
    """Salesforce/codegen-350M-mono""": 20_48,
}
@lru_cache()
def 							__lowerCAmelCase			():
    a__  			=							(
        list(range(ord("""!"""		) ,     ord("""~"""		) + 1		)		) + list(range(ord("""¡"""		) ,     ord("""¬"""		) + 1		)		) + list(range(ord("""®"""		) ,     ord("""ÿ"""		) + 1		)		)
    )
    a__  			=							bs[:]
    a__  			=							0
    for b in range(2**8		):
        if b not in bs:
            bs.append(UpperCAmelCase_		)
            cs.append(2**8 + n		)
            n += 1
    a__  			=							[chr(UpperCAmelCase_		) for n in cs]
    return dict(zip(UpperCAmelCase_ ,     UpperCAmelCase_		)		)
def 							__lowerCAmelCase			(UpperCAmelCase_		):
    a__  			=							set()
    a__  			=							word[0]
    for char in word[1:]:
        pairs.add((prev_char, char)		)
        a__  			=							char
    return pairs







class 		__UpperCAmelCase(		__A			):





     """simple docstring"""



     __UpperCAmelCase						:			Union[str, Any]							=     VOCAB_FILES_NAMES
     __UpperCAmelCase						:			Dict							=     PRETRAINED_VOCAB_FILES_MAP
     __UpperCAmelCase						:			str							=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __UpperCAmelCase						:			Dict							=     ['input_ids', 'attention_mask']

     def __init__(   self			:							Any    ,					A			:							int    ,					A			:							Optional[int]    ,					A			:							Dict="replace"    ,					A			:							int="<|endoftext|>"    ,					A			:							Optional[int]="<|endoftext|>"    ,					A			:							Dict="<|endoftext|>"    ,					A			:							Optional[int]=None    ,					A			:							List[Any]=False    ,					A			:							Union[str, Any]=False    ,					**A			:							Tuple    ,					)      ->      Optional[int]:






         """simple docstring"""
         a__  			=							AddedToken(__lowercase    ,					lstrip=__lowercase    ,					rstrip=__lowercase     ) if isinstance(__lowercase    ,					__lowercase     ) else bos_token
         a__  			=							AddedToken(__lowercase    ,					lstrip=__lowercase    ,					rstrip=__lowercase     ) if isinstance(__lowercase    ,					__lowercase     ) else eos_token
         a__  			=							AddedToken(__lowercase    ,					lstrip=__lowercase    ,					rstrip=__lowercase     ) if isinstance(__lowercase    ,					__lowercase     ) else unk_token
         a__  			=							AddedToken(__lowercase    ,					lstrip=__lowercase    ,					rstrip=__lowercase     ) if isinstance(__lowercase    ,					__lowercase     ) else pad_token
         super().__init__(
             errors=__lowercase    ,					unk_token=__lowercase    ,					bos_token=__lowercase    ,					eos_token=__lowercase    ,					pad_token=__lowercase    ,					add_prefix_space=__lowercase    ,					add_bos_token=__lowercase    ,					**__lowercase    ,					)
         a__  			=							add_bos_token

         with open(__lowercase    ,					encoding="""utf-8"""     ) as vocab_handle:
             a__  			=							json.load(__lowercase     )
         a__  			=							{v: k for k, v in self.encoder.items()}
         a__  			=							errors  # how to handle errors in decoding
         a__  			=							bytes_to_unicode()
         a__  			=							{v: k for k, v in self.byte_encoder.items()}
         with open(__lowercase    ,					encoding="""utf-8"""     ) as merges_handle:
             a__  			=							merges_handle.read().split("""\n"""     )[1:-1]
         a__  			=							[tuple(merge.split()     ) for merge in bpe_merges]
         a__  			=							dict(zip(__lowercase    ,					range(len(__lowercase     )     )     )     )
         a__  			=							{}
         a__  			=							add_prefix_space

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

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[str]     )      ->      str:






         """simple docstring"""
         return len(self.encoder     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]     )      ->      Dict:






         """simple docstring"""
         return dict(self.encoder    ,					**self.added_tokens_encoder     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Union[str, Any]    ,					A			:							Optional[int]     )      ->      Dict:






         """simple docstring"""
         if token in self.cache:
             return self.cache[token]
         a__  			=							tuple(__lowercase     )
         a__  			=							get_pairs(__lowercase     )

         if not pairs:
             return token

         while True:
             a__  			=							min(__lowercase    ,					key=lambda A     : self.bpe_ranks.get(__lowercase    ,					float("""inf"""     )     )     )
             if bigram not in self.bpe_ranks:
                 break
             a__			,		a__  			=							bigram
             a__  			=							[]
             a__  			=							0
             while i < len(__lowercase     ):
                 try:
                     a__  			=							word.index(__lowercase    ,					__lowercase     )
                 except ValueError:
                     new_word.extend(word[i:]     )
                     break
                 else:
                     new_word.extend(word[i:j]     )
                     a__  			=							j

                 if word[i] == first and i < len(__lowercase     ) - 1 and word[i + 1] == second:
                     new_word.append(first + second     )
                     i += 2
                 else:
                     new_word.append(word[i]     )
                     i += 1
             a__  			=							tuple(__lowercase     )
             a__  			=							new_word
             if len(__lowercase     ) == 1:
                 break
             else:
                 a__  			=							get_pairs(__lowercase     )
         a__  			=							""" """.join(__lowercase     )
         a__  			=							word
         return word

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple    ,					A			:							Union[str, Any]    ,					A			:							List[str]=None     )      ->      Any:






         """simple docstring"""
         if self.add_bos_token:
             a__  			=							[self.bos_token_id]
         else:
             a__  			=							[]

         a__  			=							bos_token_ids + token_ids_a

         if token_ids_a is None:
             return output

         return output + bos_token_ids + token_ids_a

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]    ,					A			:							List[str]     )      ->      Optional[Any]:






         """simple docstring"""
         a__  			=							[]
         for token in re.findall(self.pat    ,					__lowercase     ):
             a__  			=							"""""".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(__lowercase     ).split(""" """     )     )
         return bpe_tokens

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple    ,					A			:							List[str]     )      ->      Optional[int]:






         """simple docstring"""
         return self.encoder.get(__lowercase    ,					self.encoder.get(self.unk_token     )     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int    ,					A			:							int     )      ->      Any:






         """simple docstring"""
         return self.decoder.get(__lowercase     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[Any]    ,					A			:							Any     )      ->      List[str]:






         """simple docstring"""
         a__  			=							"""""".join(__lowercase     )
         a__  			=							bytearray([self.byte_decoder[c] for c in text]     ).decode("""utf-8"""    ,					errors=self.errors     )
         return text

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Any    ,					A			:							List[str]    ,					A			:							List[str] = None     )      ->      List[Any]:






         """simple docstring"""
         if not os.path.isdir(__lowercase     ):
             logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""     )
             return
         a__  			=							os.path.join(
             __lowercase    ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]     )
         a__  			=							os.path.join(
             __lowercase    ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]     )

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

         a__  			=							0
         with open(__lowercase    ,					"""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 A     : 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!"""     )
                     a__  			=							token_index
                 writer.write(""" """.join(__lowercase     ) + """\n"""     )
                 index += 1

         return vocab_file, merge_file

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[str]    ,					A			:							Dict    ,					A			:							Any=False    ,					**A			:							Any     )      ->      Optional[Any]:






         """simple docstring"""
         a__  			=							kwargs.pop("""add_prefix_space"""    ,					self.add_prefix_space     )
         if is_split_into_words or add_prefix_space:
             a__  			=							""" """ + text
         return (text, kwargs)

     def 					__SCREAMING_SNAKE_CASE		(   self			:							str    ,					A			:							str    ,					A			:							Union[str, Any] = False    ,					A			:							Any = None    ,					A			:							Union[str, Any] = None    ,					**A			:							int    ,					)      ->      List[str]:






         """simple docstring"""
         a__  			=							super()._decode(
             token_ids=__lowercase    ,					skip_special_tokens=__lowercase    ,					clean_up_tokenization_spaces=__lowercase    ,					**__lowercase    ,					)

         if truncate_before_pattern is not None and len(__lowercase     ) > 0:
             a__  			=							self.truncate(__lowercase    ,					__lowercase     )

         return decoded_text






     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]    ,					A			:							int    ,					A			:							Optional[int]     )      ->      Optional[Any]:






         """simple docstring"""
         def find_re(A			:							Any    ,					A			:							List[str]    ,					A			:							Union[str, Any]     ):
             a__  			=							pattern.search(__lowercase    ,					__lowercase     )
             return m.start() if m else -1

         a__  			=							[re.compile(__lowercase    ,					re.MULTILINE     ) for pattern in truncate_before_pattern]

         a__  			=							list(re.finditer("""^print"""    ,					__lowercase    ,					re.MULTILINE     )     )

         if len(__lowercase     ) > 1:
             a__  			=							completion[: prints[1].start()]

         a__  			=							list(re.finditer("""^def"""    ,					__lowercase    ,					re.MULTILINE     )     )

         if len(__lowercase     ) > 1:
             a__  			=							completion[: defs[1].start()]

         a__  			=							0

         a__  			=							[
             pos for pos in [find_re(__lowercase    ,					__lowercase    ,					__lowercase     ) for terminal in terminals] if pos != -1
         ]

         if len(__lowercase     ) > 0:
             return completion[: min(__lowercase     )]
         else:
             return completion










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

