






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



@dataclass
class 							A					:
					'''simple docstring'''






					A__    =				field(
					    default='''roberta-large-mnli'''				,						metadata={'''help''': '''The NLI/zero-shot teacher model to be distilled.'''}							)
					A__    =				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.'''
					        )
					    }				,						)
					A__    =				field(
					    default=32				,						metadata={'''help''': '''Batch size for generating teacher predictions.'''}							)
					A__    =				field(
					    default=snake_case__				,						metadata={
					        '''help''': (
					            '''Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called'''
					            '''multi-class multi-label classification).'''
					        )
					    }				,						)
					A__    =				field(
					    default=1.0				,						metadata={'''help''': '''Temperature applied to teacher softmax for distillation.'''}							)






@dataclass
class 							A					:
					'''simple docstring'''






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






@dataclass
class 							A					:
					'''simple docstring'''






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






@dataclass
class 							A					( snake_case__							):
					'''simple docstring'''






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






					def 						lowerCamelCase__  (self					:		Any   ,      _UpperCAmelCase					:		List[Any]   ,      _UpperCAmelCase					:		str   ,      _UpperCAmelCase					:		Optional[int]=False	)		->     Any:




							"""simple docstring"""


							lowercase__      =	inputs['labels']
							lowercase__      =	model(inputs["""input_ids"""]   ,      attention_mask=inputs["""attention_mask"""]	)
							lowercase__      =	outputs[0]

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

							if return_outputs:
									return loss, outputs

							return loss






def 				UpperCamelCase      (			__magic_name__  :							List[str]  )     ->						Tuple:
		"""simple docstring"""




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






def 				UpperCamelCase      (			__magic_name__  :							Optional[Any]					,					__magic_name__  :							Dict					,					__magic_name__  :							Dict  )     ->						Union[str, Any]:
		"""simple docstring"""




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






def 				UpperCamelCase      (			__magic_name__  :							Any  )     ->						Optional[int]:
		"""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      (			__magic_name__  :							Dict					,					__magic_name__  :							Any					,					__magic_name__  :							str					,					__magic_name__  :							str					,					__magic_name__  :							Optional[int]					,					__magic_name__  :							str					,					__magic_name__  :							int					,					__magic_name__  :							Tuple					,					__magic_name__  :							Optional[Any]					,					__magic_name__  :							str					,					)     ->						Optional[Any]:
		"""simple docstring"""




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

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

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

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

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

		lowercase__      =	get_entailment_id(lowerCAmelCase__  )
		lowercase__      =	-1 if entail_id == 0 else 0
		lowercase__      =	torch.cat(lowerCAmelCase__					,					dim=0  )  # N*K x 3
		lowercase__      =	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
				lowercase__      =	(nli_logits / temperature).softmax(-1  )
		else:
				# softmax over entail logits across classes s.t. class probabilities sum to 1.
				lowercase__      =	(nli_logits / temperature).softmax(1  )

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






def 				UpperCamelCase      (			)     ->						Union[str, Any]:
		"""simple docstring"""




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

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

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

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

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

		def compute_metrics(__magic_name__  :							str					,					__magic_name__  :							List[str]=False  ):
				lowercase__      =	p.predictions.argmax(-1  )
				lowercase__      =	p.label_ids.argmax(-1  )  # "label_ids" are actually distributions
				return {"agreement": (preds == proxy_labels).mean().item()}

		lowercase__      =	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:
				lowercase__      =	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 copy

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


A :	Optional[Any]												=     logging.get_logger(__name__)

A :	Union[str, Any]												=     {
    'facebook/sam-vit-huge': 'https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json',
    'facebook/sam-vit-large': 'https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json',
    'facebook/sam-vit-base': 'https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json',
}



class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		Dict   ,      _UpperCAmelCase					:		List[str]=256   ,      _UpperCAmelCase					:		Tuple=1024   ,      _UpperCAmelCase					:		List[str]=16   ,      _UpperCAmelCase					:		Optional[Any]=16   ,      _UpperCAmelCase					:		Union[str, Any]=4   ,      _UpperCAmelCase					:		str="gelu"   ,      _UpperCAmelCase					:		List[str]=1E-6   ,      **_UpperCAmelCase					:		List[Any]   ,      )		->     Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	hidden_size
							lowercase__      =	image_size
							lowercase__      =	patch_size
							lowercase__      =	image_size // patch_size
							lowercase__      =	mask_input_channels
							lowercase__      =	num_point_embeddings
							lowercase__      =	hidden_act
							lowercase__      =	layer_norm_eps






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		List[str]   ,      _UpperCAmelCase					:		Optional[int]=256   ,      _UpperCAmelCase					:		int="relu"   ,      _UpperCAmelCase					:		Union[str, Any]=2048   ,      _UpperCAmelCase					:		int=2   ,      _UpperCAmelCase					:		Optional[Any]=8   ,      _UpperCAmelCase					:		Any=2   ,      _UpperCAmelCase					:		Tuple=3   ,      _UpperCAmelCase					:		List[str]=3   ,      _UpperCAmelCase					:		List[str]=256   ,      _UpperCAmelCase					:		Tuple=1E-6   ,      **_UpperCAmelCase					:		int   ,      )		->     Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	hidden_size
							lowercase__      =	hidden_act
							lowercase__      =	mlp_dim
							lowercase__      =	num_hidden_layers
							lowercase__      =	num_attention_heads
							lowercase__      =	attention_downsample_rate
							lowercase__      =	num_multimask_outputs
							lowercase__      =	iou_head_depth
							lowercase__      =	iou_head_hidden_dim
							lowercase__      =	layer_norm_eps






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		Optional[int]   ,      _UpperCAmelCase					:		List[Any]=768   ,      _UpperCAmelCase					:		Union[str, Any]=256   ,      _UpperCAmelCase					:		Union[str, Any]=12   ,      _UpperCAmelCase					:		Optional[Any]=12   ,      _UpperCAmelCase					:		Tuple=3   ,      _UpperCAmelCase					:		Optional[int]=1024   ,      _UpperCAmelCase					:		str=16   ,      _UpperCAmelCase					:		Tuple="gelu"   ,      _UpperCAmelCase					:		Any=1E-0_6   ,      _UpperCAmelCase					:		Any=0.0   ,      _UpperCAmelCase					:		str=1E-1_0   ,      _UpperCAmelCase					:		Tuple=True   ,      _UpperCAmelCase					:		Tuple=4.0   ,      _UpperCAmelCase					:		Optional[Any]=True   ,      _UpperCAmelCase					:		Optional[int]=True   ,      _UpperCAmelCase					:		Optional[Any]=14   ,      _UpperCAmelCase					:		Optional[int]=[2, 5, 8, 11]   ,      _UpperCAmelCase					:		List[Any]=128   ,      _UpperCAmelCase					:		int=None   ,      **_UpperCAmelCase					:		int   ,      )		->     Dict:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)

							lowercase__      =	hidden_size
							lowercase__      =	output_channels
							lowercase__      =	num_hidden_layers
							lowercase__      =	num_attention_heads
							lowercase__      =	num_channels
							lowercase__      =	image_size
							lowercase__      =	patch_size
							lowercase__      =	hidden_act
							lowercase__      =	layer_norm_eps
							lowercase__      =	attention_dropout
							lowercase__      =	initializer_range
							lowercase__      =	qkv_bias
							lowercase__      =	mlp_ratio
							lowercase__      =	use_abs_pos
							lowercase__      =	use_rel_pos
							lowercase__      =	window_size
							lowercase__      =	global_attn_indexes
							lowercase__      =	num_pos_feats
							lowercase__      =	int(hidden_size * mlp_ratio	) if mlp_dim is None else mlp_dim






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					A__    =				'''sam'''
					A__    =				True

					def __init__(self					:		List[str]   ,      _UpperCAmelCase					:		Any=None   ,      _UpperCAmelCase					:		List[Any]=None   ,      _UpperCAmelCase					:		List[Any]=None   ,      _UpperCAmelCase					:		List[Any]=0.02   ,      **_UpperCAmelCase					:		Optional[Any]   ,      )		->     Dict:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	vision_config if vision_config is not None else {}
							lowercase__      =	prompt_encoder_config if prompt_encoder_config is not None else {}
							lowercase__      =	mask_decoder_config if mask_decoder_config is not None else {}

							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	vision_config.to_dict()
							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	prompt_encoder_config.to_dict()
							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	mask_decoder_config.to_dict()

							lowercase__      =	SamVisionConfig(**_UpperCAmelCase	)
							lowercase__      =	SamPromptEncoderConfig(**_UpperCAmelCase	)
							lowercase__      =	SamMaskDecoderConfig(**_UpperCAmelCase	)
							lowercase__      =	initializer_range


					def 						lowerCamelCase__  (self					:		Union[str, Any]	)		->     Tuple:




							"""simple docstring"""


							lowercase__      =	copy.deepcopy(self.__dict__	)
							lowercase__      =	self.vision_config.to_dict()
							lowercase__      =	self.prompt_encoder_config.to_dict()
							lowercase__      =	self.mask_decoder_config.to_dict()
							lowercase__      =	self.__class__.model_type
							return output

