


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


__SCREAMING_SNAKE_CASE					=						"""
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.
"""

__SCREAMING_SNAKE_CASE					=						logging.getLogger(__name__)





@dataclass
class __snake_case		:







   """simple docstring"""




   lowerCAmelCase_				:   Optional[str]     	=			field(
       default='roberta-large-mnli'				,       metadata={'help': 'The NLI/zero-shot teacher model to be distilled.'}      )
   lowerCAmelCase_				:   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.'
           )
       }				,       )
   lowerCAmelCase_				:   Optional[int]     	=			field(
       default=32				,       metadata={'help': 'Batch size for generating teacher predictions.'}      )
   lowerCAmelCase_				:   Optional[bool]     	=			field(
       default=_SCREAMING_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).'
           )
       }				,       )
   lowerCAmelCase_				:   Optional[float]     	=			field(
       default=1.0				,       metadata={'help': 'Temperature applied to teacher softmax for distillation.'}      )






@dataclass
class __snake_case		:







   """simple docstring"""




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






@dataclass
class __snake_case		:







   """simple docstring"""




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






@dataclass
class __snake_case		(					_SCREAMING_SNAKE_CASE      ):







   """simple docstring"""




   lowerCAmelCase_				:   Optional[str]     	=			field(
       default=_SCREAMING_SNAKE_CASE				,       metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'}				,       )
   lowerCAmelCase_				:   int     	=			field(
       default=32				,       metadata={'help': 'Batch size per GPU/TPU core/CPU for training.'}      )
   lowerCAmelCase_				:   int     	=			field(
       default=128				,       metadata={'help': 'Batch size per GPU/TPU core/CPU for evaluation.'}      )
   lowerCAmelCase_				:   float     	=			field(default=1.0				,       metadata={'help': 'Total number of training epochs to perform.'}      )
   lowerCAmelCase_				:   bool     	=			field(default=_SCREAMING_SNAKE_CASE				,       metadata={'help': 'Whether to run training of student model.'}      )
   lowerCAmelCase_				:   bool     	=			field(
       default=_SCREAMING_SNAKE_CASE				,       metadata={
           'help': (
               'Whether to evaluate the agreement of the final student predictions and the teacher predictions'
               'after training.'
           )
       }				,       )
   lowerCAmelCase_				:   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 __snake_case		(					_SCREAMING_SNAKE_CASE      ):







   """simple docstring"""




   def SCREAMING_SNAKE_CASE_      (		self							:Any				,  UpperCamelCase__							:Tuple				,  UpperCamelCase__							:Optional[int]				,  UpperCamelCase__							:Optional[int]=False       ):
          _a          =				inputs["labels"]
          _a          =				model(inputs["input_ids"]				,  attention_mask=inputs["attention_mask"]       )
          _a          =				outputs[0]

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

          if return_outputs:
                 return loss, outputs

          return loss






def 						__a      (  a					):





       """simple docstring"""







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



def 						__a      (  a,		a,		a					):





       """simple docstring"""







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



def 						__a      (  a					):





       """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 						__a      (  a,		a,		a,		a,		a,		a,		a,		a,		a,		a,		):





       """simple docstring"""







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

       _a   , _a          =				get_premise_hypothesis_pairs(a,		a,		a					)
       _a          =				[]

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

              _a          =				tokenizer(
                  a,		a,		padding=a,		truncation="only_first",		return_tensors="pt",		)

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

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

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

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



def 						__a      (  ):





       """simple docstring"""







       _a          =				HfArgumentParser(
           (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments),		description=a,		)

       if len(sys.argv					) == 2 and sys.argv[1].endswith(".json"					):
              # If we pass only one argument to the script and it's the path to a json file,
              # let's parse it to get our arguments.
              _a   , _a   , _a   , _a          =				parser.parse_json_file(
                  json_file=os.path.abspath(sys.argv[1]					)					)
       else:
              _a   , _a   , _a   , _a          =				parser.parse_args_into_dataclasses()

       # Detecting last checkpoint.
       _a          =				None
       if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
              _a          =				get_last_checkpoint(training_args.output_dir					)
              if last_checkpoint is None and len(os.listdir(training_args.output_dir					)					) > 0:
                     raise ValueError(
                         F'Output directory ({training_args.output_dir}) already exists and is not empty. '
                         "Use --overwrite_output_dir to overcome."					)
              elif last_checkpoint is not None:
                     logger.info(
                         F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                         "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."					)

    # Setup logging
       logging.basicConfig(
           format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",		datefmt="%m/%d/%Y %H:%M:%S",		handlers=[logging.StreamHandler(sys.stdout					)],		)
       logger.setLevel(logging.INFO if is_main_process(training_args.local_rank					) else logging.WARN					)

       # Log on each process the small summary:
       logger.warning(
           F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
           + F'distributed training: {bool(training_args.local_rank != -1					)}, 16-bits training: {training_args.fpaa}'					)
       # Set the verbosity to info of the Transformers logger (on main process only):
       if is_main_process(training_args.local_rank					):
              utils.logging.set_verbosity_info()
              utils.logging.enable_default_handler()
              utils.logging.enable_explicit_format()

       if training_args.local_rank != -1:
              raise ValueError("Distributed training is not currently supported."					)
       if training_args.tpu_num_cores is not None:
              raise ValueError("TPU acceleration is not currently supported."					)

       logger.info(F'Training/evaluation parameters {training_args}'					)

       # Set seed before initializing model.
       set_seed(training_args.seed					)

       # 1. read in data
       _a          =				read_lines(data_args.data_file					)
       _a          =				read_lines(data_args.class_names_file					)

       # 2. get teacher predictions and load into dataset
       logger.info("Generating predictions from zero-shot teacher model"					)
       _a          =				get_teacher_predictions(
           teacher_args.teacher_name_or_path,		a,		a,		teacher_args.hypothesis_template,		teacher_args.teacher_batch_size,		teacher_args.temperature,		teacher_args.multi_label,		data_args.use_fast_tokenizer,		training_args.no_cuda,		training_args.fpaa,		)
       _a          =				Dataset.from_dict(
           {
               "text": examples,
               "labels": teacher_soft_preds,
           }					)

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

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

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

       _a          =				DistillationTrainer(
           model=a,		tokenizer=a,		args=a,		train_dataset=a,		compute_metrics=a,		)

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

       if training_args.do_eval:
              _a          =				trainer.evaluate(eval_dataset=a					)["eval_agreement"]
              logger.info(F'Agreement of student and teacher predictions: {agreement * 1_0_0:0.2f}%'					)

       trainer.save_model()


if __name__ == "__main__":
   main()




"""simple docstring"""




import argparse
import time

import torch
import transformers
from measures_util import end_measure, log_measures, start_measure
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoTokenizer

from accelerate.utils import compute_module_sizes


__SCREAMING_SNAKE_CASE					=						{
    """gpt-j-6b""": {"""is_causal""": True, """model""": """sgugger/sharded-gpt-j-6B""", """tokenizer""": """EleutherAI/gpt-j-6B"""},
    """gpt-neox""": {"""is_causal""": True, """model""": """EleutherAI/gpt-neox-20b"""},
    """opt""": {"""is_causal""": True, """model""": """facebook/opt-30b"""},
    """T0pp""": {"""is_causal""": False, """model""": """bigscience/T0pp""", """model_revision""": """sharded"""},
}

__SCREAMING_SNAKE_CASE					=						[
    """Hello, my name is""",
    """Are unicorns real? Unicorns are""",
    """For the first time in several years,""",
    """My name is Julien and I am""",
    """The goal of life is""",
    """Whenever I'm sad, I like to""",
]



def 						__a      (  ):





       """simple docstring"""







       _a          =				argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate."					)
       parser.add_argument("model_name",		type=a,		default=a,		help="The name of the model to try."					)
       parser.add_argument(
           "--tokenizer_name",		type=a,		default=a,		help="The name of the tokenizer (if different from the model."					)
       parser.add_argument("--is_causal",		type=a,		default=a,		help="Whether or not the model is causal."					)
       parser.add_argument(
           "--model_revision",		type=a,		default=a,		help="The revision to use for the model checkpoint."					)
       parser.add_argument("--torch_dtype",		type=a,		default=a,		help="The dtype for the model."					)
       parser.add_argument("--disk_offload",		action="store_true"					)

       _a          =				parser.parse_args()

       # Sanitize args
       if args.model_name in DEFAULT_MODELS:
              _a          =				DEFAULT_MODELS[args.model_name]
              _a          =				defaults["model"]
              if args.tokenizer_name is None:
                     _a          =				defaults.get("tokenizer",		args.model_name					)
              if args.is_causal is None:
                     _a          =				defaults["is_causal"]
              if args.model_revision is None:
                     _a          =				defaults.get("model_revision",		"main"					)

       if args.is_causal is None:
              raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it."					)
       if args.tokenizer_name is None:
              _a          =				args.model_name
       if args.model_revision is None:
              _a          =				"main"

       return args



def 						__a      (  ):





       """simple docstring"""







       transformers.utils.logging.set_verbosity_error()
       _a          =				parse_args()

       if args.torch_dtype is None:
              _a          =				AutoConfig.from_pretrained(args.model_name					)
              _a          =				getattr(a,		"torch_dtype",		torch.floataa					)
       else:
              _a          =				getattr(a,		args.torch_dtype					)
       _a          =				AutoModelForCausalLM if args.is_causal else AutoModelForSeqaSeqLM
       _a          =				{
           "torch_dtype": torch_dtype,
           "revision": args.model_revision,
       }
       if args.disk_offload:
              _a          =				"tmp_offload"
              _a          =				True

       _a          =				start_measure()
       _a          =				model_cls.from_pretrained(args.model_name,		device_map="auto",		**a					)
       _a          =				end_measure(a					)
       log_measures(a,		"Model loading"					)

       _a          =				compute_module_sizes(a					)
       _a          =				{v: 0 for v in model.hf_device_map.values()}
       for module, device in model.hf_device_map.items():
              device_size[device] += module_sizes[module]
       _a          =				"\n".join([F'- {device}: {size // 2**2_0}MiB' for device, size in device_size.items()]					)
       print(F'\nTheoretical use:\n{message}'					)

       _a          =				AutoTokenizer.from_pretrained(args.tokenizer_name					)

       _a          =				start_measure()
       _a          =				[]
       _a          =				[]
       _a          =				[]
       for prompt in PROMPTS:
              _a          =				tokenizer(a,		return_tensors="pt"					).to(0					)
              _a          =				inputs["input_ids"][0].tolist()
              _a          =				time.time()
              _a          =				model.generate(inputs["input_ids"]					)
              _a          =				time.time()
              _a          =				outputs[0].tolist()
              _a          =				len(a					) if outputs[: len(a					)] != tokens else len(a					) - len(a					)
              _a          =				after_generate - before_generate

              _a          =				tokenizer.decode(a,		skip_special_tokens=a					)
              texts_outs.append(a					)
              generation_times.append(a					)
              gen_tokens.append(a					)
              print(F'Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n'					)

       _a          =				end_measure(a					)
       log_measures(a,		"Model generation"					)

       _a          =				[gen / tok for gen, tok in zip(a,		a					)]
       _a          =				sum(a					) / len(a					)
       print(F'Average time of generation per token: {avg_gen:.2f}s'					)
       print(F'First generation (avg time per token): {generation_times_per_token[0]:.2f}s'					)
       _a          =				sum(generation_times_per_token[1:]					) / (len(a					) - 1)
       print(F'Average time of generation per token (excluding the first): {avg_gen:.2f}s'					)


if __name__ == "__main__":
   main()
