




import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

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


a__		    =    logging.get_logger(__name__)


a__		    =    {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}

# See all MVP models at https://huggingface.co/models?filter=mvp
a__		    =    {
    '''vocab_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json''',
    },
    '''added_tokens.json''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json''',
    },
    '''merges_file''': {
        '''RUCAIBox/mvp''': '''https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt''',
    },
}

a__		    =    {
    '''RUCAIBox/mvp''': 1024,
}





@lru_cache()
def 							A__   ()    ->	Any:
					__UpperCamelCase				:  Optional[int]								=			(
					    list(range(ord("""!"""							)		,  ord("""~"""							) + 1							)							) + list(range(ord("""¡"""							)		,  ord("""¬"""							) + 1							)							) + list(range(ord("""®"""							)		,  ord("""ÿ"""							) + 1							)							)
					)
					__UpperCamelCase				:  str								=			bs[:]
					__UpperCamelCase				:  Dict								=			0
					for b in range(2**8							):
										if b not in bs:
															bs.append(a_							)
															cs.append(2**8 + n							)
															n += 1
					__UpperCamelCase				:  Tuple								=			[chr(a_							) for n in cs]
					return dict(zip(a_		,  a_							)							)





def 							A__   (snake_case      :		Tuple							)    ->	List[str]:
					__UpperCamelCase				:  int								=			set()
					__UpperCamelCase				:  Any								=			word[0]
					for char in word[1:]:
										pairs.add((prev_char, char)							)
										__UpperCamelCase				:  Dict								=			char
					return pairs







class       UpperCAmelCase__							(					lowerCAmelCase_      ):



	"""simple docstring"""


	__magic_name__      :					Any			  =		VOCAB_FILES_NAMES
	__magic_name__      :					Dict			  =		PRETRAINED_VOCAB_FILES_MAP
	__magic_name__      :					Any			  =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	__magic_name__      :					Any			  =		['input_ids', 'attention_mask']






	def __init__(				self		:	Union[str, Any]				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	Optional[Any]="replace"				,    lowerCAmelCase		:	Optional[int]="<s>"				,    lowerCAmelCase		:	List[Any]="</s>"				,    lowerCAmelCase		:	List[str]="</s>"				,    lowerCAmelCase		:	Optional[Any]="<s>"				,    lowerCAmelCase		:	List[Any]="<unk>"				,    lowerCAmelCase		:	str="<pad>"				,    lowerCAmelCase		:	Union[str, Any]="<mask>"				,    lowerCAmelCase		:	List[str]=False				,    **lowerCAmelCase		:	Any				,    )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  str								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else bos_token
						__UpperCamelCase				:  Any								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else eos_token
						__UpperCamelCase				:  int								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else sep_token
						__UpperCamelCase				:  str								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else cls_token
						__UpperCamelCase				:  int								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else unk_token
						__UpperCamelCase				:  Optional[int]								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else pad_token

						# Mask token behave like a normal word, i.e. include the space before it
						__UpperCamelCase				:  int								=			AddedToken(lowerCamelCase_				,    lstrip=lowerCamelCase_				,    rstrip=lowerCamelCase_  ) if isinstance(lowerCamelCase_				,    lowerCamelCase_  ) else mask_token

						super().__init__(
						    errors=lowerCamelCase_				,    bos_token=lowerCamelCase_				,    eos_token=lowerCamelCase_				,    unk_token=lowerCamelCase_				,    sep_token=lowerCamelCase_				,    cls_token=lowerCamelCase_				,    pad_token=lowerCamelCase_				,    mask_token=lowerCamelCase_				,    add_prefix_space=lowerCamelCase_				,    **lowerCamelCase_				,    )
						with open(lowerCamelCase_				,    encoding="""utf-8"""  ) as vocab_handle:
											__UpperCamelCase				:  str								=			json.load(lowerCamelCase_  )
						__UpperCamelCase				:  Tuple								=			{v: k for k, v in self.encoder.items()}
						__UpperCamelCase				:  List[Any]								=			errors  # how to handle errors in decoding
						__UpperCamelCase				:  Optional[int]								=			bytes_to_unicode()
						__UpperCamelCase				:  Tuple								=			{v: k for k, v in self.byte_encoder.items()}
						with open(lowerCamelCase_				,    encoding="""utf-8"""  ) as merges_handle:
											__UpperCamelCase				:  List[Any]								=			merges_handle.read().split("""\n"""  )[1:-1]
						__UpperCamelCase				:  List[Any]								=			[tuple(merge.split()  ) for merge in bpe_merges]
						__UpperCamelCase				:  Any								=			dict(zip(lowerCamelCase_				,    range(len(lowerCamelCase_  )  )  )  )
						__UpperCamelCase				:  Optional[Any]								=			{}
						__UpperCamelCase				:  str								=			add_prefix_space

						# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
						__UpperCamelCase				:  Tuple								=			re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""  )






	@property
	def 				lowerCamelCase__    (				self		:	List[str]  )  ->					Union[str, Any]:







						"""simple docstring"""







						return len(self.encoder  )






	def 				lowerCamelCase__    (				self		:	Optional[int]  )  ->					Optional[int]:







						"""simple docstring"""







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






	def 				lowerCamelCase__    (				self		:	List[Any]				,    lowerCAmelCase		:	List[str]  )  ->					Dict:







						"""simple docstring"""







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

						if not pairs:
											return token

						while True:
											__UpperCamelCase				:  Tuple								=			min(lowerCamelCase_				,    key=lambda lowerCAmelCase  : self.bpe_ranks.get(lowerCamelCase_				,    float("""inf"""  )  )  )
											if bigram not in self.bpe_ranks:
																break
											__UpperCamelCase			, __UpperCamelCase				:  List[Any]								=			bigram
											__UpperCamelCase				:  int								=			[]
											__UpperCamelCase				:  Any								=			0
											while i < len(lowerCamelCase_  ):
																try:
																					__UpperCamelCase				:  Tuple								=			word.index(lowerCamelCase_				,    lowerCamelCase_  )
																except ValueError:
																					new_word.extend(word[i:]  )
																					break
																else:
																					new_word.extend(word[i:j]  )
																					__UpperCamelCase				:  List[Any]								=			j

																if word[i] == first and i < len(lowerCamelCase_  ) - 1 and word[i + 1] == second:
																					new_word.append(first + second  )
																					i += 2
																else:
																					new_word.append(word[i]  )
																					i += 1
											__UpperCamelCase				:  Optional[Any]								=			tuple(lowerCamelCase_  )
											__UpperCamelCase				:  Optional[Any]								=			new_word
											if len(lowerCamelCase_  ) == 1:
																break
											else:
																__UpperCamelCase				:  str								=			get_pairs(lowerCamelCase_  )
						__UpperCamelCase				:  Optional[int]								=			""" """.join(lowerCamelCase_  )
						__UpperCamelCase				:  Dict								=			word
						return word






	def 				lowerCamelCase__    (				self		:	Optional[int]				,    lowerCAmelCase		:	Any  )  ->					Tuple:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			[]
						for token in re.findall(self.pat				,    lowerCamelCase_  ):
											__UpperCamelCase				:  Union[str, Any]								=			"""""".join(
											    self.byte_encoder[b] for b in token.encode("""utf-8"""  )  )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
											bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCamelCase_  ).split(""" """  )  )
						return bpe_tokens






	def 				lowerCamelCase__    (				self		:	List[str]				,    lowerCAmelCase		:	Any  )  ->					int:







						"""simple docstring"""







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






	def 				lowerCamelCase__    (				self		:	str				,    lowerCAmelCase		:	Optional[int]  )  ->					str:







						"""simple docstring"""







						return self.decoder.get(lowerCamelCase_  )






	def 				lowerCamelCase__    (				self		:	int				,    lowerCAmelCase		:	Tuple  )  ->					List[str]:







						"""simple docstring"""







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






	def 				lowerCamelCase__    (				self		:	Union[str, Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	List[str] = None  )  ->					List[str]:







						"""simple docstring"""







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

						with open(lowerCamelCase_				,    """w"""				,    encoding="""utf-8"""  ) as f:
											f.write(json.dumps(self.encoder				,    indent=2				,    sort_keys=lowerCamelCase_				,    ensure_ascii=lowerCamelCase_  ) + """\n"""  )

						__UpperCamelCase				:  List[Any]								=			0
						with open(lowerCamelCase_				,    """w"""				,    encoding="""utf-8"""  ) as writer:
											writer.write("""#version: 0.2\n"""  )
											for bpe_tokens, token_index in sorted(self.bpe_ranks.items()				,    key=lambda lowerCAmelCase  : kv[1]  ):
																if index != token_index:
																					logger.warning(
																					    F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
																					    """ Please check that the tokenizer is not corrupted!"""  )
																					__UpperCamelCase				:  Dict								=			token_index
																writer.write(""" """.join(lowerCamelCase_  ) + """\n"""  )
																index += 1

						return vocab_file, merge_file






	def 				lowerCamelCase__    (				self		:	Optional[int]				,    lowerCAmelCase		:	Optional[int]				,    lowerCAmelCase		:	Any = None  )  ->					int:







						"""simple docstring"""







						if token_ids_a is None:
											return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
						__UpperCamelCase				:  List[Any]								=			[self.cls_token_id]
						__UpperCamelCase				:  Any								=			[self.sep_token_id]
						return cls + token_ids_a + sep + sep + token_ids_a + sep






	def 				lowerCamelCase__    (				self		:	Tuple				,    lowerCAmelCase		:	Dict				,    lowerCAmelCase		:	int = None				,    lowerCAmelCase		:	List[Any] = False  )  ->					List[str]:







						"""simple docstring"""







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

						if token_ids_a is None:
											return [1] + ([0] * len(lowerCamelCase_  )) + [1]
						return [1] + ([0] * len(lowerCamelCase_  )) + [1, 1] + ([0] * len(lowerCamelCase_  )) + [1]






	def 				lowerCamelCase__    (				self		:	Union[str, Any]				,    lowerCAmelCase		:	List[str]				,    lowerCAmelCase		:	List[Any] = None  )  ->					Dict:







						"""simple docstring"""







						__UpperCamelCase				:  List[str]								=			[self.sep_token_id]
						__UpperCamelCase				:  Union[str, Any]								=			[self.cls_token_id]

						if token_ids_a is None:
											return len(cls + token_ids_a + sep  ) * [0]
						return len(cls + token_ids_a + sep + sep + token_ids_a + sep  ) * [0]






	def 				lowerCamelCase__    (				self		:	Union[str, Any]				,    lowerCAmelCase		:	str				,    lowerCAmelCase		:	Any=False				,    **lowerCAmelCase		:	List[str]  )  ->					Optional[Any]:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			kwargs.pop("""add_prefix_space"""				,    self.add_prefix_space  )
						if (is_split_into_words or add_prefix_space) and (len(lowerCamelCase_  ) > 0 and not text[0].isspace()):
											__UpperCamelCase				:  List[Any]								=			""" """ + text
						return (text, kwargs)












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


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

a__		    =    logging.getLogger(__name__)


@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


	__magic_name__      :					Optional[str]			  =		field(
	    default='roberta-large-mnli'  ,     metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}      )
	__magic_name__      :					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.'
	        )
	    }  ,     )
	__magic_name__      :					Optional[int]			  =		field(
	    default=32  ,     metadata={'help': 'Batch size for generating teacher predictions.'}      )
	__magic_name__      :					Optional[bool]			  =		field(
	    default=_UpperCamelCase  ,     metadata={
	        'help': (
	            'Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called'
	            'multi-class multi-label classification).'
	        )
	    }  ,     )
	__magic_name__      :					Optional[float]			  =		field(
	    default=1.0  ,     metadata={'help': 'Temperature applied to teacher softmax for distillation.'}      )






@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


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






@dataclass
class       SCREAMING_SNAKE_CASE_							:



	"""simple docstring"""


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






@dataclass
class       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase      ):



	"""simple docstring"""


	__magic_name__      :					Optional[str]			  =		field(
	    default=_UpperCamelCase  ,     metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'}  ,     )
	__magic_name__      :					int			  =		field(
	    default=32  ,     metadata={'help': 'Batch size per GPU/TPU core/CPU for training.'}      )
	__magic_name__      :					int			  =		field(
	    default=128  ,     metadata={'help': 'Batch size per GPU/TPU core/CPU for evaluation.'}      )
	__magic_name__      :					float			  =		field(default=1.0  ,     metadata={'help': 'Total number of training epochs to perform.'}      )
	__magic_name__      :					bool			  =		field(default=_UpperCamelCase  ,     metadata={'help': 'Whether to run training of student model.'}      )
	__magic_name__      :					bool			  =		field(
	    default=_UpperCamelCase  ,     metadata={
	        'help': (
	            'Whether to evaluate the agreement of the final student predictions and the teacher predictions'
	            'after training.'
	        )
	    }  ,     )
	__magic_name__      :					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       SCREAMING_SNAKE_CASE_							(					_UpperCamelCase      ):



	"""simple docstring"""


	def 				lowerCamelCase__    (				self		:	Any				,    lowerCAmelCase		:	int				,    lowerCAmelCase		:	Union[str, Any]				,    lowerCAmelCase		:	Tuple=False  )  ->					Any:







						"""simple docstring"""







						__UpperCamelCase				:  List[Any]								=			inputs["""labels"""]
						__UpperCamelCase				:  List[Any]								=			model(inputs["""input_ids"""]				,    attention_mask=inputs["""attention_mask"""]  )
						__UpperCamelCase				:  Optional[Any]								=			outputs[0]

						__UpperCamelCase				:  List[str]								=			-torch.sum(target_p * logits.log_softmax(dim=-1  )				,    axis=-1  ).mean()

						if return_outputs:
											return loss, outputs

						return loss






def 							A__   (snake_case      :		Optional[int]							)    ->	List[Any]:
					__UpperCamelCase				:  Union[str, Any]								=			[]
					with open(snake_case		,  """r"""							) as f:
										for line in f:
															__UpperCamelCase				:  Tuple								=			line.strip()
															if len(snake_case							) > 0:
																				lines.append(snake_case							)
					return lines





def 							A__   (snake_case      :		Optional[int]		,  snake_case      :		Optional[Any]		,  snake_case      :		str							)    ->	str:
					__UpperCamelCase				:  Union[str, Any]								=			[]
					__UpperCamelCase				:  List[str]								=			[]
					for example in examples:
										for name in class_names:
															premises.append(snake_case							)
															hypotheses.append(hypothesis_template.format(snake_case							)							)
					return premises, hypotheses





def 							A__   (snake_case      :		Optional[Any]							)    ->	int:
					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 							A__   (snake_case      :		str		,  snake_case      :		List[str]		,  snake_case      :		List[str]		,  snake_case      :		str		,  snake_case      :		int		,  snake_case      :		float		,  snake_case      :		bool		,  snake_case      :		bool		,  snake_case      :		bool		,  snake_case      :		bool		,  )    ->	List[Any]:
					__UpperCamelCase				:  Any								=			AutoModelForSequenceClassification.from_pretrained(snake_case							)
					__UpperCamelCase				:  str								=			model.config
					if not no_cuda and torch.cuda.is_available():
										__UpperCamelCase				:  List[Any]								=			nn.DataParallel(model.cuda()							)
										batch_size *= len(model.device_ids							)
					__UpperCamelCase				:  Optional[int]								=			AutoTokenizer.from_pretrained(snake_case		,  use_fast=snake_case							)

					__UpperCamelCase			, __UpperCamelCase				:  int								=			get_premise_hypothesis_pairs(snake_case		,  snake_case		,  snake_case							)
					__UpperCamelCase				:  Any								=			[]

					for i in tqdm(range(0		,  len(snake_case							)		,  snake_case							)							):
										__UpperCamelCase				:  List[str]								=			premises[i : i + batch_size]
										__UpperCamelCase				:  Dict								=			hypotheses[i : i + batch_size]

										__UpperCamelCase				:  Any								=			tokenizer(
										    snake_case		,  snake_case		,  padding=snake_case		,  truncation="""only_first"""		,  return_tensors="""pt"""		,  )

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

					__UpperCamelCase				:  Tuple								=			get_entailment_id(snake_case							)
					__UpperCamelCase				:  List[Any]								=			-1 if entail_id == 0 else 0
					__UpperCamelCase				:  List[Any]								=			torch.cat(snake_case		,  dim=0							)  # N*K x 3
					__UpperCamelCase				:  str								=			logits.reshape(len(snake_case							)		,  len(snake_case							)		,  -1							)[..., [contr_id, entail_id]]  # N x K x 2

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

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





def 							A__   ()    ->	Optional[Any]:
					__UpperCamelCase				:  Dict								=			HfArgumentParser(
					    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)		,  description=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.
										__UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase				:  Tuple								=			parser.parse_json_file(
										    json_file=os.path.abspath(sys.argv[1]							)							)
					else:
										__UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase			, __UpperCamelCase				:  List[Any]								=			parser.parse_args_into_dataclasses()

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

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

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

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

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

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

					# 1. read in data
					__UpperCamelCase				:  Union[str, Any]								=			read_lines(data_args.data_file							)
					__UpperCamelCase				:  int								=			read_lines(data_args.class_names_file							)

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

					# 3. create student
					logger.info("""Initializing student model"""							)
					__UpperCamelCase				:  List[str]								=			AutoModelForSequenceClassification.from_pretrained(
					    student_args.student_name_or_path		,  num_labels=len(snake_case							)							)
					__UpperCamelCase				:  Tuple								=			AutoTokenizer.from_pretrained(student_args.student_name_or_path		,  use_fast=data_args.use_fast_tokenizer							)
					__UpperCamelCase				:  int								=			dict(enumerate(snake_case							)							)
					__UpperCamelCase				:  List[str]								=			{label: i for i, label in enumerate(snake_case							)}

					# 4. train student on teacher predictions
					__UpperCamelCase				:  Tuple								=			dataset.map(snake_case		,  input_columns="""text"""							)
					dataset.set_format("""torch"""							)

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

					__UpperCamelCase				:  List[str]								=			DistillationTrainer(
					    model=snake_case		,  tokenizer=snake_case		,  args=snake_case		,  train_dataset=snake_case		,  compute_metrics=snake_case		,  )

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

					if training_args.do_eval:
										__UpperCamelCase				:  List[str]								=			trainer.evaluate(eval_dataset=snake_case							)["""eval_agreement"""]
										logger.info(F'''Agreement of student and teacher predictions: {agreement * 1_00:0.2f}%'''							)

					trainer.save_model()


if __name__ == "__main__":
	main()






