

'''simple docstring'''







import argparse
import logging
import math
import time

import torch

from transformers import TransfoXLCorpus, TransfoXLLMHeadModel


logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO
)
_lowerCamelCase    =  logging.getLogger(__name__)






def 					_SCREAMING_SNAKE_CASE		(						):
	_lowercase							=     argparse.ArgumentParser(description="""PyTorch Transformer Language Model"""	)
	parser.add_argument("""--model_name"""							,       type=snake_case_							,       default="""transfo-xl-wt103"""							,       help="""pretrained model name"""	)
	parser.add_argument(
	    """--split"""							,       type=snake_case_							,       default="""test"""							,       choices=["""all""", """valid""", """test"""]							,       help="""which split to evaluate"""	)
	parser.add_argument("""--batch_size"""							,       type=snake_case_							,       default=10							,       help="""batch size"""	)
	parser.add_argument("""--tgt_len"""							,       type=snake_case_							,       default=128							,       help="""number of tokens to predict"""	)
	parser.add_argument("""--ext_len"""							,       type=snake_case_							,       default=0							,       help="""length of the extended context"""	)
	parser.add_argument("""--mem_len"""							,       type=snake_case_							,       default=1600							,       help="""length of the retained previous heads"""	)
	parser.add_argument("""--clamp_len"""							,       type=snake_case_							,       default=1000							,       help="""max positional embedding index"""	)
	parser.add_argument("""--no_cuda"""							,       action="""store_true"""							,       help="""Do not use CUDA even though CUA is available"""	)
	parser.add_argument("""--work_dir"""							,       type=snake_case_							,       required=snake_case_							,       help="""path to the work_dir"""	)
	parser.add_argument("""--no_log"""							,       action="""store_true"""							,       help="""do not log the eval result"""	)
	parser.add_argument("""--same_length"""							,       action="""store_true"""							,       help="""set same length attention with masking"""	)
	parser.add_argument("""--server_ip"""							,       type=snake_case_							,       default=""""""							,       help="""Can be used for distant debugging."""	)
	parser.add_argument("""--server_port"""							,       type=snake_case_							,       default=""""""							,       help="""Can be used for distant debugging."""	)
	_lowercase							=     parser.parse_args()
	assert args.ext_len >= 0, "extended context length must be non-negative"

	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=snake_case_	)
		ptvsd.wait_for_attach()

	_lowercase							=     torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""	)
	logger.info("""device: {}""".format(snake_case_	)	)

	# Load a pre-processed dataset
	# You can also build the corpus yourself using TransfoXLCorpus methods
	# The pre-processing involve computing word frequencies to prepare the Adaptive input and SoftMax
	# and tokenizing the dataset
	# The pre-processed corpus is a convertion (using the conversion script )
	_lowercase							=     TransfoXLCorpus.from_pretrained(args.model_name	)

	_lowercase							=     corpus.get_iterator("""valid"""							,       args.batch_size							,       args.tgt_len							,       device=snake_case_							,       ext_len=args.ext_len	)
	_lowercase							=     corpus.get_iterator("""test"""							,       args.batch_size							,       args.tgt_len							,       device=snake_case_							,       ext_len=args.ext_len	)

	# Load a pre-trained model
	_lowercase							=     TransfoXLLMHeadModel.from_pretrained(args.model_name	)
	model.to(snake_case_	)

	logger.info(
	    """Evaluating with bsz {} tgt_len {} ext_len {} mem_len {} clamp_len {}""".format(
	        args.batch_size							,       args.tgt_len							,       args.ext_len							,       args.mem_len							,       args.clamp_len	)	)

	model.reset_memory_length(args.mem_len	)
	if args.clamp_len > 0:
		_lowercase							=     args.clamp_len
	if args.same_length:
		_lowercase							=     True

	###############################################################################
	# Evaluation code
	###############################################################################
	def evaluate(snake_case_	):
		# Turn on evaluation mode which disables dropout.
		model.eval()
		_lowercase		,		_lowercase							=     0, 0.0
		_lowercase							=     time.time()
		with torch.no_grad():
			_lowercase							=     None
			for idx, (data, target, seq_len) in enumerate(snake_case_	):
				_lowercase							=     model(snake_case_							,       lm_labels=snake_case_							,       mems=snake_case_	)
				_lowercase		,		_lowercase		,		_lowercase							=     ret
				_lowercase							=     loss.mean()
				total_loss += seq_len * loss.item()
				total_len += seq_len
			_lowercase							=     time.time() - start_time
		logger.info("""Time : {:.2f}s, {:.2f}ms/segment""".format(snake_case_							,       1000 * total_time / (idx + 1)	)	)
		return total_loss / total_len

	# Run on test data.
	if args.split == "all":
		_lowercase							=     evaluate(snake_case_	)
		_lowercase							=     evaluate(snake_case_	)
	elif args.split == "valid":
		_lowercase							=     evaluate(snake_case_	)
		_lowercase							=     None
	elif args.split == "test":
		_lowercase							=     evaluate(snake_case_	)
		_lowercase							=     None

	def format_log(snake_case_							,       snake_case_	):
		_lowercase							=     """| {0} loss {1:5.2f} | {0} ppl {2:9.3f} """.format(snake_case_							,       snake_case_							,       math.exp(snake_case_	)	)
		return log_str

	_lowercase							=     """"""
	if valid_loss is not None:
		log_str += format_log(snake_case_							,       """valid"""	)
	if test_loss is not None:
		log_str += format_log(snake_case_							,       """test"""	)

	logger.info("""=""" * 100	)
	logger.info(snake_case_	)
	logger.info("""=""" * 100	)


if __name__ == "__main__":
							main()






"""simple docstring"""




import os
from shutil import copyfile
from typing import TYPE_CHECKING, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
					from transformers.pipelines.conversational import Conversation

require_version('''tokenizers>=0.13.3''')

if is_sentencepiece_available():
					from .tokenization_llama import LlamaTokenizer
else:
					__lowerCAmelCase							:  List[str] 				=		None

__lowerCAmelCase							:  Optional[int] 				=		logging.get_logger(__name__)
__lowerCAmelCase							:  int 				=		{'''vocab_file''': '''tokenizer.model''', '''tokenizer_file''': '''tokenizer.json'''}

__lowerCAmelCase				,__lowerCAmelCase							:  Any 				=		'''[INST]''', '''[/INST]'''
__lowerCAmelCase				,__lowerCAmelCase							:  Tuple 				=		'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
__lowerCAmelCase							:  List[str] 				=		'''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''
class SCREAMING_SNAKE_CASE       (      lowerCAmelCase					):






	'''simple docstring'''







	snake_case__							:		List[str]         =		VOCAB_FILES_NAMES
	snake_case__							:		Optional[Any]         =		LlamaTokenizer
	snake_case__							:		Union[str, Any]         =		'left'
	snake_case__							:		Any         =		['input_ids', 'attention_mask']


	def __init__(  self :Optional[Any]       ,    __magic_name__ :Optional[Any]=None       ,    __magic_name__ :Tuple=None       ,    __magic_name__ :List[Any]=False       ,    __magic_name__ :List[str]="<unk>"       ,    __magic_name__ :List[str]="<s>"       ,    __magic_name__ :List[str]="</s>"       ,    __magic_name__ :Any=True       ,    __magic_name__ :Union[str, Any]=False       ,    **__magic_name__ :Optional[int]       ,    )			->   List[Any]:

			'''simple docstring'''






			super().__init__(
			    vocab_file=__magic_name__       ,    tokenizer_file=__magic_name__       ,    clean_up_tokenization_spaces=__magic_name__       ,    unk_token=__magic_name__       ,    bos_token=__magic_name__       ,    eos_token=__magic_name__       ,    **__magic_name__       ,    )
			a__   		=     add_bos_token
			a__   		=     add_eos_token
			self.update_post_processor()

			a__   		=     vocab_file
			a__   		=     False if not self.vocab_file else True


	def    _UpperCamelCase							(  self :List[str]			)			->   Optional[int]:

			'''simple docstring'''






			a__   		=     self.bos_token
			a__   		=     self.bos_token_id

			a__   		=     self.eos_token
			a__   		=     self.eos_token_id

			a__   		=     F"{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}"
			a__   		=     F"{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}"

			a__   		=     []
			if self.add_bos_token:
					special_tokens.append((bos, bos_token_id)			)
			if self.add_eos_token:
					special_tokens.append((eos, eos_token_id)			)
			a__   		=     processors.TemplateProcessing(
			    single=__magic_name__       ,    pair=__magic_name__       ,    special_tokens=__magic_name__			)


	@property
	def    _UpperCamelCase							(  self :Optional[int]			)			->   Any:

			'''simple docstring'''






			return self._add_eos_token


	@property
	def    _UpperCamelCase							(  self :Optional[int]			)			->   Optional[Any]:

			'''simple docstring'''






			return self._add_bos_token


	@add_eos_token.setter
	def    _UpperCamelCase							(  self :int       ,    __magic_name__ :int			)			->   int:

			'''simple docstring'''






			a__   		=     value
			self.update_post_processor()


	@add_bos_token.setter
	def    _UpperCamelCase							(  self :Any       ,    __magic_name__ :str			)			->   Optional[int]:

			'''simple docstring'''






			a__   		=     value
			self.update_post_processor()


	def    _UpperCamelCase							(  self :Dict       ,    __magic_name__ :str       ,    __magic_name__ :Optional[str] = None			)			->   Tuple[str]:

			'''simple docstring'''






			if not self.can_save_slow_tokenizer:
					raise ValueError(
					    '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
					    '''tokenizer.'''			)

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

			if os.path.abspath(self.vocab_file			) != os.path.abspath(__magic_name__			):
					copyfile(self.vocab_file       ,    __magic_name__			)

			return (out_vocab_file,)






	def    _UpperCamelCase							(  self :int       ,    __magic_name__ :"Conversation"			)			->   List[Any]:

			'''simple docstring'''






			a__   		=     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...)'''			)

			a__   		=     []
			if len(conversation.past_user_inputs			) > 0:
					if not conversation.past_user_inputs[0].startswith(__magic_name__			) or E_SYS not in conversation.past_user_inputs[0]:
							a__   		=     (
							    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
							)
			elif not dialogue[0][1].startswith(__magic_name__			) or E_SYS not in dialogue[0][1]:
					a__   		=     (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=__magic_name__			)
			        + [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=__magic_name__			)
			return dialog_tokens




