



'''simple docstring'''

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, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


UpperCAmelCase			=    logging.getLogger(__name__)






def 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						Any							)			->						Tuple:







	"""simple docstring"""
	lowerCAmelCase    =	p * torch.log(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	0
	return -plogp.sum(dim=-1							)






def 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						Dict							)			->						List[Any]:







	"""simple docstring"""
	logger.info("""lv, h >\t""" + """\t""".join(f'{x + 1}' for x in range(len(_SCREAMING_SNAKE_CASE							)							)							)							)
	for row in range(len(_SCREAMING_SNAKE_CASE							)							):
		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 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						Tuple							,		_SCREAMING_SNAKE_CASE     :						Dict							,		_SCREAMING_SNAKE_CASE     :						Tuple							,		_SCREAMING_SNAKE_CASE     :						List[str]=True							,		_SCREAMING_SNAKE_CASE     :						List[Any]=True							,		_SCREAMING_SNAKE_CASE     :						Any=None							,		_SCREAMING_SNAKE_CASE     :						int=False							)			->						Optional[int]:







	"""simple docstring"""
	lowerCAmelCase,   lowerCAmelCase    =	model.config.num_hidden_layers, model.config.num_attention_heads
	lowerCAmelCase    =	torch.zeros(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							).to(args.device							)
	lowerCAmelCase    =	torch.zeros(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							).to(args.device							)

	if head_mask is None:
		lowerCAmelCase    =	torch.ones(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							).to(args.device							)

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

	lowerCAmelCase    =	None
	lowerCAmelCase    =	None
	lowerCAmelCase    =	0.0

	for step, inputs in enumerate(tqdm(_SCREAMING_SNAKE_CASE							,		desc="""Iteration"""							,		disable=args.local_rank not in [-1, 0]							)							):
		for k, v in inputs.items():
			lowerCAmelCase    =	v.to(args.device							)

		# Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
		lowerCAmelCase    =	model(**_SCREAMING_SNAKE_CASE							,		head_mask=_SCREAMING_SNAKE_CASE							)
		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

		if compute_entropy:
			for layer, attn in enumerate(_SCREAMING_SNAKE_CASE							):
				lowerCAmelCase    =	entropy(attn.detach()							) * inputs["""attention_mask"""].float().unsqueeze(1							)
				attn_entropy[layer] += masked_entropy.sum(-1							).sum(0							).detach()

		if compute_importance:
			head_importance += head_mask.grad.abs().detach()

		# Also store our logits/labels if we want to compute metrics afterwards
		if preds is None:
			lowerCAmelCase    =	logits.detach().cpu().numpy()
			lowerCAmelCase    =	inputs["""labels"""].detach().cpu().numpy()
		else:
			lowerCAmelCase    =	np.append(_SCREAMING_SNAKE_CASE							,		logits.detach().cpu().numpy()							,		axis=0							)
			lowerCAmelCase    =	np.append(_SCREAMING_SNAKE_CASE							,		inputs["""labels"""].detach().cpu().numpy()							,		axis=0							)

		tot_tokens += inputs["attention_mask"].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(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							).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/save matrices
	np.save(os.path.join(args.output_dir							,		"""attn_entropy.npy"""							)							,		attn_entropy.detach().cpu().numpy()							)
	np.save(os.path.join(args.output_dir							,		"""head_importance.npy"""							)							,		head_importance.detach().cpu().numpy()							)

	logger.info("""Attention entropies"""							)
	print_ad_tensor(_SCREAMING_SNAKE_CASE							)
	logger.info("""Head importance scores"""							)
	print_ad_tensor(_SCREAMING_SNAKE_CASE							)
	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(_SCREAMING_SNAKE_CASE							)
	print_ad_tensor(_SCREAMING_SNAKE_CASE							)

	return attn_entropy, head_importance, preds, labels






def 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						List[Any]							,		_SCREAMING_SNAKE_CASE     :						Union[str, Any]							,		_SCREAMING_SNAKE_CASE     :						List[Any]							)			->						Any:







	"""simple docstring"""
	lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	compute_heads_importance(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		compute_entropy=_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	np.argmax(_SCREAMING_SNAKE_CASE							,		axis=1							) if args.output_mode == """classification""" else np.squeeze(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	glue_compute_metrics(args.task_name							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)[args.metric_name]
	logger.info("""Pruning: original score: %f, threshold: %f"""							,		_SCREAMING_SNAKE_CASE							,		original_score * args.masking_threshold							)

	lowerCAmelCase    =	torch.ones_like(_SCREAMING_SNAKE_CASE							)
	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()  # 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(_SCREAMING_SNAKE_CASE							) <= 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(_SCREAMING_SNAKE_CASE							)
		lowerCAmelCase    =	new_head_mask.clone().detach()
		print_ad_tensor(_SCREAMING_SNAKE_CASE							)

		# Compute metric and head importance again
		lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	compute_heads_importance(
		    _SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		compute_entropy=_SCREAMING_SNAKE_CASE							,		head_mask=_SCREAMING_SNAKE_CASE							)
		lowerCAmelCase    =	np.argmax(_SCREAMING_SNAKE_CASE							,		axis=1							) if args.output_mode == """classification""" else np.squeeze(_SCREAMING_SNAKE_CASE							)
		lowerCAmelCase    =	glue_compute_metrics(args.task_name							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)[args.metric_name]
		logger.info(
		    """Masking: current score: %f, remaining heads %d (%.1f percents)"""							,		_SCREAMING_SNAKE_CASE							,		new_head_mask.sum()							,		new_head_mask.sum() / new_head_mask.numel() * 100							,		)

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

	return head_mask






def 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						Tuple							,		_SCREAMING_SNAKE_CASE     :						Any							,		_SCREAMING_SNAKE_CASE     :						int							,		_SCREAMING_SNAKE_CASE     :						str							)			->						Optional[Any]:







	"""simple docstring"""
	lowerCAmelCase    =	datetime.now()
	lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	compute_heads_importance(
	    _SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		compute_entropy=_SCREAMING_SNAKE_CASE							,		compute_importance=_SCREAMING_SNAKE_CASE							,		head_mask=_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	np.argmax(_SCREAMING_SNAKE_CASE							,		axis=1							) if args.output_mode == """classification""" else np.squeeze(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	glue_compute_metrics(args.task_name							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)[args.metric_name]
	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(_SCREAMING_SNAKE_CASE							)							)
	}

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

	lowerCAmelCase    =	datetime.now()
	lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	compute_heads_importance(
	    _SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		compute_entropy=_SCREAMING_SNAKE_CASE							,		compute_importance=_SCREAMING_SNAKE_CASE							,		head_mask=_SCREAMING_SNAKE_CASE							,		actually_pruned=_SCREAMING_SNAKE_CASE							,		)
	lowerCAmelCase    =	np.argmax(_SCREAMING_SNAKE_CASE							,		axis=1							) if args.output_mode == """classification""" else np.squeeze(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	glue_compute_metrics(args.task_name							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)[args.metric_name]
	lowerCAmelCase    =	datetime.now() - before_time

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






def 		_snake_case		(					)			->						Any:







	"""simple docstring"""
	lowerCAmelCase    =	argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    """--data_dir"""							,		default=_SCREAMING_SNAKE_CASE							,		type=_SCREAMING_SNAKE_CASE							,		required=_SCREAMING_SNAKE_CASE							,		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=_SCREAMING_SNAKE_CASE							,		type=_SCREAMING_SNAKE_CASE							,		required=_SCREAMING_SNAKE_CASE							,		help="""Path to pretrained model or model identifier from huggingface.co/models"""							,		)
	parser.add_argument(
	    """--task_name"""							,		default=_SCREAMING_SNAKE_CASE							,		type=_SCREAMING_SNAKE_CASE							,		required=_SCREAMING_SNAKE_CASE							,		help="""The name of the task to train selected in the list: """ + """, """.join(glue_processors.keys()							)							,		)
	parser.add_argument(
	    """--output_dir"""							,		default=_SCREAMING_SNAKE_CASE							,		type=_SCREAMING_SNAKE_CASE							,		required=_SCREAMING_SNAKE_CASE							,		help="""The output directory where the model predictions and checkpoints will be written."""							,		)

	# Other parameters
	parser.add_argument(
	    """--config_name"""							,		default=""""""							,		type=_SCREAMING_SNAKE_CASE							,		help="""Pretrained config name or path if not the same as model_name_or_path"""							,		)
	parser.add_argument(
	    """--tokenizer_name"""							,		default=""""""							,		type=_SCREAMING_SNAKE_CASE							,		help="""Pretrained tokenizer name or path if not the same as model_name_or_path"""							,		)
	parser.add_argument(
	    """--cache_dir"""							,		default=_SCREAMING_SNAKE_CASE							,		type=_SCREAMING_SNAKE_CASE							,		help="""Where do you want to store the pre-trained models downloaded from huggingface.co"""							,		)
	parser.add_argument(
	    """--data_subset"""							,		type=_SCREAMING_SNAKE_CASE							,		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=_SCREAMING_SNAKE_CASE							,		help="""masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."""							,		)
	parser.add_argument(
	    """--masking_amount"""							,		default=0.1							,		type=_SCREAMING_SNAKE_CASE							,		help="""Amount to heads to masking at each masking step."""							)
	parser.add_argument("""--metric_name"""							,		default="""acc"""							,		type=_SCREAMING_SNAKE_CASE							,		help="""Metric to use for head masking."""							)

	parser.add_argument(
	    """--max_seq_length"""							,		default=128							,		type=_SCREAMING_SNAKE_CASE							,		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=_SCREAMING_SNAKE_CASE							,		help="""Batch size."""							)

	parser.add_argument("""--seed"""							,		type=_SCREAMING_SNAKE_CASE							,		default=42							)
	parser.add_argument("""--local_rank"""							,		type=_SCREAMING_SNAKE_CASE							,		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=_SCREAMING_SNAKE_CASE							,		default=""""""							,		help="""Can be used for distant debugging."""							)
	parser.add_argument("""--server_port"""							,		type=_SCREAMING_SNAKE_CASE							,		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=_SCREAMING_SNAKE_CASE							)
		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							)							)							)
	# Set the verbosity to info of the Transformers logger (on main process only):
	if is_main_process(args.local_rank							):
		transformers.utils.logging.set_verbosity_info()
		transformers.utils.logging.enable_default_handler()
		transformers.utils.logging.enable_explicit_format()

	# Set seeds
	set_seed(args.seed							)

	# Prepare GLUE task
	lowerCAmelCase    =	args.task_name.lower()
	if args.task_name not in glue_processors:
		raise ValueError("""Task not found: %s""" % (args.task_name)							)
	lowerCAmelCase    =	glue_processors[args.task_name]()
	lowerCAmelCase    =	glue_output_modes[args.task_name]
	lowerCAmelCase    =	processor.get_labels()
	lowerCAmelCase    =	len(_SCREAMING_SNAKE_CASE							)

	# Load pretrained model and tokenizer
	#
	# Distributed training:
	# The .from_pretrained methods guarantee that only one local process can concurrently
	# download model & vocab.

	lowerCAmelCase    =	AutoConfig.from_pretrained(
	    args.config_name if args.config_name else args.model_name_or_path							,		num_labels=_SCREAMING_SNAKE_CASE							,		finetuning_task=args.task_name							,		output_attentions=_SCREAMING_SNAKE_CASE							,		cache_dir=args.cache_dir							,		)
	lowerCAmelCase    =	AutoTokenizer.from_pretrained(
	    args.tokenizer_name if args.tokenizer_name else args.model_name_or_path							,		cache_dir=args.cache_dir							,		)
	lowerCAmelCase    =	AutoModelForSequenceClassification.from_pretrained(
	    args.model_name_or_path							,		from_tf=bool(""".ckpt""" in args.model_name_or_path							)							,		config=_SCREAMING_SNAKE_CASE							,		cache_dir=args.cache_dir							,		)

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

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

	# Prepare dataset for the GLUE task
	lowerCAmelCase    =	GlueDataset(_SCREAMING_SNAKE_CASE							,		tokenizer=_SCREAMING_SNAKE_CASE							,		mode="""dev"""							)
	if args.data_subset > 0:
		lowerCAmelCase    =	Subset(_SCREAMING_SNAKE_CASE							,		list(range(min(args.data_subset							,		len(_SCREAMING_SNAKE_CASE							)							)							)							)							)
	lowerCAmelCase    =	SequentialSampler(_SCREAMING_SNAKE_CASE							) if args.local_rank == -1 else DistributedSampler(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	DataLoader(
	    _SCREAMING_SNAKE_CASE							,		sampler=_SCREAMING_SNAKE_CASE							,		batch_size=args.batch_size							,		collate_fn=_SCREAMING_SNAKE_CASE							)

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

	# 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(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)
		prune_heads(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)


if __name__ == "__main__":
				main()




'''simple docstring'''

import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
				from transformers.pipelines.conversational import Conversation

UpperCAmelCase			=    logging.get_logger(__name__)

UpperCAmelCase			=    {'vocab_file': 'tokenizer.model'}

UpperCAmelCase			=    {
    'vocab_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model',
    },
    'tokenizer_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json',
    },
}
UpperCAmelCase			=    {
    'hf-internal-testing/llama-tokenizer': 2048,
}
UpperCAmelCase			=    '▁'

UpperCAmelCase		,   UpperCAmelCase			=    '[INST]', '[/INST]'
UpperCAmelCase		,   UpperCAmelCase			=    '<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
UpperCAmelCase			=    'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'

class __snake_case(      _lowerCAmelCase					):


						'''simple docstring'''



						UpperCAmelCase							:    str           =		VOCAB_FILES_NAMES
						UpperCAmelCase							:    Optional[Any]           =		PRETRAINED_VOCAB_FILES_MAP
						UpperCAmelCase							:    Optional[Any]           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						UpperCAmelCase							:    Tuple           =		["input_ids", "attention_mask"]


						def __init__(					self	,       A_	,       A_="<unk>"	,       A_="<s>"	,       A_="</s>"	,       A_=None	,       A_ = None	,       A_=True	,       A_=False	,       A_=False	,       A_=True	,       **A_	,       )	->	Dict:
							lowerCAmelCase    =	{} if sp_model_kwargs is None else sp_model_kwargs
							lowerCAmelCase    =	AddedToken(A_	,       lstrip=A_	,       rstrip=A_      ) if isinstance(A_	,       A_      ) else bos_token
							lowerCAmelCase    =	AddedToken(A_	,       lstrip=A_	,       rstrip=A_      ) if isinstance(A_	,       A_      ) else eos_token
							lowerCAmelCase    =	AddedToken(A_	,       lstrip=A_	,       rstrip=A_      ) if isinstance(A_	,       A_      ) else unk_token
							lowerCAmelCase    =	AddedToken(A_	,       lstrip=A_	,       rstrip=A_      ) if isinstance(A_	,       A_      ) else pad_token
							super().__init__(
							    bos_token=A_	,       eos_token=A_	,       unk_token=A_	,       pad_token=A_	,       add_bos_token=A_	,       add_eos_token=A_	,       sp_model_kwargs=self.sp_model_kwargs	,       clean_up_tokenization_spaces=A_	,       legacy=A_	,       **A_	,       )
							if legacy:
								logger.warning_once(
								    f'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'
								    """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565"""      )
							lowerCAmelCase    =	legacy
							lowerCAmelCase    =	vocab_file
							lowerCAmelCase    =	add_bos_token
							lowerCAmelCase    =	add_eos_token
							lowerCAmelCase    =	spm.SentencePieceProcessor(**self.sp_model_kwargs      )
							self.sp_model.Load(A_      )


						def __getstate__(					self      )	->	List[str]:
							lowerCAmelCase    =	self.__dict__.copy()
							lowerCAmelCase    =	None
							lowerCAmelCase    =	self.sp_model.serialized_model_proto()
							return state


						def __setstate__(					self	,       A_      )	->	List[Any]:
							lowerCAmelCase    =	d
							lowerCAmelCase    =	spm.SentencePieceProcessor(**self.sp_model_kwargs      )
							self.sp_model.LoadFromSerializedProto(self.sp_model_proto      )


						@property
						def 				__snake_case    (					self      )	->	Optional[int]:
							return self.sp_model.get_piece_size()


						def 				__snake_case    (					self      )	->	Optional[int]:
							lowerCAmelCase    =	{self.convert_ids_to_tokens(A_      ): i for i in range(self.vocab_size      )}
							vocab.update(self.added_tokens_encoder      )
							return vocab


						def 				__snake_case    (					self	,       A_	,       **A_      )	->	List[str]:
							# Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
							# the beginning of the text
							if not self.legacy:
								lowerCAmelCase    =	SPIECE_UNDERLINE + text.replace(A_	,       """ """      )
							return super().tokenize(A_	,       **A_      )


						def 				__snake_case    (					self	,       A_      )	->	Tuple:
							if not self.legacy:
								lowerCAmelCase    =	text.startswith(A_      )
								if is_first:
									lowerCAmelCase    =	text[1:]

							lowerCAmelCase    =	self.sp_model.encode(A_	,       out_type=A_      )

							if not self.legacy and not is_first and not text.startswith(""" """      ) and tokens[0].startswith(A_      ):
								lowerCAmelCase    =	([tokens[0][1:]] if len(tokens[0]      ) > 1 else []) + tokens[1:]
							return tokens


						def 				__snake_case    (					self	,       A_      )	->	List[str]:
							return self.sp_model.piece_to_id(A_      )


						def 				__snake_case    (					self	,       A_      )	->	str:
							lowerCAmelCase    =	self.sp_model.IdToPiece(A_      )
							return token


						def 				__snake_case    (					self	,       A_      )	->	Dict:
							lowerCAmelCase    =	[]
							lowerCAmelCase    =	""""""
							lowerCAmelCase    =	False
							for i, token in enumerate(A_      ):
								# make sure that special tokens are not decoded using sentencepiece model
								if token in self.all_special_tokens:
									if not prev_is_special and i != 0:
										out_string += " "
									out_string += self.sp_model.decode(A_      ) + token
									lowerCAmelCase    =	True
									lowerCAmelCase    =	[]
								else:
									current_sub_tokens.append(A_      )
									lowerCAmelCase    =	False
							out_string += self.sp_model.decode(A_      )
							return out_string


						def 				__snake_case    (					self	,       A_	,       A_ = None      )	->	Tuple[str]:
							if not os.path.isdir(A_      ):
								logger.error(f'Vocabulary path ({save_directory}) should be a directory'      )
								return
							lowerCAmelCase    =	os.path.join(
							    A_	,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]      )

							if os.path.abspath(self.vocab_file      ) != os.path.abspath(A_      ) and os.path.isfile(self.vocab_file      ):
								copyfile(self.vocab_file	,       A_      )
							elif not os.path.isfile(self.vocab_file      ):
								with open(A_	,       """wb"""      ) as fi:
									lowerCAmelCase    =	self.sp_model.serialized_model_proto()
									fi.write(A_      )

							return (out_vocab_file,)


						def 				__snake_case    (					self	,       A_	,       A_=None      )	->	Any:
							lowerCAmelCase    =	[self.bos_token_id] if self.add_bos_token else []
							lowerCAmelCase    =	[self.eos_token_id] if self.add_eos_token else []

							lowerCAmelCase    =	bos_token_id + token_ids_a + eos_token_id

							if token_ids_a is not None:
								lowerCAmelCase    =	output + bos_token_id + token_ids_a + eos_token_id

							return output


						def 				__snake_case    (					self	,       A_	,       A_ = None	,       A_ = False      )	->	List[int]:
							if already_has_special_tokens:
								return super().get_special_tokens_mask(
								    token_ids_a=A_	,       token_ids_a=A_	,       already_has_special_tokens=A_      )

							lowerCAmelCase    =	[1] if self.add_bos_token else []
							lowerCAmelCase    =	[1] if self.add_eos_token else []

							if token_ids_a is None:
								return bos_token_id + ([0] * len(A_      )) + eos_token_id
							return (
							    bos_token_id
							    + ([0] * len(A_      ))
							    + eos_token_id
							    + bos_token_id
							    + ([0] * len(A_      ))
							    + eos_token_id
							)


						def 				__snake_case    (					self	,       A_	,       A_ = None      )	->	List[int]:
							lowerCAmelCase    =	[self.bos_token_id] if self.add_bos_token else []
							lowerCAmelCase    =	[self.eos_token_id] if self.add_eos_token else []

							lowerCAmelCase    =	[0] * len(bos_token_id + token_ids_a + eos_token_id      )

							if token_ids_a is not None:
								output += [1] * len(bos_token_id + token_ids_a + eos_token_id      )

							return output




						def 				__snake_case    (					self	,       A_      )	->	List[int]:
							lowerCAmelCase    =	list(conversation.iter_texts()      )
							if not all([is_user for is_user, msg in dialogue[::2]]      ) or not all(
							    [not is_user for is_user, msg in dialogue[1::2]]      ):
								raise ValueError(
								    """The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)"""      )

							lowerCAmelCase    =	[]
							if len(conversation.past_user_inputs      ) > 0:
								if not conversation.past_user_inputs[0].startswith(A_      ) or E_SYS not in conversation.past_user_inputs[0]:
									lowerCAmelCase    =	(
									    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
									)
							elif not dialogue[0][1].startswith(A_      ) or E_SYS not in dialogue[0][1]:
								lowerCAmelCase    =	(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

							dialog_tokens += sum(
							    [
							        [self.bos_token_id]
							        + self.encode(
							            f'{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '	,       add_special_tokens=A_      )
							        + [self.eos_token_id]
							        for prompt, answer in zip(dialogue[::2]	,       dialogue[1::2]      )
							    ]	,       []	,       )
							if not (dialogue[-1][0]):
								raise ValueError(f'Last message must be from user, got {dialogue[-1]["role"]}'      )
							dialog_tokens += [self.bos_token_id] + self.encode(
							    f'{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'	,       add_special_tokens=A_      )
							return dialog_tokens