




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


a__		    =    logging.get_logger(__name__)


if is_vision_available():
	import PIL


class       UpperCAmelCase__							(					_a      ):



	"""simple docstring"""


	__magic_name__      :					List[Any]			  =		['pixel_values']






	def __init__(				self		:	str				,    lowerCAmelCase		:	bool = True				,    lowerCAmelCase		:	Dict[str, int] = None				,    lowerCAmelCase		:	PILImageResampling = PILImageResampling.BICUBIC				,    lowerCAmelCase		:	bool = True				,    lowerCAmelCase		:	Dict[str, int] = None				,    lowerCAmelCase		:	bool = True				,    lowerCAmelCase		:	Union[int, float] = 1 / 255				,    lowerCAmelCase		:	bool = True				,    lowerCAmelCase		:	Optional[Union[float, List[float]]] = None				,    lowerCAmelCase		:	Optional[Union[float, List[float]]] = None				,    lowerCAmelCase		:	bool = True				,    **lowerCAmelCase		:	Any				,    )  ->					None:







						"""simple docstring"""







						super().__init__(**lowerCAmelCase  )
						__UpperCamelCase				:  Optional[Any]								=			size if size is not None else {"""shortest_edge""": 224}
						__UpperCamelCase				:  Optional[int]								=			get_size_dict(lowerCAmelCase				,    default_to_square=lowerCAmelCase  )
						__UpperCamelCase				:  Tuple								=			crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						__UpperCamelCase				:  int								=			get_size_dict(lowerCAmelCase  )

						__UpperCamelCase				:  Optional[Any]								=			do_resize
						__UpperCamelCase				:  Any								=			size
						__UpperCamelCase				:  str								=			resample
						__UpperCamelCase				:  int								=			do_center_crop
						__UpperCamelCase				:  str								=			crop_size
						__UpperCamelCase				:  List[str]								=			do_rescale
						__UpperCamelCase				:  Optional[Any]								=			rescale_factor
						__UpperCamelCase				:  Optional[int]								=			do_normalize
						__UpperCamelCase				:  Optional[Any]								=			image_mean if image_mean is not None else OPENAI_CLIP_MEAN
						__UpperCamelCase				:  Optional[int]								=			image_std if image_std is not None else OPENAI_CLIP_STD
						__UpperCamelCase				:  Optional[int]								=			do_convert_rgb






	def 				lowerCamelCase__    (				self		:	Optional[int]				,    lowerCAmelCase		:	np.ndarray				,    lowerCAmelCase		:	Dict[str, int]				,    lowerCAmelCase		:	PILImageResampling = PILImageResampling.BICUBIC				,    lowerCAmelCase		:	Optional[Union[str, ChannelDimension]] = None				,    **lowerCAmelCase		:	Any				,    )  ->					np.ndarray:







						"""simple docstring"""







						__UpperCamelCase				:  Optional[int]								=			get_size_dict(lowerCAmelCase				,    default_to_square=lowerCAmelCase  )
						__UpperCamelCase				:  Optional[int]								=			get_resize_output_image_size(
						    lowerCAmelCase				,    size=(size["""height"""], size["""width"""])				,    default_to_square=lowerCAmelCase  )
						return resize(lowerCAmelCase				,    size=lowerCAmelCase				,    resample=lowerCAmelCase				,    data_format=lowerCAmelCase				,    **lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	List[Any]				,    lowerCAmelCase		:	np.ndarray				,    lowerCAmelCase		:	Dict[str, int]				,    lowerCAmelCase		:	Optional[Union[str, ChannelDimension]] = None				,    **lowerCAmelCase		:	int				,    )  ->					np.ndarray:







						"""simple docstring"""







						__UpperCamelCase				:  Dict								=			get_size_dict(lowerCAmelCase  )
						return center_crop(lowerCAmelCase				,    size=(size["""height"""], size["""width"""])				,    data_format=lowerCAmelCase				,    **lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	int				,    lowerCAmelCase		:	np.ndarray				,    lowerCAmelCase		:	Union[int, float]				,    lowerCAmelCase		:	Optional[Union[str, ChannelDimension]] = None				,    **lowerCAmelCase		:	Tuple				,    )  ->					Dict:







						"""simple docstring"""







						return rescale(lowerCAmelCase				,    scale=lowerCAmelCase				,    data_format=lowerCAmelCase				,    **lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	int				,    lowerCAmelCase		:	np.ndarray				,    lowerCAmelCase		:	Union[float, List[float]]				,    lowerCAmelCase		:	Union[float, List[float]]				,    lowerCAmelCase		:	Optional[Union[str, ChannelDimension]] = None				,    **lowerCAmelCase		:	List[str]				,    )  ->					np.ndarray:







						"""simple docstring"""







						return normalize(lowerCAmelCase				,    mean=lowerCAmelCase				,    std=lowerCAmelCase				,    data_format=lowerCAmelCase				,    **lowerCAmelCase  )






	def 				lowerCamelCase__    (				self		:	Dict				,    lowerCAmelCase		:	ImageInput				,    lowerCAmelCase		:	bool = None				,    lowerCAmelCase		:	Dict[str, int] = None				,    lowerCAmelCase		:	PILImageResampling = None				,    lowerCAmelCase		:	bool = None				,    lowerCAmelCase		:	int = None				,    lowerCAmelCase		:	bool = None				,    lowerCAmelCase		:	float = None				,    lowerCAmelCase		:	bool = None				,    lowerCAmelCase		:	Optional[Union[float, List[float]]] = None				,    lowerCAmelCase		:	Optional[Union[float, List[float]]] = None				,    lowerCAmelCase		:	bool = None				,    lowerCAmelCase		:	Optional[Union[str, TensorType]] = None				,    lowerCAmelCase		:	Optional[ChannelDimension] = ChannelDimension.FIRST				,    **lowerCAmelCase		:	List[str]				,    )  ->					PIL.Image.Image:







						"""simple docstring"""







						__UpperCamelCase				:  Any								=			do_resize if do_resize is not None else self.do_resize
						__UpperCamelCase				:  Any								=			size if size is not None else self.size
						__UpperCamelCase				:  int								=			get_size_dict(lowerCAmelCase				,    default_to_square=lowerCAmelCase  )
						__UpperCamelCase				:  int								=			resample if resample is not None else self.resample
						__UpperCamelCase				:  Union[str, Any]								=			do_center_crop if do_center_crop is not None else self.do_center_crop
						__UpperCamelCase				:  Any								=			crop_size if crop_size is not None else self.crop_size
						__UpperCamelCase				:  int								=			get_size_dict(lowerCAmelCase  )
						__UpperCamelCase				:  Optional[int]								=			do_rescale if do_rescale is not None else self.do_rescale
						__UpperCamelCase				:  Tuple								=			rescale_factor if rescale_factor is not None else self.rescale_factor
						__UpperCamelCase				:  Dict								=			do_normalize if do_normalize is not None else self.do_normalize
						__UpperCamelCase				:  Union[str, Any]								=			image_mean if image_mean is not None else self.image_mean
						__UpperCamelCase				:  Any								=			image_std if image_std is not None else self.image_std
						__UpperCamelCase				:  int								=			do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

						__UpperCamelCase				:  List[str]								=			make_list_of_images(lowerCAmelCase  )

						if not valid_images(lowerCAmelCase  ):
											raise ValueError(
											    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
											    """torch.Tensor, tf.Tensor or jax.ndarray."""  )

						if do_resize and size is None:
											raise ValueError("""Size must be specified if do_resize is True."""  )

						if do_center_crop and crop_size is None:
											raise ValueError("""Crop size must be specified if do_center_crop is True."""  )

						if do_rescale and rescale_factor is None:
											raise ValueError("""Rescale factor must be specified if do_rescale is True."""  )

						if do_normalize and (image_mean is None or image_std is None):
											raise ValueError("""Image mean and std must be specified if do_normalize is True."""  )

						# PIL RGBA images are converted to RGB
						if do_convert_rgb:
											__UpperCamelCase				:  List[str]								=			[convert_to_rgb(lowerCAmelCase  ) for image in images]

						# All transformations expect numpy arrays.
						__UpperCamelCase				:  List[Any]								=			[to_numpy_array(lowerCAmelCase  ) for image in images]

						if do_resize:
											__UpperCamelCase				:  Optional[int]								=			[self.resize(image=lowerCAmelCase				,    size=lowerCAmelCase				,    resample=lowerCAmelCase  ) for image in images]

						if do_center_crop:
											__UpperCamelCase				:  str								=			[self.center_crop(image=lowerCAmelCase				,    size=lowerCAmelCase  ) for image in images]

						if do_rescale:
											__UpperCamelCase				:  Dict								=			[self.rescale(image=lowerCAmelCase				,    scale=lowerCAmelCase  ) for image in images]

						if do_normalize:
											__UpperCamelCase				:  Dict								=			[self.normalize(image=lowerCAmelCase				,    mean=lowerCAmelCase				,    std=lowerCAmelCase  ) for image in images]

						__UpperCamelCase				:  Optional[Any]								=			[to_channel_dimension_format(lowerCAmelCase				,    lowerCAmelCase  ) for image in images]

						__UpperCamelCase				:  Union[str, Any]								=			{"""pixel_values""": images}
						return BatchFeature(data=lowerCAmelCase				,    tensor_type=lowerCAmelCase  )












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()






