



'''simple docstring'''

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


UpperCAmelCase			=    '\nDistills an NLI-based zero-shot classifier to a smaller, more efficient model with a fixed set of candidate class\nnames. Useful for speeding up zero-shot classification in cases where labeled training data is not available, but\nwhen only a single fixed set of classes is needed. Takes a teacher NLI model, student classifier model, unlabeled\ndataset, and set of K possible class names. Yields a single classifier with K outputs corresponding to the provided\nclass names.\n'

UpperCAmelCase			=    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=_lowerCAmelCase		,							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=_lowerCAmelCase		,							metadata={"help": "Whether to use one of the fast tokenizer (backed by the Rust tokenizers library) or not."}		,							)







@dataclass
class __snake_case(      _lowerCAmelCase					):


						'''simple docstring'''



						UpperCAmelCase							:    Optional[str]           =		field(
						    default=_lowerCAmelCase		,							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=_lowerCAmelCase		,							metadata={"help": "Whether to run training of student model."}					)
						UpperCAmelCase							:    bool           =		field(
						    default=_lowerCAmelCase		,							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(      _lowerCAmelCase					):


						'''simple docstring'''



						def 				__snake_case    (					self	,       A_	,       A_	,       A_=False      )	->	Union[str, Any]:
							lowerCAmelCase    =	inputs["""labels"""]
							lowerCAmelCase    =	model(inputs["""input_ids"""]	,       attention_mask=inputs["""attention_mask"""]      )
							lowerCAmelCase    =	outputs[0]

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

							if return_outputs:
								return loss, outputs

							return loss







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







	"""simple docstring"""
	lowerCAmelCase    =	[]
	with open(_SCREAMING_SNAKE_CASE							,		"""r"""							) as f:
		for line in f:
			lowerCAmelCase    =	line.strip()
			if len(_SCREAMING_SNAKE_CASE							) > 0:
				lines.append(_SCREAMING_SNAKE_CASE							)
	return lines






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







	"""simple docstring"""
	lowerCAmelCase    =	[]
	lowerCAmelCase    =	[]
	for example in examples:
		for name in class_names:
			premises.append(_SCREAMING_SNAKE_CASE							)
			hypotheses.append(hypothesis_template.format(_SCREAMING_SNAKE_CASE							)							)
	return premises, hypotheses






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







	"""simple docstring"""
	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 		_snake_case		(					_SCREAMING_SNAKE_CASE     :						str							,		_SCREAMING_SNAKE_CASE     :						List[str]							,		_SCREAMING_SNAKE_CASE     :						List[str]							,		_SCREAMING_SNAKE_CASE     :						str							,		_SCREAMING_SNAKE_CASE     :						int							,		_SCREAMING_SNAKE_CASE     :						float							,		_SCREAMING_SNAKE_CASE     :						bool							,		_SCREAMING_SNAKE_CASE     :						bool							,		_SCREAMING_SNAKE_CASE     :						bool							,		_SCREAMING_SNAKE_CASE     :						bool							,		)			->						Dict:







	"""simple docstring"""
	lowerCAmelCase    =	AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	model.config
	if not no_cuda and torch.cuda.is_available():
		lowerCAmelCase    =	nn.DataParallel(model.cuda()							)
		batch_size *= len(model.device_ids							)
	lowerCAmelCase    =	AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE							,		use_fast=_SCREAMING_SNAKE_CASE							)

	lowerCAmelCase,   lowerCAmelCase    =	get_premise_hypothesis_pairs(_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							)
	lowerCAmelCase    =	[]

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

		lowerCAmelCase    =	tokenizer(
		    _SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		padding=_SCREAMING_SNAKE_CASE							,		truncation="""only_first"""							,		return_tensors="""pt"""							,		)

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

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

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

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






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







	"""simple docstring"""
	lowerCAmelCase    =	HfArgumentParser(
	    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)							,		description=_SCREAMING_SNAKE_CASE							,		)

	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.
		lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	parser.parse_json_file(
		    json_file=os.path.abspath(sys.argv[1]							)							)
	else:
		lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase,   lowerCAmelCase    =	parser.parse_args_into_dataclasses()

	# Detecting last checkpoint.
	lowerCAmelCase    =	None
	if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
		lowerCAmelCase    =	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
	lowerCAmelCase    =	read_lines(data_args.data_file							)
	lowerCAmelCase    =	read_lines(data_args.class_names_file							)

	# 2. get teacher predictions and load into dataset
	logger.info("""Generating predictions from zero-shot teacher model"""							)
	lowerCAmelCase    =	get_teacher_predictions(
	    teacher_args.teacher_name_or_path							,		_SCREAMING_SNAKE_CASE							,		_SCREAMING_SNAKE_CASE							,		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							,		)
	lowerCAmelCase    =	Dataset.from_dict(
	    {
	        """text""": examples,
	        """labels""": teacher_soft_preds,
	    }							)

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

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

	def compute_metrics(_SCREAMING_SNAKE_CASE     :						List[str]							,		_SCREAMING_SNAKE_CASE     :						Optional[Any]=False							):
		lowerCAmelCase    =	p.predictions.argmax(-1							)
		lowerCAmelCase    =	p.label_ids.argmax(-1							)  # "label_ids" are actually distributions
		return {"agreement": (preds == proxy_labels).mean().item()}

	lowerCAmelCase    =	DistillationTrainer(
	    model=_SCREAMING_SNAKE_CASE							,		tokenizer=_SCREAMING_SNAKE_CASE							,		args=_SCREAMING_SNAKE_CASE							,		train_dataset=_SCREAMING_SNAKE_CASE							,		compute_metrics=_SCREAMING_SNAKE_CASE							,		)

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

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

	trainer.save_model()


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