


'''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


_lowerCAmelCase	:		Any		  =						'\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'

_lowerCAmelCase	:		List[str]		  =						logging.getLogger(__name__)



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



@dataclass
class 			lowerCAmelCase					:
	_lowerCamelCase :       Optional[str]         =			field(
	    default="""distilbert-base-uncased"""   ,					metadata={"""help""": """The NLI/zero-shot teacher model to be distilled."""}				)



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



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



	def 					lowercase  (       self			,       snake_case__			,       snake_case__			,       snake_case__=False     ):
		lowerCAmelCase       :     Optional[Any]   				=			inputs['labels']
		lowerCAmelCase       :     Optional[int]   				=			model(inputs['input_ids']			,       attention_mask=inputs['attention_mask']     )
		lowerCAmelCase       :     List[Any]   				=			outputs[0]

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

		if return_outputs:
			return loss, outputs

		return loss


def       __UpperCamelCase     (     _A     :					List[Any]					)     ->   Optional[int]:




	"""simple docstring"""





	lowerCAmelCase       :     Optional[Any]   				=			[]
	with open(_A       , 'r'					) as f:
		for line in f:
			lowerCAmelCase       :     Optional[int]   				=			line.strip()
			if len(_A					) > 0:
				lines.append(_A					)
	return lines

def       __UpperCamelCase     (     _A     :					Tuple       , _A     :					Tuple       , _A     :					List[str]					)     ->   Tuple:




	"""simple docstring"""





	lowerCAmelCase       :     int   				=			[]
	lowerCAmelCase       :     Tuple   				=			[]
	for example in examples:
		for name in class_names:
			premises.append(_A					)
			hypotheses.append(hypothesis_template.format(_A					)					)
	return premises, hypotheses

def       __UpperCamelCase     (     _A     :					Optional[Any]					)     ->   List[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       __UpperCamelCase     (     _A     :					str       , _A     :					List[str]       , _A     :					List[str]       , _A     :					str       , _A     :					int       , _A     :					float       , _A     :					bool       , _A     :					bool       , _A     :					bool       , _A     :					bool       , )     ->   Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase       :     Any   				=			AutoModelForSequenceClassification.from_pretrained(_A					)
	lowerCAmelCase       :     int   				=			model.config
	if not no_cuda and torch.cuda.is_available():
		lowerCAmelCase       :     Dict   				=			nn.DataParallel(model.cuda()					)
		batch_size *= len(model.device_ids					)
	lowerCAmelCase       :     Tuple   				=			AutoTokenizer.from_pretrained(_A       , use_fast=_A					)

	lowerCAmelCase				, lowerCAmelCase       :     str   				=			get_premise_hypothesis_pairs(_A       , _A       , _A					)
	lowerCAmelCase       :     Optional[Any]   				=			[]

	for i in tqdm(range(0       , len(_A					)       , _A					)					):
		lowerCAmelCase       :     Optional[Any]   				=			premises[i : i + batch_size]
		lowerCAmelCase       :     List[Any]   				=			hypotheses[i : i + batch_size]

		lowerCAmelCase       :     Optional[Any]   				=			tokenizer(
		    _A       , _A       , padding=_A       , truncation='only_first'       , return_tensors='pt'       , )

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

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

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

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

def       __UpperCamelCase     (     )     ->   Dict:




	"""simple docstring"""





	lowerCAmelCase       :     Optional[int]   				=			HfArgumentParser(
	    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)       , description=_A       , )

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

	# Detecting last checkpoint.
	lowerCAmelCase       :     Tuple   				=			None
	if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
		lowerCAmelCase       :     Optional[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
	lowerCAmelCase       :     Optional[Any]   				=			read_lines(data_args.data_file					)
	lowerCAmelCase       :     str   				=			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       :     Optional[Any]   				=			get_teacher_predictions(
	    teacher_args.teacher_name_or_path       , _A       , _A       , 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       :     Any   				=			Dataset.from_dict(
	    {
	        'text': examples,
	        'labels': teacher_soft_preds,
	    }					)

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

	# 4. train student on teacher predictions
	lowerCAmelCase       :     Optional[int]   				=			dataset.map(_A       , input_columns='text'					)
	dataset.set_format('torch'					)

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

	lowerCAmelCase       :     List[str]   				=			DistillationTrainer(
	    model=_A       , tokenizer=_A       , args=_A       , train_dataset=_A       , compute_metrics=_A       , )

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

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

	trainer.save_model()


if __name__ == "__main__":
				main()




'''simple docstring'''




from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowerCAmelCase	:		List[str]		  =						logging.get_logger(__name__)

_lowerCAmelCase	:		int		  =						{
    'facebook/opt-125m': 'https://huggingface.co/facebook/opt-125m/blob/main/config.json',
    'facebook/opt-350m': 'https://huggingface.co/facebook/opt-350m/blob/main/config.json',
    'facebook/opt-1.3b': 'https://huggingface.co/facebook/opt-1.3b/blob/main/config.json',
    'facebook/opt-2.7b': 'https://huggingface.co/facebook/opt-2.7b/blob/main/config.json',
    'facebook/opt-6.7b': 'https://huggingface.co/facebook/opt-6.7b/blob/main/config.json',
    'facebook/opt-13b': 'https://huggingface.co/facebook/opt-13b/blob/main/config.json',
}



class 			lowerCAmelCase					(					a				):
	_lowerCamelCase :       Dict         =			"""opt"""
	_lowerCamelCase :       Optional[Any]         =			["""past_key_values"""]



	def __init__(       self			,       snake_case__=5_0272			,       snake_case__=768			,       snake_case__=12			,       snake_case__=3072			,       snake_case__=2048			,       snake_case__=True			,       snake_case__=False			,       snake_case__=None			,       snake_case__=0.1			,       snake_case__=0.0			,       snake_case__=12			,       snake_case__="relu"			,       snake_case__=0.0			,       snake_case__=0.0_2			,       snake_case__=True			,       snake_case__=1			,       snake_case__=2			,       snake_case__=2			,       snake_case__=True			,       snake_case__=True			,       **snake_case__			,       ):
		super().__init__(
		    pad_token_id=snake_case__			,       bos_token_id=snake_case__			,       eos_token_id=snake_case__			,       **snake_case__			,       )
		lowerCAmelCase       :     Union[str, Any]   				=			vocab_size
		lowerCAmelCase       :     List[Any]   				=			max_position_embeddings
		lowerCAmelCase       :     List[str]   				=			num_attention_heads
		lowerCAmelCase       :     Dict   				=			word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size
		lowerCAmelCase       :     Optional[Any]   				=			ffn_dim
		lowerCAmelCase       :     Optional[int]   				=			hidden_size
		lowerCAmelCase       :     List[str]   				=			num_hidden_layers
		lowerCAmelCase       :     Union[str, Any]   				=			dropout
		lowerCAmelCase       :     List[str]   				=			attention_dropout
		lowerCAmelCase       :     Union[str, Any]   				=			activation_function
		lowerCAmelCase       :     Optional[Any]   				=			init_std
		lowerCAmelCase       :     List[str]   				=			layerdrop
		lowerCAmelCase       :     Dict   				=			use_cache
		lowerCAmelCase       :     List[Any]   				=			do_layer_norm_before
		# We keep these variables at `True` for backward compatibility.
		lowerCAmelCase       :     List[str]   				=			enable_bias
		lowerCAmelCase       :     Dict   				=			layer_norm_elementwise_affine

		# Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility
		# with checkpoints that have been fine-tuned before transformers v4.20.1
		# see https://github.com/facebookresearch/metaseq/pull/164
		lowerCAmelCase       :     Tuple   				=			_remove_final_layer_norm
