
'''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


_lowercase					:    List[Any]       				=			'\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'

_lowercase					:    str       				=			logging.getLogger(__name__)






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







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







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







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






					def       _snake_case       (  self							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE=False						):


											"""simple docstring"""





											lowercase_      :	Optional[Any]						=			inputs['''labels''']
											lowercase_      :	Optional[int]						=			model(inputs['''input_ids''']							,				attention_mask=inputs['''attention_mask''']						)
											lowercase_      :	int						=			outputs[0]

											lowercase_      :	List[str]						=			-torch.sum(target_p * logits.log_softmax(dim=-1						)							,				axis=-1						).mean()

											if return_outputs:
																	return loss, outputs

											return loss







def    snake_case_						(							__SCREAMING_SNAKE_CASE   :					Any				):



						"""simple docstring"""





						lowercase_      :	Optional[int]						=			[]
						with open(lowerCAmelCase_ , '''r'''				) as f:
												for line in f:
																		lowercase_      :	int						=			line.strip()
																		if len(lowerCAmelCase_				) > 0:
																								lines.append(lowerCAmelCase_				)
						return lines
def    snake_case_						(							__SCREAMING_SNAKE_CASE   :					Any , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , __SCREAMING_SNAKE_CASE   :					List[str]				):



						"""simple docstring"""





						lowercase_      :	Any						=			[]
						lowercase_      :	Union[str, Any]						=			[]
						for example in examples:
												for name in class_names:
																		premises.append(lowerCAmelCase_				)
																		hypotheses.append(hypothesis_template.format(lowerCAmelCase_				)				)
						return premises, hypotheses
def    snake_case_						(							__SCREAMING_SNAKE_CASE   :					Union[str, Any]				):



						"""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    snake_case_						(							__SCREAMING_SNAKE_CASE   :					str , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , __SCREAMING_SNAKE_CASE   :					Dict , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , __SCREAMING_SNAKE_CASE   :					List[str] , __SCREAMING_SNAKE_CASE   :					str , __SCREAMING_SNAKE_CASE   :					List[str] , __SCREAMING_SNAKE_CASE   :					Union[str, Any] , ):



						"""simple docstring"""





						lowercase_      :	List[Any]						=			AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase_				)
						lowercase_      :	Dict						=			model.config
						if not no_cuda and torch.cuda.is_available():
												lowercase_      :	Optional[int]						=			nn.DataParallel(model.cuda()				)
												batch_size *= len(model.device_ids				)
						lowercase_      :	int						=			AutoTokenizer.from_pretrained(lowerCAmelCase_ , use_fast=lowerCAmelCase_				)

						lowercase_		,					lowercase_      :	Dict						=			get_premise_hypothesis_pairs(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_				)
						lowercase_      :	Tuple						=			[]

						for i in tqdm(range(0 , len(lowerCAmelCase_				) , lowerCAmelCase_				)				):
												lowercase_      :	str						=			premises[i : i + batch_size]
												lowercase_      :	List[Any]						=			hypotheses[i : i + batch_size]

												lowercase_      :	List[str]						=			tokenizer(
												    lowerCAmelCase_ , lowerCAmelCase_ , padding=lowerCAmelCase_ , truncation='''only_first''' , return_tensors='''pt''' , )

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

						lowercase_      :	Union[str, Any]						=			get_entailment_id(lowerCAmelCase_				)
						lowercase_      :	Dict						=			-1 if entail_id == 0 else 0
						lowercase_      :	Dict						=			torch.cat(lowerCAmelCase_ , dim=0				)  # N*K x 3
						lowercase_      :	List[str]						=			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_      :	List[str]						=			(nli_logits / temperature).softmax(-1				)
						else:
												# softmax over entail logits across classes s.t. class probabilities sum to 1.
												lowercase_      :	str						=			(nli_logits / temperature).softmax(1				)

						return nli_prob[..., 1]  # N x K
def    snake_case_						(							):



						"""simple docstring"""





						lowercase_      :	List[str]						=			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_		,					lowercase_		,					lowercase_		,					lowercase_      :	Optional[Any]						=			parser.parse_json_file(
												    json_file=os.path.abspath(sys.argv[1]				)				)
						else:
												lowercase_		,					lowercase_		,					lowercase_		,					lowercase_      :	List[Any]						=			parser.parse_args_into_dataclasses()

						# Detecting last checkpoint.
						lowercase_      :	int						=			None
						if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
												lowercase_      :	List[str]						=			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_      :	Any						=			read_lines(data_args.data_file				)
						lowercase_      :	Union[str, Any]						=			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_      :	Any						=			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_      :	Dict						=			Dataset.from_dict(
						    {
						        '''text''': examples,
						        '''labels''': teacher_soft_preds,
						    }				)

						# 3. create student
						logger.info('''Initializing student model'''				)
						lowercase_      :	str						=			AutoModelForSequenceClassification.from_pretrained(
						    student_args.student_name_or_path , num_labels=len(lowerCAmelCase_				)				)
						lowercase_      :	Any						=			AutoTokenizer.from_pretrained(student_args.student_name_or_path , use_fast=data_args.use_fast_tokenizer				)
						lowercase_      :	Any						=			dict(enumerate(lowerCAmelCase_				)				)
						lowercase_      :	Optional[Any]						=			{label: i for i, label in enumerate(lowerCAmelCase_				)}

						# 4. train student on teacher predictions
						lowercase_      :	Any						=			dataset.map(lowerCAmelCase_ , input_columns='''text'''				)
						dataset.set_format('''torch'''				)

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

						lowercase_      :	List[Any]						=			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_      :	Union[str, Any]						=			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()








'''simple docstring'''







import argparse
import os

# New Code #
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator
from accelerate.utils import find_executable_batch_size


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to combine both the gradient accumulation
# and automatic batch size finder utilities of Accelerate to perfrom
# automatic gradient accumulation
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################

lowercase__  :	Optional[Any]            =      32





def     snake_case__			(lowerCAmelCase_       ,	lowerCAmelCase_ = 16						):
    UpperCamelCase__	     =      AutoTokenizer.from_pretrained("bert-base-cased"						)
    UpperCamelCase__	     =      load_dataset("glue"       ,	"mrpc"						)

    def tokenize_function(lowerCAmelCase_						):
        # max_length=None => use the model max length (it's actually the default)
        UpperCamelCase__	     =      tokenizer(examples["sentence1"]       ,	examples["sentence2"]       ,	truncation=lowerCAmelCase_       ,	max_length=lowerCAmelCase_						)
        return outputs

    # Apply the method we just defined to all the examples in all the splits of the dataset
    # starting with the main process first:
    with accelerator.main_process_first():
        UpperCamelCase__	     =      datasets.map(
            lowerCAmelCase_       ,	batched=lowerCAmelCase_       ,	remove_columns=["idx", "sentence1", "sentence2"]       ,	)

    # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
    # transformers library
    UpperCamelCase__	     =      tokenized_datasets.rename_column("label"       ,	"labels"						)

    def collate_fn(lowerCAmelCase_						):
        # When using mixed precision we want round multiples of 8/16
        if accelerator.mixed_precision == "fp8":
            UpperCamelCase__	     =      16
        elif accelerator.mixed_precision != "no":
            UpperCamelCase__	     =      8
        else:
            UpperCamelCase__	     =      None

        return tokenizer.pad(
            lowerCAmelCase_       ,	padding="longest"       ,	pad_to_multiple_of=lowerCAmelCase_       ,	return_tensors="pt"       ,	)

    # Instantiate dataloaders.
    UpperCamelCase__	     =      DataLoader(
        tokenized_datasets["train"]       ,	shuffle=lowerCAmelCase_       ,	collate_fn=lowerCAmelCase_       ,	batch_size=lowerCAmelCase_						)
    UpperCamelCase__	     =      DataLoader(
        tokenized_datasets["validation"]       ,	shuffle=lowerCAmelCase_       ,	collate_fn=lowerCAmelCase_       ,	batch_size=lowerCAmelCase_						)

    return train_dataloader, eval_dataloader


# For testing only
if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1":
      from accelerate.test_utils.training import mocked_dataloaders

      lowercase__  :	Dict            =      mocked_dataloaders  # noqa: F811





def     snake_case__			(lowerCAmelCase_       ,	lowerCAmelCase_						):
    # For testing only
    if os.environ.get("TESTING_MOCKED_DATALOADERS"       ,	lowerCAmelCase_						) == "1":
        UpperCamelCase__	     =      2
    # Initialize accelerator
    UpperCamelCase__	     =      Accelerator(cpu=args.cpu       ,	mixed_precision=args.mixed_precision						)
    # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
    UpperCamelCase__	     =      config["lr"]
    UpperCamelCase__	     =      int(config["num_epochs"]						)
    UpperCamelCase__	     =      int(config["seed"]						)
    UpperCamelCase__	     =      int(config["batch_size"]						)

    UpperCamelCase__	     =      evaluate.load("glue"       ,	"mrpc"						)

    # New Code #
    # We use the `find_executable_batch_size` decorator, passing in the desired observed batch size
    # to train on. If a CUDA OOM error occurs, it will retry this loop cutting the batch size in
    # half each time. From this, we can calculate the number of gradient accumulation steps needed
    # and modify the Accelerator object as a result
    @find_executable_batch_size(starting_batch_size=int(lowerCAmelCase_						)						)
    def inner_training_loop(lowerCAmelCase_						):
        # Since we need to modify the outside accelerator object, we need to bring it
        # to the local scope
        nonlocal accelerator

        # We can calculate the number of gradient accumulation steps based on the current
        # batch size vs the starting batch size
        UpperCamelCase__	     =      observed_batch_size // batch_size

        # And then set it in the Accelerator directly:
        UpperCamelCase__	     =      num_gradient_accumulation_steps

        # Next we need to free all of the stored model references in the Accelerator each time
        accelerator.free_memory()

        # And set the seed so our results are reproducable each reset
        set_seed(lowerCAmelCase_						)

        # Instantiate the model (we build the model here so that the seed also control new weights initialization)
        UpperCamelCase__	     =      AutoModelForSequenceClassification.from_pretrained("bert-base-cased"       ,	return_dict=lowerCAmelCase_						)

        # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
        # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
        # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
        UpperCamelCase__	     =      model.to(accelerator.device						)

        # Instantiate optimizer
        UpperCamelCase__	     =      AdamW(params=model.parameters()       ,	lr=lowerCAmelCase_						)
        UpperCamelCase__     ,	UpperCamelCase__	     =      get_dataloaders(lowerCAmelCase_       ,	lowerCAmelCase_						)

        # Instantiate scheduler
        UpperCamelCase__	     =      get_linear_schedule_with_warmup(
            optimizer=lowerCAmelCase_       ,	num_warmup_steps=1_00       ,	num_training_steps=(len(lowerCAmelCase_						) * num_epochs)       ,	)

        # Prepare everything
        # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
        # prepare method.
        UpperCamelCase__     ,	UpperCamelCase__     ,	UpperCamelCase__     ,	UpperCamelCase__     ,	UpperCamelCase__	     =      accelerator.prepare(
            lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_						)

        # Now we train the model
        for epoch in range(lowerCAmelCase_						):
            model.train()
            for step, batch in enumerate(lowerCAmelCase_						):
                # And perform gradient accumulation
                with accelerator.accumulate(lowerCAmelCase_						):
                    # We could avoid this line since we set the accelerator with `device_placement=True`.
                    batch.to(accelerator.device						)
                    UpperCamelCase__	     =      model(**lowerCAmelCase_						)
                    UpperCamelCase__	     =      outputs.loss
                    accelerator.backward(lowerCAmelCase_						)
                    optimizer.step()
                    lr_scheduler.step()
                    optimizer.zero_grad()

            model.eval()
            for step, batch in enumerate(lowerCAmelCase_						):
                # We could avoid this line since we set the accelerator with `device_placement=True`.
                batch.to(accelerator.device						)
                with torch.no_grad():
                    UpperCamelCase__	     =      model(**lowerCAmelCase_						)
                UpperCamelCase__	     =      outputs.logits.argmax(dim=-1						)
                UpperCamelCase__     ,	UpperCamelCase__	     =      accelerator.gather_for_metrics((predictions, batch["labels"])						)
                metric.add_batch(
                    predictions=lowerCAmelCase_       ,	references=lowerCAmelCase_       ,	)

            UpperCamelCase__	     =      metric.compute()
            # Use accelerator.print to print only on the main process.
            accelerator.print(F'epoch {epoch}:'       ,	lowerCAmelCase_						)

    # New Code #
    # And call it at the end with no arguments
    # Note: You could also refactor this outside of your training loop function
    inner_training_loop()





def     snake_case__			():
    UpperCamelCase__	     =      argparse.ArgumentParser(description="Simple example of training script."						)
    parser.add_argument(
        "--mixed_precision"       ,	type=lowerCAmelCase_       ,	default=lowerCAmelCase_       ,	choices=["no", "fp16", "bf16", "fp8"]       ,	help="Whether to use mixed precision. Choose"
        "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
        "and an Nvidia Ampere GPU."       ,	)
    parser.add_argument("--cpu"       ,	action="store_true"       ,	help="If passed, will train on the CPU."						)
    UpperCamelCase__	     =      parser.parse_args()
    # New Code #
    # We modify the starting batch size to be an observed batch size of 256, to guarentee an initial CUDA OOM
    UpperCamelCase__	     =      {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 2_56}
    training_function(lowerCAmelCase_       ,	lowerCAmelCase_						)


if __name__ == "__main__":
      main()




