




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


__magic_name__     :     Optional[Any]  							=					"""
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.
"""

__magic_name__     :     Dict  							=					logging.getLogger(__name__)





@dataclass
class 						SCREAMING_SNAKE_CASE__		:
     lowercase_   :			Optional[str]   =   field(
         default="roberta-large-mnli"						,				metadata={"help": "The NLI/zero-shot teacher model to be distilled."} )
     lowercase_   :			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."
             )
         }						,				)
     lowercase_   :			Optional[int]   =   field(
         default=32						,				metadata={"help": "Batch size for generating teacher predictions."} )
     lowercase_   :			Optional[bool]   =   field(
         default=_a						,				metadata={
             "help": (
                 "Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called"
                 "multi-class multi-label classification)."
             )
         }						,				)
     lowercase_   :			Optional[float]   =   field(
         default=1.0						,				metadata={"help": "Temperature applied to teacher softmax for distillation."} )





@dataclass
class 						SCREAMING_SNAKE_CASE__		:
     lowercase_   :			Optional[str]   =   field(
         default="distilbert-base-uncased"						,				metadata={"help": "The NLI/zero-shot teacher model to be distilled."} )





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





@dataclass
class 						SCREAMING_SNAKE_CASE__		(_a ):
     lowercase_   :			Optional[str]   =   field(
         default=_a						,				metadata={"help": "The output directory where the model predictions and checkpoints will be written."}						,				)
     lowercase_   :			int   =   field(
         default=32						,				metadata={"help": "Batch size per GPU/TPU core/CPU for training."} )
     lowercase_   :			int   =   field(
         default=128						,				metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."} )
     lowercase_   :			float   =   field(default=1.0						,				metadata={"help": "Total number of training epochs to perform."} )
     lowercase_   :			bool   =   field(default=_a						,				metadata={"help": "Whether to run training of student model."} )
     lowercase_   :			bool   =   field(
         default=_a						,				metadata={
             "help": (
                 "Whether to evaluate the agreement of the final student predictions and the teacher predictions"
                 "after training."
             )
         }						,				)
     lowercase_   :			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__		(_a ):
     def 					A__			(	self  :		List[Any]					,	__lowerCamelCase  :		List[Any]					,	__lowerCamelCase  :		Any					,	__lowerCamelCase  :		int=False	):



       """simple docstring"""
       lowerCAmelCase__								=			inputs['''labels''']
       lowerCAmelCase__								=			model(inputs['''input_ids''']					,	attention_mask=inputs['''attention_mask''']	)
       lowerCAmelCase__								=			outputs[0]

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

       if return_outputs:
         return loss, outputs

       return loss



def 		a_       (   __lowerCAmelCase							):
  lowerCAmelCase__								=			[]
  with open(__lowerCAmelCase      ,   '''r'''							) as f:
    for line in f:
      lowerCAmelCase__								=			line.strip()
      if len(__lowerCAmelCase							) > 0:
        lines.append(__lowerCAmelCase							)
  return lines
def 		a_       (   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase							):
  lowerCAmelCase__								=			[]
  lowerCAmelCase__								=			[]
  for example in examples:
    for name in class_names:
      premises.append(__lowerCAmelCase							)
      hypotheses.append(hypothesis_template.format(__lowerCAmelCase							)							)
  return premises, hypotheses
def 		a_       (   __lowerCAmelCase							):
  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_       (   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   __lowerCAmelCase      ,   ):
  lowerCAmelCase__								=			AutoModelForSequenceClassification.from_pretrained(__lowerCAmelCase							)
  lowerCAmelCase__								=			model.config
  if not no_cuda and torch.cuda.is_available():
    lowerCAmelCase__								=			nn.DataParallel(model.cuda()							)
    batch_size *= len(model.device_ids							)
  lowerCAmelCase__								=			AutoTokenizer.from_pretrained(__lowerCAmelCase      ,   use_fast=__lowerCAmelCase							)

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

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

    lowerCAmelCase__								=			tokenizer(
        __lowerCAmelCase      ,   __lowerCAmelCase      ,   padding=__lowerCAmelCase      ,   truncation='''only_first'''      ,   return_tensors='''pt'''      ,   )

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

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

  return nli_prob[..., 1]  # N x K
def 		a_       (   ):
  lowerCAmelCase__								=			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.
    lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__								=			parser.parse_json_file(
        json_file=os.path.abspath(sys.argv[1]							)							)
  else:
    lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__							,			lowerCAmelCase__								=			parser.parse_args_into_dataclasses()

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

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

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

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

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

  lowerCAmelCase__								=			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:
    lowerCAmelCase__								=			trainer.evaluate(eval_dataset=__lowerCAmelCase							)['''eval_agreement''']
    logger.info(F"""Agreement of student and teacher predictions: {agreement * 1_00:0.2f}%"""							)

  trainer.save_model()


if __name__ == "__main__":
      main()







import json

import requests

from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def 		a_       (   __lowerCAmelCase							):





  class 						SCREAMING_SNAKE_CASE__		:
       def __init__(	self  :		List[str]					,	__lowerCamelCase  :		Any	):



         """simple docstring"""
         assert isinstance(__lowerCamelCase					,	(bytes, str)	)
         lowerCAmelCase__								=			content



       def 					A__			(	self  :		int	):



         """simple docstring"""
         return json.loads(self.content	)

  def mock_response(*__lowerCAmelCase      ,   **__lowerCAmelCase							):
    assert args[0] == AUTHENTICATED_USER_ENDPOINT
    assert "Authorization" in kwargs["headers"]
    assert kwargs["headers"]["Authorization"].startswith('''token '''							)
    assert "Accept" in kwargs["headers"]
    return FakeResponse(B'''{"login":"test","id":1}'''							)

  monkeypatch.setattr(__lowerCAmelCase      ,   '''get'''      ,   __lowerCAmelCase							)
  lowerCAmelCase__								=			fetch_github_info('''token'''							)
  assert result["login"] == "test"
  assert result["id"] == 1

