





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			:List[str]	 =     '\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			:Optional[Any]	 =     logging.getLogger(__name__)






@dataclass
class 							_a:
		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 							_a:
		lowerCamelCase__  :Optional[str] 					=		field(
		    default='distilbert-base-uncased'						, metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}     )






@dataclass
class 							_a:
		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 							_a(     __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 							_a(     __A     ):







		def 							lowercase							(     self			,    __snake_case			,    __snake_case			,    __snake_case=False					)   ->   str:


							'''simple docstring'''

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

							_snake_case							:       Optional[int]												= -torch.sum(target_p * logits.log_softmax(dim=-1					)			,    axis=-1					).mean()

							if return_outputs:
												return loss, outputs

							return loss







def  A					(				UpperCAmelCase					):
					_snake_case							:       Union[str, Any]												= []
					with open(UpperCAmelCase	,	"r"					) as f:
										for line in f:
															_snake_case							:       str												= line.strip()
															if len(UpperCAmelCase					) > 0:
																				lines.append(UpperCAmelCase					)
					return lines







def  A					(				UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase					):
					_snake_case							:       Any												= []
					_snake_case							:       Tuple												= []
					for example in examples:
										for name in class_names:
															premises.append(UpperCAmelCase					)
															hypotheses.append(hypothesis_template.format(UpperCAmelCase					)					)
					return premises, hypotheses







def  A					(				UpperCAmelCase					):
					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					(				UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase	,	):
					_snake_case							:       str												= AutoModelForSequenceClassification.from_pretrained(UpperCAmelCase					)
					_snake_case							:       Optional[Any]												= model.config
					if not no_cuda and torch.cuda.is_available():
										_snake_case							:       str												= nn.DataParallel(model.cuda()					)
										batch_size *= len(model.device_ids					)
					_snake_case							:       Any												= AutoTokenizer.from_pretrained(UpperCAmelCase	,	use_fast=UpperCAmelCase					)

					_snake_case							,			_snake_case							:       int												= get_premise_hypothesis_pairs(UpperCAmelCase	,	UpperCAmelCase	,	UpperCAmelCase					)
					_snake_case							:       int												= []

					for i in tqdm(range(0	,	len(UpperCAmelCase					)	,	UpperCAmelCase					)					):
										_snake_case							:       int												= premises[i : i + batch_size]
										_snake_case							:       Optional[int]												= hypotheses[i : i + batch_size]

										_snake_case							:       int												= tokenizer(
										    UpperCAmelCase	,	UpperCAmelCase	,	padding=UpperCAmelCase	,	truncation="only_first"	,	return_tensors="pt"	,	)

										with torch.cuda.amp.autocast(enabled=UpperCAmelCase					):
															with torch.no_grad():
																				_snake_case							:       List[str]												= model(**UpperCAmelCase					)
										logits.append(outputs.logits.detach().cpu().float()					)

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

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

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







def  A					(				):
					_snake_case							:       Dict												= HfArgumentParser(
					    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)	,	description=UpperCAmelCase	,	)

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

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

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

					# 4. train student on teacher predictions
					_snake_case							:       List[str]												= dataset.map(UpperCAmelCase	,	input_columns="text"					)
					dataset.set_format("torch"					)

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

					_snake_case							:       Tuple												= DistillationTrainer(
					    model=UpperCAmelCase	,	tokenizer=UpperCAmelCase	,	args=UpperCAmelCase	,	train_dataset=UpperCAmelCase	,	compute_metrics=UpperCAmelCase	,	)

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

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

					trainer.save_model()


if __name__ == "__main__":
							main()






import json
import os
import subprocess
import sys
import warnings
from argparse import ArgumentParser
from contextlib import AbstractContextManager
from typing import Dict, List, Optional

import requests

from ..utils import logging
from . import BaseTransformersCLICommand


__lowerCAmelCase			:Tuple	 =     logging.get_logger(__name__)  # pylint: disable=invalid-name


__lowerCAmelCase			:Union[str, Any]	 =     'lfs-multipart-upload'






class 							_a(     __A     ):







		@staticmethod
		def 							lowercase							(     __snake_case					)   ->   Tuple:


							'''simple docstring'''

							_snake_case							:       Tuple												= parser.add_parser(
							    "lfs-enable-largefiles"			,    help=(
							        "Deprecated: use `huggingface-cli` instead. Configure your repository to enable upload of files > 5GB."
							    )			,    )
							enable_parser.add_argument("path"			,    type=__snake_case			,    help="Local path to repository you want to configure."					)
							enable_parser.set_defaults(func=lambda __snake_case					: LfsEnableCommand(__snake_case					)					)

							_snake_case							:       Union[str, Any]												= parser.add_parser(
							    __snake_case			,    help=(
							        "Deprecated: use `huggingface-cli` instead. "
							        "Command will get called by git-lfs, do not call it directly."
							    )			,    )
							upload_parser.set_defaults(func=lambda __snake_case					: LfsUploadCommand(__snake_case					)					)






class 							_a:







		def __init__(     self			,    __snake_case					)   ->   Any:


							'''simple docstring'''

							_snake_case							:       List[Any]												= args







		def 							lowercase							(     self					)   ->   Dict:


							'''simple docstring'''

							warnings.warn(
							    "Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead."					)
							_snake_case							:       Dict												= os.path.abspath(self.args.path					)
							if not os.path.isdir(__snake_case					):
												print("This does not look like a valid git repo."					)
												exit(1					)
							subprocess.run(
							    "git config lfs.customtransfer.multipart.path transformers-cli".split()			,    check=__snake_case			,    cwd=__snake_case					)
							subprocess.run(
							    f"""git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}""".split()			,    check=__snake_case			,    cwd=__snake_case			,    )
							print("Local repo set up for largefiles"					)







def  A					(				UpperCAmelCase					):
					_snake_case							:       str												= json.dumps(UpperCAmelCase					) + "\n"
					sys.stdout.write(UpperCAmelCase					)
					sys.stdout.flush()







def  A					(				):
					_snake_case							:       str												= json.loads(sys.stdin.readline().strip()					)

					if "terminate" in (msg.get("type"					), msg.get("event"					)):
										# terminate message received
										return None

					if msg.get("event"					) not in ("download", "upload"):
										logger.critical("Received unexpected message"					)
										sys.exit(1					)

					return msg






class 							_a(     __A     ):







		def __init__(     self			,    __snake_case			,    __snake_case			,    __snake_case					)   ->   Optional[int]:


							'''simple docstring'''

							_snake_case							:       int												= filepath
							_snake_case							:       Tuple												= seek_from
							_snake_case							:       int												= read_limit
							_snake_case							:       int												= 0







		def __enter__(     self					)   ->   Any:


							'''simple docstring'''

							_snake_case							:       Optional[Any]												= open(self.filepath			,    "rb"					)
							self.f.seek(self.seek_from					)
							return self







		def __len__(     self					)   ->   Dict:


							'''simple docstring'''

							_snake_case							:       Dict												= os.fstat(self.f.fileno()					).st_size
							return min(self.read_limit			,    total_length - self.seek_from					)







		def 							lowercase							(     self			,    __snake_case=-1					)   ->   Union[str, Any]:


							'''simple docstring'''

							if self.n_seen >= self.read_limit:
												return b""
							_snake_case							:       Dict												= self.read_limit - self.n_seen
							_snake_case							:       Tuple												= self.f.read(remaining_amount if n < 0 else min(__snake_case			,    __snake_case					)					)
							self.n_seen += len(__snake_case					)
							return data







		def __iter__(     self					)   ->   int:


							'''simple docstring'''

							yield self.read(n=4 * 1_0_2_4 * 1_0_2_4					)







		def __exit__(     self			,    *__snake_case					)   ->   List[str]:


							'''simple docstring'''

							self.f.close()






class 							_a:







		def __init__(     self			,    __snake_case					)   ->   List[str]:


							'''simple docstring'''

							_snake_case							:       Any												= args







		def 							lowercase							(     self					)   ->   str:


							'''simple docstring'''

							_snake_case							:       Optional[Any]												= json.loads(sys.stdin.readline().strip()					)
							if not (init_msg.get("event"					) == "init" and init_msg.get("operation"					) == "upload"):
												write_msg({"error": {"code": 3_2, "message": "Wrong lfs init operation"}}					)
												sys.exit(1					)

							# The transfer process should use the information it needs from the
							# initiation structure, and also perform any one-off setup tasks it
							# needs to do. It should then respond on stdout with a simple empty
							# confirmation structure, as follows:
							write_msg({}					)

							# After the initiation exchange, git-lfs will send any number of
							# transfer requests to the stdin of the transfer process, in a serial sequence.
							while True:
												_snake_case							:       Optional[Any]												= read_msg()
												if msg is None:
																	# When all transfers have been processed, git-lfs will send
																	# a terminate event to the stdin of the transfer process.
																	# On receiving this message the transfer process should
																	# clean up and terminate. No response is expected.
																	sys.exit(0					)

												_snake_case							:       Dict												= msg["oid"]
												_snake_case							:       int												= msg["path"]
												_snake_case							:       Any												= msg["action"]["href"]
												_snake_case							:       Union[str, Any]												= msg["action"]["header"]
												_snake_case							:       Any												= int(header.pop("chunk_size"					)					)
												_snake_case							:       List[str]												= list(header.values()					)

												_snake_case							:       Any												= []
												for i, presigned_url in enumerate(__snake_case					):
																	with FileSlice(__snake_case			,    seek_from=i * chunk_size			,    read_limit=__snake_case					) as data:
																						_snake_case							:       List[str]												= requests.put(__snake_case			,    data=__snake_case					)
																						r.raise_for_status()
																						parts.append(
																						    {
																						        "etag": r.headers.get("etag"					),
																						        "partNumber": i + 1,
																						    }					)
																						# In order to support progress reporting while data is uploading / downloading,
																						# the transfer process should post messages to stdout
																						write_msg(
																						    {
																						        "event": "progress",
																						        "oid": oid,
																						        "bytesSoFar": (i + 1) * chunk_size,
																						        "bytesSinceLast": chunk_size,
																						    }					)
																						# Not precise but that's ok.

												_snake_case							:       Optional[Any]												= requests.post(
												    __snake_case			,    json={
												        "oid": oid,
												        "parts": parts,
												    }			,    )
												r.raise_for_status()

												write_msg({"event": "complete", "oid": oid}					)