




'''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							:						int							     =  '\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							:						Any							     =  logging.getLogger(__name__)





@dataclass
class 					lowerCamelCase_							:




					'''simple docstring'''






					lowercase__   =			field(
					    default="""roberta-large-mnli""",	metadata={"""help""": """The NLI/zero-shot teacher model to be distilled."""}							)
					lowercase__   =			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."""
					        )
					    },	)
					lowercase__   =			field(
					    default=3_2,	metadata={"""help""": """Batch size for generating teacher predictions."""}							)
					lowercase__   =			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)."""
					        )
					    },	)
					lowercase__   =			field(
					    default=1.0,	metadata={"""help""": """Temperature applied to teacher softmax for distillation."""}							)





@dataclass
class 					lowerCamelCase_							:




					'''simple docstring'''






					lowercase__   =			field(
					    default="""distilbert-base-uncased""",	metadata={"""help""": """The NLI/zero-shot teacher model to be distilled."""}							)





@dataclass
class 					lowerCamelCase_							:




					'''simple docstring'''






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





@dataclass
class 					lowerCamelCase_							(	UpperCAmelCase_							):




					'''simple docstring'''






					lowercase__   =			field(
					    default=UpperCAmelCase_,	metadata={"""help""": """The output directory where the model predictions and checkpoints will be written."""},	)
					lowercase__   =			field(
					    default=3_2,	metadata={"""help""": """Batch size per GPU/TPU core/CPU for training."""}							)
					lowercase__   =			field(
					    default=1_2_8,	metadata={"""help""": """Batch size per GPU/TPU core/CPU for evaluation."""}							)
					lowercase__   =			field(default=1.0,	metadata={"""help""": """Total number of training epochs to perform."""}							)
					lowercase__   =			field(default=UpperCAmelCase_,	metadata={"""help""": """Whether to run training of student model."""}							)
					lowercase__   =			field(
					    default=UpperCAmelCase_,	metadata={
					        """help""": (
					            """Whether to evaluate the agreement of the final student predictions and the teacher predictions"""
					            """after training."""
					        )
					    },	)
					lowercase__   =			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_							(	UpperCAmelCase_							):




					'''simple docstring'''






					def     __SCREAMING_SNAKE_CASE     (   self,  __UpperCamelCase,  __UpperCamelCase,  __UpperCamelCase=False			):
							_snake_case     	=	inputs["labels"]
							_snake_case     	=	model(inputs["input_ids"],  attention_mask=inputs["attention_mask"]			)
							_snake_case     	=	outputs[0]

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

							if return_outputs:
									return loss, outputs

							return loss






def 		_lowercase		(     lowercase_  ):



		'''simple docstring'''







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






def 		_lowercase		(     lowercase_						,							lowercase_						,							lowercase_  ):



		'''simple docstring'''







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






def 		_lowercase		(     lowercase_  ):



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



		'''simple docstring'''







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

		_snake_case	,   _snake_case     	=	get_premise_hypothesis_pairs(lowercase_						,							lowercase_						,							lowercase_  )
		_snake_case     	=	[]

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

				_snake_case     	=	tokenizer(
				    lowercase_						,							lowercase_						,							padding=lowercase_						,							truncation="only_first"						,							return_tensors="pt"						,							)

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

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

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

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






def 		_lowercase		(     ):



		'''simple docstring'''







		_snake_case     	=	HfArgumentParser(
		    (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)						,							description=lowercase_						,							)

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

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

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

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

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

		_snake_case     	=	DistillationTrainer(
		    model=lowercase_						,							tokenizer=lowercase_						,							args=lowercase_						,							train_dataset=lowercase_						,							compute_metrics=lowercase_						,							)

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

		if training_args.do_eval:
				_snake_case     	=	trainer.evaluate(eval_dataset=lowercase_  )["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 unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import CLIPImageProcessor





class 					lowerCamelCase_							(	unittest.TestCase							):




					'''simple docstring'''






					def __init__(   self,  __UpperCamelCase,  __UpperCamelCase=7,  __UpperCamelCase=3,  __UpperCamelCase=18,  __UpperCamelCase=30,  __UpperCamelCase=400,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73],  __UpperCamelCase=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11],  __UpperCamelCase=True,  ):
							_snake_case     	=	size if size is not None else {"shortest_edge": 20}
							_snake_case     	=	crop_size if crop_size is not None else {"height": 18, "width": 18}
							_snake_case     	=	parent
							_snake_case     	=	batch_size
							_snake_case     	=	num_channels
							_snake_case     	=	image_size
							_snake_case     	=	min_resolution
							_snake_case     	=	max_resolution
							_snake_case     	=	do_resize
							_snake_case     	=	size
							_snake_case     	=	do_center_crop
							_snake_case     	=	crop_size
							_snake_case     	=	do_normalize
							_snake_case     	=	image_mean
							_snake_case     	=	image_std
							_snake_case     	=	do_convert_rgb






					def     __SCREAMING_SNAKE_CASE     (   self			):
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_center_crop": self.do_center_crop,
							    "crop_size": self.crop_size,
							    "do_normalize": self.do_normalize,
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_convert_rgb": self.do_convert_rgb,
							}






					def     __SCREAMING_SNAKE_CASE     (   self,  __UpperCamelCase=False,  __UpperCamelCase=False,  __UpperCamelCase=False			):
							assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

							if equal_resolution:
									_snake_case     	=	[]
									for i in range(self.batch_size			):
											image_inputs.append(
											    np.random.randint(
											        255,  size=(self.num_channels, self.max_resolution, self.max_resolution),  dtype=np.uinta			)			)
							else:
									_snake_case     	=	[]
									for i in range(self.batch_size			):
											_snake_case	,   _snake_case     	=	np.random.choice(np.arange(self.min_resolution,  self.max_resolution			),  2			)
											image_inputs.append(np.random.randint(255,  size=(self.num_channels, width, height),  dtype=np.uinta			)			)

							if not numpify and not torchify:
									# PIL expects the channel dimension as last dimension
									_snake_case     	=	[Image.fromarray(np.moveaxis(__UpperCamelCase,  0,  -1			)			) for x in image_inputs]

							if torchify:
									_snake_case     	=	[torch.from_numpy(__UpperCamelCase			) for x in image_inputs]

							return image_inputs





@require_torch
@require_vision
class 					lowerCamelCase_							(	UpperCAmelCase_,	unittest.TestCase							):




					'''simple docstring'''






					lowercase__   =			CLIPImageProcessor if is_vision_available() else None






					def     __SCREAMING_SNAKE_CASE     (   self			):
							_snake_case     	=	CLIPImageProcessingTester(self			)






					@property
					def     __SCREAMING_SNAKE_CASE     (   self			):
							return self.image_processor_tester.prepare_image_processor_dict()






					def     __SCREAMING_SNAKE_CASE     (   self			):
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_resize"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "size"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_center_crop"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "center_crop"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_normalize"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "image_mean"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "image_std"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_convert_rgb"			)			)






					def     __SCREAMING_SNAKE_CASE     (   self			):
							_snake_case     	=	self.image_processing_class.from_dict(self.image_processor_dict			)
							self.assertEqual(image_processor.size,  {"shortest_edge": 20}			)
							self.assertEqual(image_processor.crop_size,  {"height": 18, "width": 18}			)

							_snake_case     	=	self.image_processing_class.from_dict(self.image_processor_dict,  size=42,  crop_size=84			)
							self.assertEqual(image_processor.size,  {"shortest_edge": 42}			)
							self.assertEqual(image_processor.crop_size,  {"height": 84, "width": 84}			)






					def     __SCREAMING_SNAKE_CASE     (   self			):
							pass






					def     __SCREAMING_SNAKE_CASE     (   self			):
							# Initialize image_processing
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							# create random PIL images
							_snake_case     	=	self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCamelCase			)
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  Image.Image			)

							# Test not batched input
							_snake_case     	=	image_processing(image_inputs[0],  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )

							# Test batched
							_snake_case     	=	image_processing(__UpperCamelCase,  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )






					def     __SCREAMING_SNAKE_CASE     (   self			):
							# Initialize image_processing
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							# create random numpy tensors
							_snake_case     	=	self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCamelCase,  numpify=__UpperCamelCase			)
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  np.ndarray			)

							# Test not batched input
							_snake_case     	=	image_processing(image_inputs[0],  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )

							# Test batched
							_snake_case     	=	image_processing(__UpperCamelCase,  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )






					def     __SCREAMING_SNAKE_CASE     (   self			):
							# Initialize image_processing
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							# create random PyTorch tensors
							_snake_case     	=	self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCamelCase,  torchify=__UpperCamelCase			)
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  torch.Tensor			)

							# Test not batched input
							_snake_case     	=	image_processing(image_inputs[0],  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        1,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )

							# Test batched
							_snake_case     	=	image_processing(__UpperCamelCase,  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )





@require_torch
@require_vision
class 					lowerCamelCase_							(	UpperCAmelCase_,	unittest.TestCase							):




					'''simple docstring'''






					lowercase__   =			CLIPImageProcessor if is_vision_available() else None






					def     __SCREAMING_SNAKE_CASE     (   self			):
							_snake_case     	=	CLIPImageProcessingTester(self,  num_channels=4			)
							_snake_case     	=	3






					@property
					def     __SCREAMING_SNAKE_CASE     (   self			):
							return self.image_processor_tester.prepare_image_processor_dict()






					def     __SCREAMING_SNAKE_CASE     (   self			):
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_resize"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "size"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_center_crop"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "center_crop"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_normalize"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "image_mean"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "image_std"			)			)
							self.assertTrue(hasattr(__UpperCamelCase,  "do_convert_rgb"			)			)






					def     __SCREAMING_SNAKE_CASE     (   self			):
							pass






					def     __SCREAMING_SNAKE_CASE     (   self			):
							# Initialize image_processing
							_snake_case     	=	self.image_processing_class(**self.image_processor_dict			)
							# create random PIL images
							_snake_case     	=	self.image_processor_tester.prepare_inputs(equal_resolution=__UpperCamelCase			)
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  Image.Image			)

							# Test not batched input
							_snake_case     	=	image_processing(image_inputs[0],  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        1,
							        self.expected_encoded_image_num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )

							# Test batched
							_snake_case     	=	image_processing(__UpperCamelCase,  return_tensors="pt"			).pixel_values
							self.assertEqual(
							    encoded_images.shape,  (
							        self.image_processor_tester.batch_size,
							        self.expected_encoded_image_num_channels,
							        self.image_processor_tester.crop_size["height"],
							        self.image_processor_tester.crop_size["width"],
							    ),  )





