




import logging
import os
import sys
from dataclasses import dataclass, field
from typing import List, Optional

import torch
from datasets import Dataset
from torch import nn
from tqdm.auto import tqdm

from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
    utils,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


snake_case__ :						int     =			'''
Distills an NLI-based zero-shot classifier to a smaller, more efficient model with a fixed set of candidate class
names. Useful for speeding up zero-shot classification in cases where labeled training data is not available, but
when only a single fixed set of classes is needed. Takes a teacher NLI model, student classifier model, unlabeled
dataset, and set of K possible class names. Yields a single classifier with K outputs corresponding to the provided
class names.
'''

snake_case__ :						Optional[int]     =			logging.getLogger(__name__)





@dataclass
class     snake_case  :


			'''simple docstring'''







			UpperCamelCase__	:       Optional[str]     =      field(
			    default="roberta-large-mnli" ,  metadata={"help": "The NLI/zero-shot teacher model to be distilled."}							)
			UpperCamelCase__	:       Optional[str]     =      field(
			    default="This example is {}." ,  metadata={
			        "help": (
			            "Template used to turn class names into mock hypotheses for teacher NLI model. Must include {{}}"
			            "where class name is inserted."
			        )
			    } ,  )
			UpperCamelCase__	:       Optional[int]     =      field(
			    default=32 ,  metadata={"help": "Batch size for generating teacher predictions."}							)
			UpperCamelCase__	:       Optional[bool]     =      field(
			    default=_snake_case ,  metadata={
			        "help": (
			            "Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called"
			            "multi-class multi-label classification)."
			        )
			    } ,  )
			UpperCamelCase__	:       Optional[float]     =      field(
			    default=1.0 ,  metadata={"help": "Temperature applied to teacher softmax for distillation."}							)





@dataclass
class     snake_case  :


			'''simple docstring'''







			UpperCamelCase__	:       Optional[str]     =      field(
			    default="distilbert-base-uncased" ,  metadata={"help": "The NLI/zero-shot teacher model to be distilled."}							)





@dataclass
class     snake_case  :


			'''simple docstring'''







			UpperCamelCase__	:       str     =      field(metadata={"help": "Text file with one unlabeled instance per line."}							)
			UpperCamelCase__	:       str     =      field(metadata={"help": "Text file with one class name per line."}							)
			UpperCamelCase__	:       bool     =      field(
			    default=_snake_case ,  metadata={"help": "Whether to use one of the fast tokenizer (backed by the Rust tokenizers library) or not."} ,  )





@dataclass
class     snake_case  (	_snake_case							):


			'''simple docstring'''







			UpperCamelCase__	:       Optional[str]     =      field(
			    default=_snake_case ,  metadata={"help": "The output directory where the model predictions and checkpoints will be written."} ,  )
			UpperCamelCase__	:       int     =      field(
			    default=32 ,  metadata={"help": "Batch size per GPU/TPU core/CPU for training."}							)
			UpperCamelCase__	:       int     =      field(
			    default=1_28 ,  metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}							)
			UpperCamelCase__	:       float     =      field(default=1.0 ,  metadata={"help": "Total number of training epochs to perform."}							)
			UpperCamelCase__	:       bool     =      field(default=_snake_case ,  metadata={"help": "Whether to run training of student model."}							)
			UpperCamelCase__	:       bool     =      field(
			    default=_snake_case ,  metadata={
			        "help": (
			            "Whether to evaluate the agreement of the final student predictions and the teacher predictions"
			            "after training."
			        )
			    } ,  )
			UpperCamelCase__	:       Optional[int]     =      field(
			    default=0 ,  metadata={
			        "help": (
			            "Limit the total amount of checkpoints."
			            "Deletes the older checkpoints in the output_dir. Default is 0 (no checkpoints)."
			        )
			    } ,  )





class     snake_case  (	_snake_case							):


			'''simple docstring'''







			def 	UpperCAmelCase       (					self     :	Optional[int]						,    lowerCamelCase_     :	Tuple						,    lowerCamelCase_     :	Union[str, Any]						,    lowerCamelCase_     :	Tuple=False			)					->str:
					'''simple docstring'''







					UpperCAmelCase__    						=   inputs["""labels"""]
					UpperCAmelCase__    						=   model(inputs["""input_ids"""]						,    attention_mask=inputs["""attention_mask"""]			)
					UpperCAmelCase__    						=   outputs[0]

					UpperCAmelCase__    						=   -torch.sum(target_p * logits.log_softmax(dim=-1			)						,    axis=-1			).mean()

					if return_outputs:
							return loss, outputs

					return loss



def 						lowercase		(     _lowerCAmelCase      ):
		UpperCAmelCase__    						=   []
		with open(_lowerCAmelCase   ,     """r"""      ) as f:
				for line in f:
						UpperCAmelCase__    						=   line.strip()
						if len(_lowerCAmelCase      ) > 0:
								lines.append(_lowerCAmelCase      )
		return lines


def 						lowercase		(     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase      ):
		UpperCAmelCase__    						=   []
		UpperCAmelCase__    						=   []
		for example in examples:
				for name in class_names:
						premises.append(_lowerCAmelCase      )
						hypotheses.append(hypothesis_template.format(_lowerCAmelCase      )      )
		return premises, hypotheses


def 						lowercase		(     _lowerCAmelCase      ):
		for label, ind in config.labelaid.items():
				if label.lower().startswith("""entail"""      ):
						return ind
		logger.warning("""Could not identify entailment dimension from teacher config label2id. Setting to -1."""      )
		return -1


def 						lowercase		(     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     ):
		UpperCAmelCase__    						=   AutoModelForSequenceClassification.from_pretrained(_lowerCAmelCase      )
		UpperCAmelCase__    						=   model.config
		if not no_cuda and torch.cuda.is_available():
				UpperCAmelCase__    						=   nn.DataParallel(model.cuda()      )
				batch_size *= len(model.device_ids      )
		UpperCAmelCase__    						=   AutoTokenizer.from_pretrained(_lowerCAmelCase   ,     use_fast=_lowerCAmelCase      )

		UpperCAmelCase__						,					UpperCAmelCase__    						=   get_premise_hypothesis_pairs(_lowerCAmelCase   ,     _lowerCAmelCase   ,     _lowerCAmelCase      )
		UpperCAmelCase__    						=   []

		for i in tqdm(range(0   ,     len(_lowerCAmelCase      )   ,     _lowerCAmelCase      )      ):
				UpperCAmelCase__    						=   premises[i : i + batch_size]
				UpperCAmelCase__    						=   hypotheses[i : i + batch_size]

				UpperCAmelCase__    						=   tokenizer(
				    _lowerCAmelCase   ,     _lowerCAmelCase   ,     padding=_lowerCAmelCase   ,     truncation="""only_first"""   ,     return_tensors="""pt"""   ,     )

				with torch.cuda.amp.autocast(enabled=_lowerCAmelCase      ):
						with torch.no_grad():
								UpperCAmelCase__    						=   model(**_lowerCAmelCase      )
				logits.append(outputs.logits.detach().cpu().float()      )

		UpperCAmelCase__    						=   get_entailment_id(_lowerCAmelCase      )
		UpperCAmelCase__    						=   -1 if entail_id == 0 else 0
		UpperCAmelCase__    						=   torch.cat(_lowerCAmelCase   ,     dim=0      )  # N*K x 3
		UpperCAmelCase__    						=   logits.reshape(len(_lowerCAmelCase      )   ,     len(_lowerCAmelCase      )   ,     -1      )[..., [contr_id, entail_id]]  # N x K x 2

		if multi_label:
				# softmax over (contr, entail) logits for each class independently
				UpperCAmelCase__    						=   (nli_logits / temperature).softmax(-1      )
		else:
				# softmax over entail logits across classes s.t. class probabilities sum to 1.
				UpperCAmelCase__    						=   (nli_logits / temperature).softmax(1      )

		return nli_prob[..., 1]  # N x K


def 						lowercase		(     ):
		UpperCAmelCase__    						=   HfArgumentParser(
		    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)   ,     description=_lowerCAmelCase   ,     )

		if len(sys.argv      ) == 2 and sys.argv[1].endswith(""".json"""      ):
				# If we pass only one argument to the script and it's the path to a json file,
				# let's parse it to get our arguments.
				UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__    						=   parser.parse_json_file(
				    json_file=os.path.abspath(sys.argv[1]      )      )
		else:
				UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__    						=   parser.parse_args_into_dataclasses()

		# Detecting last checkpoint.
		UpperCAmelCase__    						=   None
		if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
				UpperCAmelCase__    						=   get_last_checkpoint(training_args.output_dir      )
				if last_checkpoint is None and len(os.listdir(training_args.output_dir      )      ) > 0:
						raise ValueError(
						    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
						    """Use --overwrite_output_dir to overcome."""      )
				elif last_checkpoint is not None:
						logger.info(
						    F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
						    """the `--output_dir` or add `--overwrite_output_dir` to train from scratch."""      )

				# Setup logging
		logging.basicConfig(
		    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""   ,     datefmt="""%m/%d/%Y %H:%M:%S"""   ,     handlers=[logging.StreamHandler(sys.stdout      )]   ,     )
		logger.setLevel(logging.INFO if is_main_process(training_args.local_rank      ) else logging.WARN      )

		# Log on each process the small summary:
		logger.warning(
		    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
		    + F'''distributed training: {bool(training_args.local_rank != -1      )}, 16-bits training: {training_args.fpaa}'''      )
		# Set the verbosity to info of the Transformers logger (on main process only):
		if is_main_process(training_args.local_rank      ):
				utils.logging.set_verbosity_info()
				utils.logging.enable_default_handler()
				utils.logging.enable_explicit_format()

		if training_args.local_rank != -1:
				raise ValueError("""Distributed training is not currently supported."""      )
		if training_args.tpu_num_cores is not None:
				raise ValueError("""TPU acceleration is not currently supported."""      )

		logger.info(F'''Training/evaluation parameters {training_args}'''      )

		# Set seed before initializing model.
		set_seed(training_args.seed      )

		# 1. read in data
		UpperCAmelCase__    						=   read_lines(data_args.data_file      )
		UpperCAmelCase__    						=   read_lines(data_args.class_names_file      )

		# 2. get teacher predictions and load into dataset
		logger.info("""Generating predictions from zero-shot teacher model"""      )
		UpperCAmelCase__    						=   get_teacher_predictions(
		    teacher_args.teacher_name_or_path   ,     _lowerCAmelCase   ,     _lowerCAmelCase   ,     teacher_args.hypothesis_template   ,     teacher_args.teacher_batch_size   ,     teacher_args.temperature   ,     teacher_args.multi_label   ,     data_args.use_fast_tokenizer   ,     training_args.no_cuda   ,     training_args.fpaa   ,     )
		UpperCAmelCase__    						=   Dataset.from_dict(
		    {
		        """text""": examples,
		        """labels""": teacher_soft_preds,
		    }      )

		# 3. create student
		logger.info("""Initializing student model"""      )
		UpperCAmelCase__    						=   AutoModelForSequenceClassification.from_pretrained(
		    student_args.student_name_or_path   ,     num_labels=len(_lowerCAmelCase      )      )
		UpperCAmelCase__    						=   AutoTokenizer.from_pretrained(student_args.student_name_or_path   ,     use_fast=data_args.use_fast_tokenizer      )
		UpperCAmelCase__    						=   dict(enumerate(_lowerCAmelCase      )      )
		UpperCAmelCase__    						=   {label: i for i, label in enumerate(_lowerCAmelCase      )}

		# 4. train student on teacher predictions
		UpperCAmelCase__    						=   dataset.map(_lowerCAmelCase   ,     input_columns="""text"""      )
		dataset.set_format("""torch"""      )

		def compute_metrics(_lowerCAmelCase   ,     _lowerCAmelCase=False      ):
				UpperCAmelCase__    						=   p.predictions.argmax(-1      )
				UpperCAmelCase__    						=   p.label_ids.argmax(-1      )  # "label_ids" are actually distributions
				return {"agreement": (preds == proxy_labels).mean().item()}

		UpperCAmelCase__    						=   DistillationTrainer(
		    model=_lowerCAmelCase   ,     tokenizer=_lowerCAmelCase   ,     args=_lowerCAmelCase   ,     train_dataset=_lowerCAmelCase   ,     compute_metrics=_lowerCAmelCase   ,     )

		if training_args.do_train:
				logger.info("""Training student model on teacher predictions"""      )
				trainer.train()

		if training_args.do_eval:
				UpperCAmelCase__    						=   trainer.evaluate(eval_dataset=_lowerCAmelCase      )["""eval_agreement"""]
				logger.info(F'''Agreement of student and teacher predictions: {agreement * 100:0.2f}%'''      )

		trainer.save_model()


if __name__ == "__main__":
			main()










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


snake_case__ :						str     =			logging.get_logger(__name__)

snake_case__ :						List[str]     =			{
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
}

snake_case__ :						Any     =			{
    '''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''',
    },
}

snake_case__ :						Tuple     =			{
    '''Salesforce/codegen-350M-mono''': 2_0_4_8,
}


@lru_cache()
def 						lowercase		(     ):
  UpperCAmelCase__    						=   (
      list(range(ord("""!"""      )   ,     ord("""~"""      ) + 1      )      ) + list(range(ord("""¡"""      )   ,     ord("""¬"""      ) + 1      )      ) + list(range(ord("""®"""      )   ,     ord("""ÿ"""      ) + 1      )      )
  )
  UpperCAmelCase__    						=   bs[:]
  UpperCAmelCase__    						=   0
  for b in range(2**8      ):
    if b not in bs:
      bs.append(_lowerCAmelCase      )
      cs.append(2**8 + n      )
      n += 1
  UpperCAmelCase__    						=   [chr(_lowerCAmelCase      ) for n in cs]
  return dict(zip(_lowerCAmelCase   ,     _lowerCAmelCase      )      )


def 						lowercase		(     _lowerCAmelCase      ):
  UpperCAmelCase__    						=   set()
  UpperCAmelCase__    						=   word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)      )
    UpperCAmelCase__    						=   char
  return pairs





class     snake_case  (	_snake_case							):


   '''simple docstring'''







   UpperCamelCase__	:       List[Any]     =      VOCAB_FILES_NAMES
   UpperCamelCase__	:       Union[str, Any]     =      PRETRAINED_VOCAB_FILES_MAP
   UpperCamelCase__	:       int     =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   UpperCamelCase__	:       int     =      ["input_ids", "attention_mask"]




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







     UpperCAmelCase__    						=   AddedToken(lowerCamelCase_						,    lstrip=lowerCamelCase_						,    rstrip=lowerCamelCase_			) if isinstance(lowerCamelCase_						,    lowerCamelCase_			) else bos_token
     UpperCAmelCase__    						=   AddedToken(lowerCamelCase_						,    lstrip=lowerCamelCase_						,    rstrip=lowerCamelCase_			) if isinstance(lowerCamelCase_						,    lowerCamelCase_			) else eos_token
     UpperCAmelCase__    						=   AddedToken(lowerCamelCase_						,    lstrip=lowerCamelCase_						,    rstrip=lowerCamelCase_			) if isinstance(lowerCamelCase_						,    lowerCamelCase_			) else unk_token
     UpperCAmelCase__    						=   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_						,    )
     UpperCAmelCase__    						=   add_bos_token

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

     # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
     UpperCAmelCase__    						=   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     :	Dict			)					->Any:
     '''simple docstring'''







     return len(self.encoder			)




   def 	UpperCAmelCase       (					self     :	Dict			)					->Optional[int]:
     '''simple docstring'''







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




   def 	UpperCAmelCase       (					self     :	Tuple						,    lowerCamelCase_     :	List[str]			)					->Optional[Any]:
     '''simple docstring'''







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

     if not pairs:
       return token

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




   def 	UpperCAmelCase       (					self     :	int						,    lowerCamelCase_     :	Optional[int]						,    lowerCamelCase_     :	Optional[Any]=None			)					->str:
     '''simple docstring'''







     if self.add_bos_token:
       UpperCAmelCase__    						=   [self.bos_token_id]
     else:
       UpperCAmelCase__    						=   []

     UpperCAmelCase__    						=   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     :	Any						,    lowerCamelCase_     :	Optional[Any]			)					->Union[str, Any]:
     '''simple docstring'''







     UpperCAmelCase__    						=   []
     for token in re.findall(self.pat						,    lowerCamelCase_			):
       UpperCAmelCase__    						=   """""".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     :	Dict						,    lowerCamelCase_     :	Optional[Any]			)					->int:
     '''simple docstring'''







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




   def 	UpperCAmelCase       (					self     :	Union[str, Any]						,    lowerCamelCase_     :	Dict			)					->Union[str, Any]:
     '''simple docstring'''







     return self.decoder.get(lowerCamelCase_			)




   def 	UpperCAmelCase       (					self     :	int						,    lowerCamelCase_     :	Union[str, Any]			)					->Union[str, Any]:
     '''simple docstring'''







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




   def 	UpperCAmelCase       (					self     :	Dict						,    lowerCamelCase_     :	str						,    lowerCamelCase_     :	Optional[str] = None			)					->Tuple[str]:
     '''simple docstring'''







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

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

     return vocab_file, merge_file




   def 	UpperCAmelCase       (					self     :	List[Any]						,    lowerCamelCase_     :	int						,    lowerCamelCase_     :	Tuple=False						,    **lowerCamelCase_     :	Any			)					->Any:
     '''simple docstring'''







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




   def 	UpperCAmelCase       (					self     :	List[Any]						,    lowerCamelCase_     :	Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"]						,    lowerCamelCase_     :	bool = False						,    lowerCamelCase_     :	bool = None						,    lowerCamelCase_     :	Optional[List[str]] = None						,    **lowerCamelCase_     :	Any						,    )					->str:
     '''simple docstring'''







     UpperCAmelCase__    						=   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:
       UpperCAmelCase__    						=   self.truncate(lowerCamelCase_						,    lowerCamelCase_			)

     return decoded_text







   def 	UpperCAmelCase       (					self     :	Tuple						,    lowerCamelCase_     :	Any						,    lowerCamelCase_     :	str			)					->Optional[int]:
     '''simple docstring'''







     def find_re(lowerCamelCase_     :	List[str]						,    lowerCamelCase_     :	Union[str, Any]						,    lowerCamelCase_     :	int			):
       UpperCAmelCase__    						=   pattern.search(lowerCamelCase_						,    lowerCamelCase_			)
       return m.start() if m else -1

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

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

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

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

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

     UpperCAmelCase__    						=   0

     UpperCAmelCase__    						=   [
         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




