



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


_lowercase:					int      =						logging.get_logger(__name__)

_lowercase:					int      =						{
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

_lowercase:					Optional[int]      =						{
    "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",
    },
}

_lowercase:					Dict      =						{
    "Salesforce/codegen-350M-mono": 2048,
}






@lru_cache()
def        a( )						->			Optional[int]:
					"""simple docstring"""





					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(A			)
															cs.append(2**8 + n			)
															n += 1
					a   	=  [chr(A			) for n in cs]
					return dict(zip(A					,	A			)			)






def        a( A			:       Any			)						->			Union[str, Any]:
					"""simple docstring"""





					a   	=  set()
					a   	=  word[0]
					for char in word[1:]:
										pairs.add((prev_char, char)			)
										a   	=  char
					return pairs







class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""
	__A		      =				VOCAB_FILES_NAMES
	__A		      =				PRETRAINED_VOCAB_FILES_MAP
	__A		      =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	__A		      =				["input_ids", "attention_mask"]




	def __init__(self						,			lowerCamelCase_						,			lowerCamelCase_						,			lowerCamelCase_="replace"						,			lowerCamelCase_="<|endoftext|>"						,			lowerCamelCase_="<|endoftext|>"						,			lowerCamelCase_="<|endoftext|>"						,			lowerCamelCase_=None						,			lowerCamelCase_=False						,			lowerCamelCase_=False						,			**lowerCamelCase_						,			):
						"""simple docstring"""

						a   	=  AddedToken(lowerCamelCase_						,			lstrip=lowerCamelCase_						,			rstrip=lowerCamelCase_						) if isinstance(lowerCamelCase_						,			lowerCamelCase_						) else bos_token
						a   	=  AddedToken(lowerCamelCase_						,			lstrip=lowerCamelCase_						,			rstrip=lowerCamelCase_						) if isinstance(lowerCamelCase_						,			lowerCamelCase_						) else eos_token
						a   	=  AddedToken(lowerCamelCase_						,			lstrip=lowerCamelCase_						,			rstrip=lowerCamelCase_						) if isinstance(lowerCamelCase_						,			lowerCamelCase_						) else unk_token
						a   	=  AddedToken(lowerCamelCase_						,			lstrip=lowerCamelCase_						,			rstrip=lowerCamelCase_						) if isinstance(lowerCamelCase_						,			lowerCamelCase_						) else pad_token
						super().__init__(
						    errors=lowerCamelCase_						,			unk_token=lowerCamelCase_						,			bos_token=lowerCamelCase_						,			eos_token=lowerCamelCase_						,			pad_token=lowerCamelCase_						,			add_prefix_space=lowerCamelCase_						,			add_bos_token=lowerCamelCase_						,			**lowerCamelCase_						,			)
						a   	=  add_bos_token

						with open(lowerCamelCase_						,			encoding="utf-8"						) as vocab_handle:
											a   	=  json.load(lowerCamelCase_						)
						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(lowerCamelCase_						,			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(lowerCamelCase_						,			range(len(lowerCamelCase_						)						)						)						)
						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 	UpperCamelCase_			(self						):
						"""simple docstring"""

						return len(self.encoder						)




	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

						return dict(self.encoder						,			**self.added_tokens_encoder						)




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						if token in self.cache:
											return self.cache[token]
						a   	=  tuple(lowerCamelCase_						)
						a   	=  get_pairs(lowerCamelCase_						)

						if not pairs:
											return token

						while True:
											a   	=  min(lowerCamelCase_						,			key=lambda lowerCamelCase_						: self.bpe_ranks.get(lowerCamelCase_						,			float("inf"						)						)						)
											if bigram not in self.bpe_ranks:
																break
											a	,							a   	=  bigram
											a   	=  []
											a   	=  0
											while i < len(lowerCamelCase_						):
																try:
																					a   	=  word.index(lowerCamelCase_						,			lowerCamelCase_						)
																except ValueError:
																					new_word.extend(word[i:]						)
																					break
																else:
																					new_word.extend(word[i:j]						)
																					a   	=  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
											a   	=  tuple(lowerCamelCase_						)
											a   	=  new_word
											if len(lowerCamelCase_						) == 1:
																break
											else:
																a   	=  get_pairs(lowerCamelCase_						)
						a   	=  " ".join(lowerCamelCase_						)
						a   	=  word
						return word




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_=None						):
						"""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 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

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




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						return self.encoder.get(lowerCamelCase_						,			self.encoder.get(self.unk_token						)						)




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						return self.decoder.get(lowerCamelCase_						)




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						):
						"""simple docstring"""

						a   	=  "".join(lowerCamelCase_						)
						a   	=  bytearray([self.byte_decoder[c] for c in text]						).decode("utf-8"						,			errors=self.errors						)
						return text




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_ = None						):
						"""simple docstring"""

						if not os.path.isdir(lowerCamelCase_						):
											logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''						)
											return
						a   	=  os.path.join(
						    lowerCamelCase_						,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)
						a   	=  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"						)

						a   	=  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!"						)
																					a   	=  token_index
																writer.write(" ".join(lowerCamelCase_						) + "\n"						)
																index += 1

						return vocab_file, merge_file




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_=False						,			**lowerCamelCase_						):
						"""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 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_ = False						,			lowerCamelCase_ = None						,			lowerCamelCase_ = None						,			**lowerCamelCase_						,			):
						"""simple docstring"""

						a   	=  super()._decode(
						    token_ids=lowerCamelCase_						,			skip_special_tokens=lowerCamelCase_						,			clean_up_tokenization_spaces=lowerCamelCase_						,			**lowerCamelCase_						,			)

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

						return decoded_text




	def 	UpperCamelCase_			(self						,			lowerCamelCase_						,			lowerCamelCase_						):
						"""simple docstring"""

						def find_re(lowerCamelCase_						,			lowerCamelCase_						,			lowerCamelCase_						):
											a   	=  pattern.search(lowerCamelCase_						,			lowerCamelCase_						)
											return m.start() if m else -1

						a   	=  [re.compile(lowerCamelCase_						,			re.MULTILINE						) for pattern in truncate_before_pattern]

						a   	=  list(re.finditer("^print"						,			lowerCamelCase_						,			re.MULTILINE						)						)

						if len(lowerCamelCase_						) > 1:
											a   	=  completion[: prints[1].start()]

						a   	=  list(re.finditer("^def"						,			lowerCamelCase_						,			re.MULTILINE						)						)

						if len(lowerCamelCase_						) > 1:
											a   	=  completion[: defs[1].start()]

						a   	=  0

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

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





from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_lowercase:					int      =						logging.get_logger(__name__)

_lowercase:					Dict      =						{
    "google/mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json"
}



class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""
	__A		      =				MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
	__A		      =				"mobilebert"




	def __init__(self						,			lowerCamelCase_=30522						,			lowerCamelCase_=512						,			lowerCamelCase_=24						,			lowerCamelCase_=4						,			lowerCamelCase_=512						,			lowerCamelCase_="relu"						,			lowerCamelCase_=0.0						,			lowerCamelCase_=0.1						,			lowerCamelCase_=512						,			lowerCamelCase_=2						,			lowerCamelCase_=0.02						,			lowerCamelCase_=1E-1_2						,			lowerCamelCase_=0						,			lowerCamelCase_=128						,			lowerCamelCase_=True						,			lowerCamelCase_=True						,			lowerCamelCase_=128						,			lowerCamelCase_=False						,			lowerCamelCase_=True						,			lowerCamelCase_=4						,			lowerCamelCase_="no_norm"						,			lowerCamelCase_=True						,			lowerCamelCase_=None						,			**lowerCamelCase_						,			):
						"""simple docstring"""

						super().__init__(pad_token_id=lowerCamelCase_						,			**lowerCamelCase_						)

						a   	=  vocab_size
						a   	=  hidden_size
						a   	=  num_hidden_layers
						a   	=  num_attention_heads
						a   	=  hidden_act
						a   	=  intermediate_size
						a   	=  hidden_dropout_prob
						a   	=  attention_probs_dropout_prob
						a   	=  max_position_embeddings
						a   	=  type_vocab_size
						a   	=  initializer_range
						a   	=  layer_norm_eps
						a   	=  embedding_size
						a   	=  trigram_input
						a   	=  use_bottleneck
						a   	=  intra_bottleneck_size
						a   	=  use_bottleneck_attention
						a   	=  key_query_shared_bottleneck
						a   	=  num_feedforward_networks
						a   	=  normalization_type
						a   	=  classifier_activation

						if self.use_bottleneck:
											a   	=  intra_bottleneck_size
						else:
											a   	=  hidden_size

						a   	=  classifier_dropout




class       _lowercase				(  lowerCAmelCase      ):





	"""simple docstring"""




	@property
	def 	UpperCamelCase_			(self						):
						"""simple docstring"""

						if self.task == "multiple-choice":
											a   	=  {0: "batch", 1: "choice", 2: "sequence"}
						else:
											a   	=  {0: "batch", 1: "sequence"}
						return OrderedDict(
						    [
						        ("input_ids", dynamic_axis),
						        ("attention_mask", dynamic_axis),
						        ("token_type_ids", dynamic_axis),
						    ]						)
