






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


snake_case_   :	Union[str, Any]							      ='''
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.
'''

snake_case_   :	str							      =logging.getLogger(__name__)





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





@dataclass
class        a__      :
		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        a__      (	lowerCAmelCase__		):
		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        a__      (	lowerCAmelCase__		):






		def 					_lowerCamelCase					(      self							, lowercase__							, lowercase__							, lowercase__=False						)				->				int:
				__A    =							inputs["labels"]
				__A    =							model(inputs["input_ids"]							, attention_mask=inputs["attention_mask"]						)
				__A    =							outputs[0]

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

				if return_outputs:
						return loss, outputs

				return loss



def      UpperCAmelCase						( lowerCAmelCase__	):


		'''simple docstring'''

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



def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		__A    =							[]
		__A    =							[]
		for example in examples:
				for name in class_names:
						premises.append(lowerCAmelCase__	)
						hypotheses.append(hypothesis_template.format(lowerCAmelCase__	)	)
		return premises, hypotheses



def      UpperCAmelCase						( lowerCAmelCase__	):


		'''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						( lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     ):


		'''simple docstring'''

		__A    =							AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__	)
		__A    =							model.config
		if not no_cuda and torch.cuda.is_available():
				__A    =							nn.DataParallel(model.cuda()	)
				batch_size *= len(model.device_ids	)
		__A    =							AutoTokenizer.from_pretrained(lowerCAmelCase__					,     use_fast=lowerCAmelCase__	)

		__A ,   __A    =							get_premise_hypothesis_pairs(lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__	)
		__A    =							[]

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

				__A    =							tokenizer(
				    lowerCAmelCase__					,     lowerCAmelCase__					,     padding=lowerCAmelCase__					,     truncation="only_first"					,     return_tensors="pt"					,     )

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

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

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

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



def      UpperCAmelCase						( ):


		'''simple docstring'''

		__A    =							HfArgumentParser(
		    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)					,     description=lowerCAmelCase__					,     )

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

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

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

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

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

		def compute_metrics(lowerCAmelCase__					,     lowerCAmelCase__=False	):
				__A    =							p.predictions.argmax(-1	)
				__A    =							p.label_ids.argmax(-1	)  # "label_ids" are actually distributions
				return {"agreement": (preds == proxy_labels).mean().item()}

		__A    =							DistillationTrainer(
		    model=lowerCAmelCase__					,     tokenizer=lowerCAmelCase__					,     args=lowerCAmelCase__					,     train_dataset=lowerCAmelCase__					,     compute_metrics=lowerCAmelCase__					,     )

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

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

		trainer.save_model()


if __name__ == "__main__":
					main()









import sys
from typing import Tuple

import numpy as np
import torch
from PIL import Image
from torch import nn

from transformers.image_utils import PILImageResampling
from utils import img_tensorize





class        a__      :






		def __init__(      self							, lowercase__							, lowercase__=sys.maxsize						)				->				str:
				__A    =							"bilinear"
				__A    =							max_size
				__A    =							short_edge_length






		def __call__(      self							, lowercase__						)				->				Dict:
				__A    =							[]
				for img in imgs:
						__A ,   __A    =							img.shape[:2]
						# later: provide list and randomly choose index for resize
						__A    =							np.random.randint(self.short_edge_length[0]							, self.short_edge_length[1] + 1						)
						if size == 0:
								return img
						__A    =							size * 1.0 / min(lowercase__							, lowercase__						)
						if h < w:
								__A ,   __A    =							size, scale * w
						else:
								__A ,   __A    =							scale * h, size
						if max(lowercase__							, lowercase__						) > self.max_size:
								__A    =							self.max_size * 1.0 / max(lowercase__							, lowercase__						)
								__A    =							newh * scale
								__A    =							neww * scale
						__A    =							int(neww + 0.5						)
						__A    =							int(newh + 0.5						)

						if img.dtype == np.uinta:
								__A    =							Image.fromarray(lowercase__						)
								__A    =							pil_image.resize((neww, newh)							, PILImageResampling.BILINEAR						)
								__A    =							np.asarray(lowercase__						)
						else:
								__A    =							img.permute(2							, 0							, 1						).unsqueeze(0						)  # 3, 0, 1)  # hw(c) -> nchw
								__A    =							nn.functional.interpolate(
								    lowercase__							, (newh, neww)							, mode=self.interp_method							, align_corners=lowercase__						).squeeze(0						)
						img_augs.append(lowercase__						)

				return img_augs





class        a__      :






		def __init__(      self							, lowercase__						)				->				Union[str, Any]:
				__A    =							ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST]							, cfg.INPUT.MAX_SIZE_TEST						)
				__A    =							cfg.INPUT.FORMAT
				__A    =							cfg.SIZE_DIVISIBILITY
				__A    =							cfg.PAD_VALUE
				__A    =							cfg.INPUT.MAX_SIZE_TEST
				__A    =							cfg.MODEL.DEVICE
				__A    =							torch.tensor(cfg.MODEL.PIXEL_STD						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						)							, 1							, 1						)
				__A    =							torch.tensor(cfg.MODEL.PIXEL_MEAN						).to(self.device						).view(len(cfg.MODEL.PIXEL_STD						)							, 1							, 1						)
				__A    =							lambda lowercase__						: (x - self.pixel_mean) / self.pixel_std






		def 					_lowerCamelCase					(      self							, lowercase__						)				->				Optional[int]:
				__A    =							tuple(max(lowercase__						) for s in zip(*[img.shape for img in images]						)						)
				__A    =							[im.shape[-2:] for im in images]
				__A    =							[
				    nn.functional.pad(
				        lowercase__							, [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]]							, value=self.pad_value							, )
				    for size, im in zip(lowercase__							, lowercase__						)
				]

				return torch.stack(lowercase__						), torch.tensor(lowercase__						)






		def __call__(      self							, lowercase__							, lowercase__=False						)				->				int:
				with torch.no_grad():
						if not isinstance(lowercase__							, lowercase__						):
								__A    =							[images]
						if single_image:
								assert len(lowercase__						) == 1
						for i in range(len(lowercase__						)						):
								if isinstance(images[i]							, torch.Tensor						):
										images.insert(lowercase__							, images.pop(lowercase__						).to(self.device						).float()						)
								elif not isinstance(images[i]							, torch.Tensor						):
										images.insert(
										    lowercase__							, torch.as_tensor(img_tensorize(images.pop(lowercase__						)							, input_format=self.input_format						)						)
										    .to(self.device						)
										    .float()							, )
            # resize smallest edge
						__A    =							torch.tensor([im.shape[:2] for im in images]						)
						__A    =							self.aug(lowercase__						)
						# transpose images and convert to torch tensors
						# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
						# now normalize before pad to avoid useless arithmetic
						__A    =							[self.normalizer(lowercase__						) for x in images]
						# now pad them to do the following operations
						__A ,   __A    =							self.pad(lowercase__						)
						# Normalize

						if self.size_divisibility > 0:
								raise NotImplementedError()
						# pad
						__A    =							torch.true_divide(lowercase__							, lowercase__						)
						if single_image:
								return images[0], sizes[0], scales_yx[0]
						else:
								return images, sizes, scales_yx



def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		boxes[:, 0::2] *= scale_yx[:, 1]
		boxes[:, 1::2] *= scale_yx[:, 0]
		return boxes





def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		assert torch.isfinite(lowerCAmelCase__	).all(), "Box tensor contains infinite or NaN!"
		__A ,   __A    =							box_size
		tensor[:, 0].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 1].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 2].clamp_(min=0					,     max=lowerCAmelCase__	)
		tensor[:, 3].clamp_(min=0					,     max=lowerCAmelCase__	)

