
import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, RandomSampler, TensorDataset
from tqdm import tqdm

from transformers import GPTaLMHeadModel


lowercase        =  logging.getLogger(__name__)



def      __lowerCAmelCase						(							UpperCAmelCase__				:      str			,				UpperCAmelCase__				:      Optional[Any]       )  ->    Any:
							# save results
							if os.path.exists(UpperCAmelCase__       ):
														if os.path.exists(os.path.join(UpperCAmelCase__			,				"""config.json"""       )       ) and os.path.isfile(
														    os.path.join(UpperCAmelCase__			,				"""config.json"""       )       ):
																					os.remove(os.path.join(UpperCAmelCase__			,				"""config.json"""       )       )
														if os.path.exists(os.path.join(UpperCAmelCase__			,				"""pytorch_model.bin"""       )       ) and os.path.isfile(
														    os.path.join(UpperCAmelCase__			,				"""pytorch_model.bin"""       )       ):
																					os.remove(os.path.join(UpperCAmelCase__			,				"""pytorch_model.bin"""       )       )
							else:
														os.makedirs(UpperCAmelCase__       )
							model.save_pretrained(UpperCAmelCase__       )



def      __lowerCAmelCase						(							UpperCAmelCase__				:      List[str]			,				UpperCAmelCase__				:      Union[str, Any]=False       )  ->    int:
							lowerCamelCase_							  =					2
							if unlogit:
														lowerCamelCase_							  =					torch.pow(UpperCAmelCase__			,				UpperCAmelCase__       )
							lowerCamelCase_							  =					p * torch.log(UpperCAmelCase__       )
							lowerCamelCase_							  =					0
							return -plogp.sum(dim=-1       )



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Union[str, Any]       )  ->    Optional[int]:
							logger.info("""lv, h >\t""" + """\t""".join(F'''{x + 1}''' for x in range(len(UpperCAmelCase__       )       )       )       )
							for row in range(len(UpperCAmelCase__       )       ):
														if tensor.dtype != torch.long:
																					logger.info(F'''layer {row + 1}:\t''' + """\t""".join(F'''{x:.5f}''' for x in tensor[row].cpu().data       )       )
														else:
																					logger.info(F'''layer {row + 1}:\t''' + """\t""".join(F'''{x:d}''' for x in tensor[row].cpu().data       )       )



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Optional[int]			,				UpperCAmelCase__				:      Dict			,				UpperCAmelCase__				:      List[Any]			,				UpperCAmelCase__				:      int=True			,				UpperCAmelCase__				:      List[str]=True			,				UpperCAmelCase__				:      int=None			,				UpperCAmelCase__				:      Optional[int]=False       )  ->    int:
							lowerCamelCase_  ,   lowerCamelCase_							  =					model.config.num_hidden_layers, model.config.num_attention_heads
							lowerCamelCase_							  =					torch.zeros(UpperCAmelCase__			,				UpperCAmelCase__       ).to(args.device       )
							lowerCamelCase_							  =					torch.zeros(UpperCAmelCase__			,				UpperCAmelCase__       ).to(args.device       )

							if head_mask is None:
														lowerCamelCase_							  =					torch.ones(UpperCAmelCase__			,				UpperCAmelCase__       ).to(args.device       )

							head_mask.requires_grad_(requires_grad=UpperCAmelCase__       )
							# If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
							if actually_pruned:
														lowerCamelCase_							  =					None

							lowerCamelCase_							  =					0.0
							lowerCamelCase_							  =					0.0
							for step, inputs in enumerate(tqdm(UpperCAmelCase__			,				desc="""Iteration"""			,				disable=args.local_rank not in [-1, 0]       )       ):
														lowerCamelCase_							  =					tuple(t.to(args.device       ) for t in inputs       )
														((lowerCamelCase_)  ,   )							  =					inputs

														# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
														lowerCamelCase_							  =					model(UpperCAmelCase__			,				labels=UpperCAmelCase__			,				head_mask=UpperCAmelCase__       )
														#  (loss), lm_logits, presents, (all hidden_states), (attentions)
														lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					(
														    outputs[0],
														    outputs[1],
														    outputs[-1],
														)  # Loss and logits are the first, attention the last
														loss.backward()  # Backpropagate to populate the gradients in the head mask
														total_loss += loss.detach().cpu().numpy()
														if compute_entropy:
																					for layer, attn in enumerate(UpperCAmelCase__       ):
																												lowerCamelCase_							  =					entropy(attn.detach()			,				UpperCAmelCase__       )
																												attn_entropy[layer] += masked_entropy.sum(-1       ).sum(0       ).sum(0       ).detach()

														if compute_importance:
																					head_importance += head_mask.grad.abs().detach()
														tot_tokens += torch.ones_like(UpperCAmelCase__       ).float().detach().sum().data

							# Normalize
							attn_entropy /= tot_tokens
							head_importance /= tot_tokens
							# Layerwise importance normalization
							if not args.dont_normalize_importance_by_layer:
														lowerCamelCase_							  =					2
														lowerCamelCase_							  =					torch.pow(torch.pow(UpperCAmelCase__			,				UpperCAmelCase__       ).sum(-1       )			,				1 / exponent       )
														head_importance /= norm_by_layer.unsqueeze(-1       ) + 1e-20

							if not args.dont_normalize_global_importance:
														lowerCamelCase_							  =					(head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

							# Print matrices
							if compute_entropy:
														logger.info("""Attention entropies"""       )
														print_ad_tensor(UpperCAmelCase__       )
							if compute_importance:
														logger.info("""Head importance scores"""       )
														print_ad_tensor(UpperCAmelCase__       )
							logger.info("""Head ranked by importance scores"""       )
							lowerCamelCase_							  =					torch.zeros(head_importance.numel()			,				dtype=torch.long			,				device=args.device       )
							lowerCamelCase_							  =					torch.arange(
							    head_importance.numel()			,				device=args.device       )
							lowerCamelCase_							  =					head_ranks.view_as(UpperCAmelCase__       )
							print_ad_tensor(UpperCAmelCase__       )
							return attn_entropy, head_importance, total_loss



def      __lowerCAmelCase						(							UpperCAmelCase__				:      Tuple			,				UpperCAmelCase__				:      Optional[Any]			,				UpperCAmelCase__				:      Dict       )  ->    Optional[int]:
							lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					compute_heads_importance(UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__			,				compute_entropy=UpperCAmelCase__       )
							lowerCamelCase_							  =					1 / loss  # instead of downsteam score use the LM loss
							logger.info("""Pruning: original score: %f, threshold: %f"""			,				UpperCAmelCase__			,				original_score * args.masking_threshold       )

							lowerCamelCase_							  =					torch.ones_like(UpperCAmelCase__       )
							lowerCamelCase_							  =					max(1			,				int(new_head_mask.numel() * args.masking_amount       )       )

							lowerCamelCase_							  =					original_score
							while current_score >= original_score * args.masking_threshold:
														lowerCamelCase_							  =					new_head_mask.clone().detach()  # save current head mask
														# heads from least important to most - keep only not-masked heads
														lowerCamelCase_							  =					float("""Inf"""       )
														lowerCamelCase_							  =					head_importance.view(-1       ).sort()[1]

														if len(UpperCAmelCase__       ) <= num_to_mask:
																					print("""BREAK BY num_to_mask"""       )
																					break

														# mask heads
														lowerCamelCase_							  =					current_heads_to_mask[:num_to_mask]
														logger.info("""Heads to mask: %s"""			,				str(current_heads_to_mask.tolist()       )       )
														lowerCamelCase_							  =					new_head_mask.view(-1       )
														lowerCamelCase_							  =					0.0
														lowerCamelCase_							  =					new_head_mask.view_as(UpperCAmelCase__       )
														lowerCamelCase_							  =					new_head_mask.clone().detach()
														print_ad_tensor(UpperCAmelCase__       )

														# Compute metric and head importance again
														lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					compute_heads_importance(
														    UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__			,				compute_entropy=UpperCAmelCase__			,				head_mask=UpperCAmelCase__       )
														lowerCamelCase_							  =					1 / loss
														logger.info(
														    """Masking: current score: %f, remaining heads %d (%.1f percents)"""			,				UpperCAmelCase__			,				new_head_mask.sum()			,				new_head_mask.sum() / new_head_mask.numel() * 1_0_0			,				)

							logger.info("""Final head mask"""       )
							print_ad_tensor(UpperCAmelCase__       )
							np.save(os.path.join(args.output_dir			,				"""head_mask.npy"""       )			,				head_mask.detach().cpu().numpy()       )

							return head_mask



def      __lowerCAmelCase						(							UpperCAmelCase__				:      List[Any]			,				UpperCAmelCase__				:      Tuple			,				UpperCAmelCase__				:      List[Any]			,				UpperCAmelCase__				:      Optional[int]       )  ->    int:
							lowerCamelCase_							  =					datetime.now()
							lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					compute_heads_importance(
							    UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__			,				compute_entropy=UpperCAmelCase__			,				compute_importance=UpperCAmelCase__			,				head_mask=UpperCAmelCase__       )
							lowerCamelCase_							  =					1 / loss
							lowerCamelCase_							  =					datetime.now() - before_time

							lowerCamelCase_							  =					sum(p.numel() for p in model.parameters()       )
							lowerCamelCase_							  =					{
							    layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCAmelCase__       )       )
							}

							for k, v in heads_to_prune.items():
														if isinstance(UpperCAmelCase__			,				UpperCAmelCase__       ):
																					lowerCamelCase_							  =					[
																					    v,
																					]

							assert sum(len(UpperCAmelCase__       ) for h in heads_to_prune.values()       ) == (1 - head_mask.long()).sum().item()
							model.prune_heads(UpperCAmelCase__       )
							lowerCamelCase_							  =					sum(p.numel() for p in model.parameters()       )

							lowerCamelCase_							  =					datetime.now()
							lowerCamelCase_  ,   lowerCamelCase_  ,   lowerCamelCase_							  =					compute_heads_importance(
							    UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__			,				compute_entropy=UpperCAmelCase__			,				compute_importance=UpperCAmelCase__			,				head_mask=UpperCAmelCase__			,				actually_pruned=UpperCAmelCase__			,				)

							lowerCamelCase_							  =					1 / loss
							lowerCamelCase_							  =					datetime.now() - before_time

							logger.info(
							    """Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)"""			,				UpperCAmelCase__			,				UpperCAmelCase__			,				pruned_num_params / original_num_params * 1_0_0			,				)
							logger.info("""Pruning: score with masking: %f score with pruning: %f"""			,				UpperCAmelCase__			,				UpperCAmelCase__       )
							logger.info("""Pruning: speed ratio (original timing / new timing): %f percents"""			,				original_time / new_time * 1_0_0       )
							save_model(UpperCAmelCase__			,				args.output_dir       )



def      __lowerCAmelCase						(							)  ->    Optional[Any]:
							lowerCamelCase_							  =					argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    """--data_dir"""			,				default=UpperCAmelCase__			,				type=UpperCAmelCase__			,				required=UpperCAmelCase__			,				help="""The input data dir. Should contain the .tsv files (or other data files) for the task."""			,				)
							parser.add_argument(
							    """--model_name_or_path"""			,				default=UpperCAmelCase__			,				type=UpperCAmelCase__			,				required=UpperCAmelCase__			,				help="""Path to pretrained model or model identifier from huggingface.co/models"""			,				)
							parser.add_argument(
							    """--output_dir"""			,				default=UpperCAmelCase__			,				type=UpperCAmelCase__			,				required=UpperCAmelCase__			,				help="""The output directory where the model predictions and checkpoints will be written."""			,				)

							# Other parameters
							parser.add_argument(
							    """--config_name"""			,				default=""""""			,				type=UpperCAmelCase__			,				help="""Pretrained config name or path if not the same as model_name_or_path"""			,				)
							parser.add_argument(
							    """--tokenizer_name"""			,				default=""""""			,				type=UpperCAmelCase__			,				help="""Pretrained tokenizer name or path if not the same as model_name_or_path"""			,				)
							parser.add_argument(
							    """--cache_dir"""			,				default=UpperCAmelCase__			,				type=UpperCAmelCase__			,				help="""Where do you want to store the pre-trained models downloaded from s3"""			,				)
							parser.add_argument(
							    """--data_subset"""			,				type=UpperCAmelCase__			,				default=-1			,				help="""If > 0: limit the data to a subset of data_subset instances."""       )
							parser.add_argument(
							    """--overwrite_output_dir"""			,				action="""store_true"""			,				help="""Whether to overwrite data in output directory"""       )
							parser.add_argument(
							    """--overwrite_cache"""			,				action="""store_true"""			,				help="""Overwrite the cached training and evaluation sets"""       )

							parser.add_argument(
							    """--dont_normalize_importance_by_layer"""			,				action="""store_true"""			,				help="""Don't normalize importance score by layers"""       )
							parser.add_argument(
							    """--dont_normalize_global_importance"""			,				action="""store_true"""			,				help="""Don't normalize all importance scores between 0 and 1"""			,				)

							parser.add_argument(
							    """--try_masking"""			,				action="""store_true"""			,				help="""Whether to try to mask head until a threshold of accuracy."""       )
							parser.add_argument(
							    """--masking_threshold"""			,				default=0.9			,				type=UpperCAmelCase__			,				help="""masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."""			,				)
							parser.add_argument(
							    """--masking_amount"""			,				default=0.1			,				type=UpperCAmelCase__			,				help="""Amount to heads to masking at each masking step."""       )
							parser.add_argument("""--metric_name"""			,				default="""acc"""			,				type=UpperCAmelCase__			,				help="""Metric to use for head masking."""       )

							parser.add_argument(
							    """--max_seq_length"""			,				default=1_2_8			,				type=UpperCAmelCase__			,				help=(
							        """The maximum total input sequence length after WordPiece tokenization. \n"""
							        """Sequences longer than this will be truncated, sequences shorter padded."""
							    )			,				)
							parser.add_argument("""--batch_size"""			,				default=1			,				type=UpperCAmelCase__			,				help="""Batch size."""       )

							parser.add_argument("""--seed"""			,				type=UpperCAmelCase__			,				default=4_2       )
							parser.add_argument("""--local_rank"""			,				type=UpperCAmelCase__			,				default=-1			,				help="""local_rank for distributed training on gpus"""       )
							parser.add_argument("""--no_cuda"""			,				action="""store_true"""			,				help="""Whether not to use CUDA when available"""       )
							parser.add_argument("""--server_ip"""			,				type=UpperCAmelCase__			,				default=""""""			,				help="""Can be used for distant debugging."""       )
							parser.add_argument("""--server_port"""			,				type=UpperCAmelCase__			,				default=""""""			,				help="""Can be used for distant debugging."""       )
							lowerCamelCase_							  =					parser.parse_args()

							if args.server_ip and args.server_port:
														# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
														import ptvsd

														print("""Waiting for debugger attach"""       )
														ptvsd.enable_attach(address=(args.server_ip, args.server_port)			,				redirect_output=UpperCAmelCase__       )
														ptvsd.wait_for_attach()

							# Setup devices and distributed training
							if args.local_rank == -1 or args.no_cuda:
														lowerCamelCase_							  =					torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""       )
														lowerCamelCase_							  =					0 if args.no_cuda else torch.cuda.device_count()
							else:
														torch.cuda.set_device(args.local_rank       )
														lowerCamelCase_							  =					torch.device("""cuda"""			,				args.local_rank       )
														lowerCamelCase_							  =					1
														torch.distributed.init_process_group(backend="""nccl"""       )  # Initializes the distributed backend

							# Setup logging
							logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN       )
							logger.info("""device: {} n_gpu: {}, distributed: {}""".format(args.device			,				args.n_gpu			,				bool(args.local_rank != -1       )       )       )

							lowerCamelCase_							  =					GPTaLMHeadModel.from_pretrained(args.model_name_or_path       )

							# Distributed and parallel training
							model.to(args.device       )
							if args.local_rank != -1:
														lowerCamelCase_							  =					nn.parallel.DistributedDataParallel(
														    UpperCAmelCase__			,				device_ids=[args.local_rank]			,				output_device=args.local_rank			,				find_unused_parameters=UpperCAmelCase__       )
							elif args.n_gpu > 1:
														lowerCamelCase_							  =					nn.DataParallel(UpperCAmelCase__       )

							# Print/save training arguments
							os.makedirs(args.output_dir			,				exist_ok=UpperCAmelCase__       )
							torch.save(UpperCAmelCase__			,				os.path.join(args.output_dir			,				"""run_args.bin"""       )       )
							logger.info("""Training/evaluation parameters %s"""			,				UpperCAmelCase__       )

							# Prepare dataset
							lowerCamelCase_							  =					np.concatenate(
							    [
							        np.loadtxt(args.data_dir			,				dtype=np.intaa       ),
							    ]       )
							lowerCamelCase_							  =					(torch.from_numpy(UpperCAmelCase__       ),)
							lowerCamelCase_							  =					TensorDataset(*UpperCAmelCase__       )
							lowerCamelCase_							  =					RandomSampler(UpperCAmelCase__       )
							lowerCamelCase_							  =					DataLoader(UpperCAmelCase__			,				sampler=UpperCAmelCase__			,				batch_size=args.batch_size       )

							# Compute head entropy and importance score
							compute_heads_importance(UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__       )

							# Try head masking (set heads to zero until the score goes under a threshole)
							# and head pruning (remove masked heads and see the effect on the network)
							if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
														lowerCamelCase_							  =					mask_heads(UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__       )
														prune_heads(UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__			,				UpperCAmelCase__       )


if __name__ == "__main__":
		main()







import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
		import jieba

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase        =  logging.get_logger(__name__)

lowercase        =  {'''vocab_file''': '''vocab.txt'''}

lowercase        =  {
    '''vocab_file''': {
        '''openbmb/cpm-ant-10b''': '''https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt''',
    },
}

lowercase        =  {
    '''openbmb/cpm-ant-10b''': 1_0_2_4,
}



def      __lowerCAmelCase						(							UpperCAmelCase__				:      List[str]       )  ->    Dict:
							lowerCamelCase_							  =					collections.OrderedDict()
							with open(UpperCAmelCase__			,				"""r"""			,				encoding="""utf-8"""       ) as reader:
														lowerCamelCase_							  =					reader.readlines()
							for index, token in enumerate(UpperCAmelCase__       ):
														lowerCamelCase_							  =					token.rstrip("""\n"""       )
														lowerCamelCase_							  =					index
							return vocab





class       __A(				UpperCAmelCase       ):

					def __init__(	self					:     Optional[Any]   ,					__UpperCamelCase					:     Tuple   ,					__UpperCamelCase					:     List[str]="<unk>"   ,					__UpperCamelCase					:     List[str]=2_0_0   ):
												lowerCamelCase_							  =					vocab
												lowerCamelCase_							  =					unk_token
												lowerCamelCase_							  =					max_input_chars_per_word



					def    lowercase__      (	self					:     int   ,					__UpperCamelCase					:     int   ):
												lowerCamelCase_							  =					list(__UpperCamelCase   )
												if len(__UpperCamelCase   ) > self.max_input_chars_per_word:
																			return [self.unk_token]

												lowerCamelCase_							  =					0
												lowerCamelCase_							  =					[]
												while start < len(__UpperCamelCase   ):
																			lowerCamelCase_							  =					len(__UpperCamelCase   )
																			lowerCamelCase_							  =					None
																			while start < end:
																										lowerCamelCase_							  =					"""""".join(chars[start:end]   )
																										if substr in self.vocab:
																																	lowerCamelCase_							  =					substr
																																	break
																										end -= 1
																			if cur_substr is None:
																										sub_tokens.append(self.unk_token   )
																										start += 1
																			else:
																										sub_tokens.append(__UpperCamelCase   )
																										lowerCamelCase_							  =					end

												return sub_tokens





class       __A(				UpperCAmelCase       ):
					SCREAMING_SNAKE_CASE			    =    VOCAB_FILES_NAMES
					SCREAMING_SNAKE_CASE			    =    PRETRAINED_VOCAB_FILES_MAP
					SCREAMING_SNAKE_CASE			    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					SCREAMING_SNAKE_CASE			    =    ['''input_ids''', '''attention_mask''']
					SCREAMING_SNAKE_CASE			    =    False

					def __init__(	self					:     int   ,					__UpperCamelCase					:     Optional[int]   ,					__UpperCamelCase					:     Optional[int]="<d>"   ,					__UpperCamelCase					:     List[str]="</d>"   ,					__UpperCamelCase					:     Optional[Any]="<s>"   ,					__UpperCamelCase					:     Union[str, Any]="</s>"   ,					__UpperCamelCase					:     List[str]="<pad>"   ,					__UpperCamelCase					:     Union[str, Any]="<unk>"   ,					__UpperCamelCase					:     List[Any]="</n>"   ,					__UpperCamelCase					:     Tuple="</_>"   ,					__UpperCamelCase					:     Optional[Any]="left"   ,					**__UpperCamelCase					:     List[str]   ,					):
												requires_backends(self   ,					["""jieba"""]   )
												super().__init__(
												    bod_token=__UpperCamelCase   ,					eod_token=__UpperCamelCase   ,					bos_token=__UpperCamelCase   ,					eos_token=__UpperCamelCase   ,					pad_token=__UpperCamelCase   ,					unk_token=__UpperCamelCase   ,					line_token=__UpperCamelCase   ,					space_token=__UpperCamelCase   ,					padding_side=__UpperCamelCase   ,					**__UpperCamelCase   ,					)
												lowerCamelCase_							  =					bod_token
												lowerCamelCase_							  =					eod_token
												lowerCamelCase_							  =					load_vocab(__UpperCamelCase   )
												lowerCamelCase_							  =					self.encoder[space_token]
												lowerCamelCase_							  =					self.encoder[line_token]

												del self.encoder[space_token]
												del self.encoder[line_token]

												lowerCamelCase_							  =					collections.OrderedDict(sorted(self.encoder.items()   ,					key=lambda __UpperCamelCase   : x[1]   )   )
												lowerCamelCase_							  =					{v: k for k, v in self.encoder.items()}

												lowerCamelCase_							  =					WordpieceTokenizer(vocab=self.encoder   ,					unk_token=self.unk_token   )

					@property
					def    lowercase__      (	self					:     Any   ):
												return self.encoder[self.bod_token]

					@property
					def    lowercase__      (	self					:     Any   ):
												return self.encoder[self.eod_token]

					@property
					def    lowercase__      (	self					:     int   ):
												return self.encoder["\n"]

					@property
					def    lowercase__      (	self					:     str   ):
												return len(self.encoder   )

					def    lowercase__      (	self					:     Any   ):
												return dict(self.encoder   ,					**self.added_tokens_encoder   )

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     Optional[Any]   ):
												lowerCamelCase_							  =					[]
												for x in jieba.cut(__UpperCamelCase   ,					cut_all=__UpperCamelCase   ):
																			output_tokens.extend(self.wordpiece_tokenizer.tokenize(__UpperCamelCase   )   )
												return output_tokens

					def    lowercase__      (	self					:     Optional[Any]   ,					__UpperCamelCase					:     Dict   ,					**__UpperCamelCase					:     str   ):
												lowerCamelCase_							  =					[i for i in token_ids if i >= 0]
												lowerCamelCase_							  =					[
												    x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
												]
												return super()._decode(__UpperCamelCase   ,					**__UpperCamelCase   )

					def    lowercase__      (	self					:     Dict   ,					__UpperCamelCase					:     Optional[Any]   ):
												return token in self.encoder

					def    lowercase__      (	self					:     int   ,					__UpperCamelCase					:     List[str]   ):
												return "".join(__UpperCamelCase   )

					def    lowercase__      (	self					:     List[str]   ,					__UpperCamelCase					:     int   ):
												return self.encoder.get(__UpperCamelCase   ,					self.encoder.get(self.unk_token   )   )

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     Union[str, Any]   ):
												return self.decoder.get(__UpperCamelCase   ,					self.unk_token   )

					def    lowercase__      (	self					:     Union[str, Any]   ,					__UpperCamelCase					:     str   ,					__UpperCamelCase					:     Optional[str] = None   ):
												if os.path.isdir(__UpperCamelCase   ):
																			lowerCamelCase_							  =					os.path.join(
																			    __UpperCamelCase   ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )
												else:
																			lowerCamelCase_							  =					(filename_prefix + """-""" if filename_prefix else """""") + save_directory
												lowerCamelCase_							  =					0
												if " " in self.encoder:
																			lowerCamelCase_							  =					self.encoder[""" """]
																			del self.encoder[" "]
												if "\n" in self.encoder:
																			lowerCamelCase_							  =					self.encoder["""\n"""]
																			del self.encoder["\n"]
												lowerCamelCase_							  =					collections.OrderedDict(sorted(self.encoder.items()   ,					key=lambda __UpperCamelCase   : x[1]   )   )
												with open(__UpperCamelCase   ,					"""w"""   ,					encoding="""utf-8"""   ) as writer:
																			for token, token_index in self.encoder.items():
																										if index != token_index:
																																	logger.warning(
																																	    F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
																																	    """ Please check that the vocabulary is not corrupted!"""   )
																																	lowerCamelCase_							  =					token_index
																										writer.write(token + """\n"""   )
																										index += 1
												return (vocab_file,)

					def    lowercase__      (	self					:     Any   ,					__UpperCamelCase					:     List[int]   ,					__UpperCamelCase					:     List[int] = None   ):
												if token_ids_a is None:
																			return [self.bos_token_id] + token_ids_a
												return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a



					def    lowercase__      (	self					:     int   ,					__UpperCamelCase					:     List[int]   ,					__UpperCamelCase					:     Optional[List[int]] = None   ,					__UpperCamelCase					:     bool = False   ):

												if already_has_special_tokens:
																			return super().get_special_tokens_mask(
																			    token_ids_a=__UpperCamelCase   ,					token_ids_a=__UpperCamelCase   ,					already_has_special_tokens=__UpperCamelCase   )

												if token_ids_a is not None:
																			return [1] + ([0] * len(__UpperCamelCase   )) + [1] + ([0] * len(__UpperCamelCase   ))
												return [1] + ([0] * len(__UpperCamelCase   ))





