





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       : Union[str, 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"

__A       : str						    = logging.getLogger(__name__)







@dataclass
class     lowerCamelCase:
     '''simple docstring'''


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







@dataclass
class     lowerCamelCase:
     '''simple docstring'''


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







@dataclass
class     lowerCamelCase:
     '''simple docstring'''


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







@dataclass
class     lowerCamelCase(	__snake_case  ):
     '''simple docstring'''


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


     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_							,    snake_case_=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 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE							)       ->   Union[str, Any]:




    """simple docstring"""




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





def 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)       ->   Any:




    """simple docstring"""




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





def 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE							)       ->   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 							__lowerCAmelCase(					_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    )       ->   int:




    """simple docstring"""




    _A    =       AutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE							)
    _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(_SCREAMING_SNAKE_CASE       ,    use_fast=_SCREAMING_SNAKE_CASE							)

    _A, _A    =       get_premise_hypothesis_pairs(_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE							)
    _A    =       []

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

        _A    =       tokenizer(
            _SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE       ,    padding=_SCREAMING_SNAKE_CASE       ,    truncation='only_first'       ,    return_tensors='pt'       ,    )

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

    _A    =       get_entailment_id(_SCREAMING_SNAKE_CASE							)
    _A    =       -1 if entail_id == 0 else 0
    _A    =       torch.cat(_SCREAMING_SNAKE_CASE       ,    dim=0							)  # N*K x 3
    _A    =       logits.reshape(len(_SCREAMING_SNAKE_CASE							)       ,    len(_SCREAMING_SNAKE_CASE							)       ,    -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 							__lowerCAmelCase(					)       ->   List[Any]:




    """simple docstring"""




    _A    =       HfArgumentParser(
        (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)       ,    description=_SCREAMING_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.
        _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       ,    _SCREAMING_SNAKE_CASE       ,    _SCREAMING_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       ,    )
    _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(_SCREAMING_SNAKE_CASE							)							)
    _A    =       AutoTokenizer.from_pretrained(student_args.student_name_or_path       ,    use_fast=data_args.use_fast_tokenizer							)
    _A    =       dict(enumerate(_SCREAMING_SNAKE_CASE							)							)
    _A    =       {label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE							)}

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

    def compute_metrics(_SCREAMING_SNAKE_CASE       ,    _SCREAMING_SNAKE_CASE=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=_SCREAMING_SNAKE_CASE       ,    tokenizer=_SCREAMING_SNAKE_CASE       ,    args=_SCREAMING_SNAKE_CASE       ,    train_dataset=_SCREAMING_SNAKE_CASE       ,    compute_metrics=_SCREAMING_SNAKE_CASE       ,    )

    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=_SCREAMING_SNAKE_CASE							)['eval_agreement']
        logger.info(F"Agreement of student and teacher predictions: {agreement * 100:0.2f}%"							)

    trainer.save_model()


if __name__ == "__main__":
 main()










import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


__A       : Optional[int]						    = logging.get_logger(__name__)







@dataclass
class     lowerCamelCase:
     '''simple docstring'''


     __magic_name__        = 42
     __magic_name__        = 42
     __magic_name__        = None
     __magic_name__        = None




     def 					lowerCAmelCase__		(						self       ):
         return json.dumps(dataclasses.asdict(self       )							,    indent=2       ) + "\n"







@dataclass(frozen=__snake_case  )
class     lowerCamelCase:
     '''simple docstring'''


     __magic_name__        = 42
     __magic_name__        = None
     __magic_name__        = None
     __magic_name__        = None




     def 					lowerCAmelCase__		(						self       ):
         return json.dumps(dataclasses.asdict(self       )       ) + "\n"







class     lowerCamelCase:
     '''simple docstring'''


     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         raise NotImplementedError()




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         raise NotImplementedError()




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         raise NotImplementedError()




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         raise NotImplementedError()




     def 					lowerCAmelCase__		(						self       ):
         raise NotImplementedError()




     def 					lowerCAmelCase__		(						self							,    snake_case_       ):
         if len(self.get_labels()       ) > 1:
             _A    =       self.get_labels()[int(example.label       )]
         return example




     @classmethod
     def 					lowerCAmelCase__		(						cls							,    snake_case_							,    snake_case_=None       ):
         with open(snake_case_							,    'r'							,    encoding='utf-8-sig'       ) as f:
             return list(csv.reader(snake_case_							,    delimiter='\t'							,    quotechar=snake_case_       )       )







class     lowerCamelCase(	__snake_case  ):
     '''simple docstring'''


     def __init__(						self							,    snake_case_=None							,    snake_case_=None							,    snake_case_="classification"							,    snake_case_=False       ):
         _A    =       [] if labels is None else labels
         _A    =       [] if examples is None else examples
         _A    =       mode
         _A    =       verbose




     def __len__(						self       ):
         return len(self.examples       )




     def __getitem__(						self							,    snake_case_       ):
         if isinstance(snake_case_							,    snake_case_       ):
             return SingleSentenceClassificationProcessor(labels=self.labels							,    examples=self.examples[idx]       )
         return self.examples[idx]




     @classmethod
     def 					lowerCAmelCase__		(						cls							,    snake_case_							,    snake_case_=""							,    snake_case_=0							,    snake_case_=1							,    snake_case_=None							,    snake_case_=False							,    **snake_case_       ):
         _A    =       cls(**snake_case_       )
         processor.add_examples_from_csv(
             snake_case_							,    split_name=snake_case_							,    column_label=snake_case_							,    column_text=snake_case_							,    column_id=snake_case_							,    skip_first_row=snake_case_							,    overwrite_labels=snake_case_							,    overwrite_examples=snake_case_							,    )
         return processor




     @classmethod
     def 					lowerCAmelCase__		(						cls							,    snake_case_							,    snake_case_=None							,    **snake_case_       ):
         _A    =       cls(**snake_case_       )
         processor.add_examples(snake_case_							,    labels=snake_case_       )
         return processor




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_=""							,    snake_case_=0							,    snake_case_=1							,    snake_case_=None							,    snake_case_=False							,    snake_case_=False							,    snake_case_=False							,    ):
         _A    =       self._read_tsv(snake_case_       )
         if skip_first_row:
             _A    =       lines[1:]
         _A    =       []
         _A    =       []
         _A    =       []
         for i, line in enumerate(snake_case_       ):
             texts.append(line[column_text]       )
             labels.append(line[column_label]       )
             if column_id is not None:
                 ids.append(line[column_id]       )
             else:
                 _A    =       F"{split_name}-{i}" if split_name else str(snake_case_       )
                 ids.append(snake_case_       )

         return self.add_examples(
             snake_case_							,    snake_case_							,    snake_case_							,    overwrite_labels=snake_case_							,    overwrite_examples=snake_case_       )




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_=None							,    snake_case_=None							,    snake_case_=False							,    snake_case_=False       ):
         if labels is not None and len(snake_case_       ) != len(snake_case_       ):
             raise ValueError(
                 F"Text and labels have mismatched lengths {len(snake_case_       )} and {len(snake_case_       )}"       )
         if ids is not None and len(snake_case_       ) != len(snake_case_       ):
             raise ValueError(F"Text and ids have mismatched lengths {len(snake_case_       )} and {len(snake_case_       )}"       )
         if ids is None:
             _A    =       [None] * len(snake_case_       )
         if labels is None:
             _A    =       [None] * len(snake_case_       )
         _A    =       []
         _A    =       set()
         for text_or_text_and_label, label, guid in zip(snake_case_							,    snake_case_							,    snake_case_       ):
             if isinstance(snake_case_							,    (tuple, list)       ) and label is None:
                 _A, _A    =       text_or_text_and_label
             else:
                 _A    =       text_or_text_and_label
             added_labels.add(snake_case_       )
             examples.append(InputExample(guid=snake_case_							,    text_a=snake_case_							,    text_b=snake_case_							,    label=snake_case_       )       )

         # Update examples
         if overwrite_examples:
             _A    =       examples
         else:
             self.examples.extend(snake_case_       )

         # Update labels
         if overwrite_labels:
             _A    =       list(snake_case_       )
         else:
             _A    =       list(set(self.labels       ).union(snake_case_       )       )

         return self.examples




     def 					lowerCAmelCase__		(						self							,    snake_case_							,    snake_case_=None							,    snake_case_=False							,    snake_case_=0							,    snake_case_=True							,    snake_case_=None							,    ):
         if max_length is None:
             _A    =       tokenizer.max_len

         _A    =       {label: i for i, label in enumerate(self.labels       )}

         _A    =       []
         for ex_index, example in enumerate(self.examples       ):
             if ex_index % 1_0000 == 0:
                 logger.info(F"Tokenizing example {ex_index}"       )

             _A    =       tokenizer.encode(
                 example.text_a							,    add_special_tokens=snake_case_							,    max_length=min(snake_case_							,    tokenizer.max_len       )							,    )
             all_input_ids.append(snake_case_       )

         _A    =       max(len(snake_case_       ) for input_ids in all_input_ids       )

         _A    =       []
         for ex_index, (input_ids, example) in enumerate(zip(snake_case_							,    self.examples       )       ):
             if ex_index % 1_0000 == 0:
                 logger.info(F"Writing example {ex_index}/{len(self.examples       )}"       )
             # The mask has 1 for real tokens and 0 for padding tokens. Only real
             # tokens are attended to.
             _A    =       [1 if mask_padding_with_zero else 0] * len(snake_case_       )

             # Zero-pad up to the sequence length.
             _A    =       batch_length - len(snake_case_       )
             if pad_on_left:
                 _A    =       ([pad_token] * padding_length) + input_ids
                 _A    =       ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
             else:
                 _A    =       input_ids + ([pad_token] * padding_length)
                 _A    =       attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

             if len(snake_case_       ) != batch_length:
                 raise ValueError(F"Error with input length {len(snake_case_       )} vs {batch_length}"       )
             if len(snake_case_       ) != batch_length:
                 raise ValueError(F"Error with input length {len(snake_case_       )} vs {batch_length}"       )

             if self.mode == "classification":
                 _A    =       label_map[example.label]
             elif self.mode == "regression":
                 _A    =       float(example.label       )
             else:
                 raise ValueError(self.mode       )

             if ex_index < 5 and self.verbose:
                 logger.info('*** Example ***'       )
                 logger.info(F"guid: {example.guid}"       )
                 logger.info(F"input_ids: {' '.join([str(snake_case_       ) for x in input_ids]       )}"       )
                 logger.info(F"attention_mask: {' '.join([str(snake_case_       ) for x in attention_mask]       )}"       )
                 logger.info(F"label: {example.label} (id = {label})"       )

             features.append(InputFeatures(input_ids=snake_case_							,    attention_mask=snake_case_							,    label=snake_case_       )       )

         if return_tensors is None:
             return features
         elif return_tensors == "tf":
             if not is_tf_available():
                 raise RuntimeError('return_tensors set to \'tf\' but TensorFlow 2.0 can\'t be imported'       )
             import tensorflow as tf

             def gen():
                 for ex in features:
                     yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

             _A    =       tf.data.Dataset.from_generator(
                 snake_case_							,    ({'input_ids': tf.intaa, 'attention_mask': tf.intaa}, tf.intaa)							,    ({'input_ids': tf.TensorShape([None]       ), 'attention_mask': tf.TensorShape([None]       )}, tf.TensorShape([]       ))							,    )
             return dataset
         elif return_tensors == "pt":
             if not is_torch_available():
                 raise RuntimeError('return_tensors set to \'pt\' but PyTorch can\'t be imported'       )
             import torch
             from torch.utils.data import TensorDataset

             _A    =       torch.tensor([f.input_ids for f in features]							,    dtype=torch.long       )
             _A    =       torch.tensor([f.attention_mask for f in features]							,    dtype=torch.long       )
             if self.mode == "classification":
                 _A    =       torch.tensor([f.label for f in features]							,    dtype=torch.long       )
             elif self.mode == "regression":
                 _A    =       torch.tensor([f.label for f in features]							,    dtype=torch.float       )

             _A    =       TensorDataset(snake_case_							,    snake_case_							,    snake_case_       )
             return dataset
         else:
             raise ValueError('return_tensors should be one of \'tf\' or \'pt\''       )





