




from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


lowerCamelCase_  						=       logging.get_logger(__name__)

lowerCamelCase_  						=       {
    "google/long-t5-local-base": "https://huggingface.co/google/long-t5-local-base/blob/main/config.json",
    "google/long-t5-local-large": "https://huggingface.co/google/long-t5-local-large/blob/main/config.json",
    "google/long-t5-tglobal-base": "https://huggingface.co/google/long-t5-tglobal-base/blob/main/config.json",
    "google/long-t5-tglobal-large": "https://huggingface.co/google/long-t5-tglobal-large/blob/main/config.json",
}
class 				__a (			__lowerCamelCase					):


     """simple docstring"""


     _A    :   str     =  "longt5"
     _A    :   List[Any]     =  ["past_key_values"]
     _A    :   Tuple     =  {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}




     def __init__(     self      :			int    ,_UpperCamelCase      :			Any=3_2_1_2_8    ,_UpperCamelCase      :			Optional[Any]=5_1_2    ,_UpperCamelCase      :			List[str]=6_4    ,_UpperCamelCase      :			Any=2_0_4_8    ,_UpperCamelCase      :			List[str]=6    ,_UpperCamelCase      :			List[str]=None    ,_UpperCamelCase      :			Union[str, Any]=8    ,_UpperCamelCase      :			Tuple=1_2_7    ,_UpperCamelCase      :			Dict=1_6    ,_UpperCamelCase      :			str=3_2    ,_UpperCamelCase      :			Union[str, Any]=1_2_8    ,_UpperCamelCase      :			Optional[int]=0.1    ,_UpperCamelCase      :			List[Any]=1e-6    ,_UpperCamelCase      :			List[Any]=1.0    ,_UpperCamelCase      :			str="relu"    ,_UpperCamelCase      :			Dict=True    ,_UpperCamelCase      :			Any="local"    ,_UpperCamelCase      :			Optional[int]=True    ,_UpperCamelCase      :			Any=0    ,_UpperCamelCase      :			Tuple=1    ,**_UpperCamelCase      :			List[Any]    ,)		->       Tuple:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__       =vocab_size
         SCREAMING_SNAKE_CASE__       =d_model
         SCREAMING_SNAKE_CASE__       =d_kv
         SCREAMING_SNAKE_CASE__       =d_ff
         SCREAMING_SNAKE_CASE__       =num_layers
         # default = symmetry
         SCREAMING_SNAKE_CASE__       =num_decoder_layers if num_decoder_layers is not None else self.num_layers
         SCREAMING_SNAKE_CASE__       =num_heads
         SCREAMING_SNAKE_CASE__       =local_radius
         SCREAMING_SNAKE_CASE__       =global_block_size
         SCREAMING_SNAKE_CASE__       =relative_attention_num_buckets
         SCREAMING_SNAKE_CASE__       =relative_attention_max_distance
         SCREAMING_SNAKE_CASE__       =dropout_rate
         SCREAMING_SNAKE_CASE__       =layer_norm_epsilon
         SCREAMING_SNAKE_CASE__       =initializer_factor
         SCREAMING_SNAKE_CASE__       =feed_forward_proj
         SCREAMING_SNAKE_CASE__       =encoder_attention_type
         SCREAMING_SNAKE_CASE__       =use_cache

         SCREAMING_SNAKE_CASE__       =self.feed_forward_proj.split("""-"""						)
         SCREAMING_SNAKE_CASE__       =act_info[-1]
         SCREAMING_SNAKE_CASE__       =act_info[0] == """gated"""

         if len(_UpperCamelCase						) > 1 and act_info[0] != "gated" or len(_UpperCamelCase						) > 2:
             raise ValueError(
                 f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
                 """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """
                 """'gated-gelu' or 'relu'"""						)

         # for backwards compatibility
         if feed_forward_proj == "gated-gelu":
             SCREAMING_SNAKE_CASE__       ="""gelu_new"""

         super().__init__(
             pad_token_id=_UpperCamelCase    ,eos_token_id=_UpperCamelCase    ,is_encoder_decoder=_UpperCamelCase    ,**_UpperCamelCase    ,)






class 				__a (			__lowerCamelCase					):


     """simple docstring"""


     @property
     def   __A    (     self      :			List[Any]						)		->       Mapping[str, Mapping[int, str]]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__       ={
             """input_ids""": {0: """batch""", 1: """encoder_sequence"""},
             """attention_mask""": {0: """batch""", 1: """encoder_sequence"""},
         }
         if self.use_past:
             SCREAMING_SNAKE_CASE__       ="""past_encoder_sequence + sequence"""
             SCREAMING_SNAKE_CASE__       ={0: """batch"""}
             SCREAMING_SNAKE_CASE__       ={0: """batch""", 1: """past_decoder_sequence + sequence"""}
         else:
             SCREAMING_SNAKE_CASE__       ={0: """batch""", 1: """decoder_sequence"""}
             SCREAMING_SNAKE_CASE__       ={0: """batch""", 1: """decoder_sequence"""}

         if self.use_past:
             self.fill_with_past_key_values_(_UpperCamelCase    ,direction="""inputs"""						)

         return common_inputs




     @property
     def   __A    (     self      :			Union[str, Any]						)		->       int:


         '''simple docstring'''





         return 1_3












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


lowerCamelCase_  						=       "\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"

lowerCamelCase_  						=       logging.getLogger(__name__)
@dataclass
class 				__a :


     """simple docstring"""


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






@dataclass
class 				__a :


     """simple docstring"""


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






@dataclass
class 				__a :


     """simple docstring"""


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






@dataclass
class 				__a (			__lowerCamelCase					):


     """simple docstring"""


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


     """simple docstring"""


     def   __A    (     self      :			int    ,_UpperCamelCase      :			Dict    ,_UpperCamelCase      :			Tuple    ,_UpperCamelCase      :			Optional[Any]=False						)		->       List[Any]:


         '''simple docstring'''





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

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

         if return_outputs:
             return loss, outputs

         return loss






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



def      UpperCAmelCase_   (     __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase     ):
    SCREAMING_SNAKE_CASE__       =[]
    SCREAMING_SNAKE_CASE__       =[]
    for example in examples:
        for name in class_names:
            premises.append(__UpperCamelCase     )
            hypotheses.append(hypothesis_template.format(__UpperCamelCase     )     )
    return premises, hypotheses



def      UpperCAmelCase_   (     __UpperCamelCase     ):
    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_   (     __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase,    ):
    SCREAMING_SNAKE_CASE__       =AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase     )
    SCREAMING_SNAKE_CASE__       =model.config
    if not no_cuda and torch.cuda.is_available():
        SCREAMING_SNAKE_CASE__       =nn.DataParallel(model.cuda()     )
        batch_size *= len(model.device_ids     )
    SCREAMING_SNAKE_CASE__       =AutoTokenizer.from_pretrained(__UpperCamelCase,    use_fast=__UpperCamelCase     )

    SCREAMING_SNAKE_CASE__      ,		SCREAMING_SNAKE_CASE__       =get_premise_hypothesis_pairs(__UpperCamelCase,    __UpperCamelCase,    __UpperCamelCase     )
    SCREAMING_SNAKE_CASE__       =[]

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

        SCREAMING_SNAKE_CASE__       =tokenizer(
            __UpperCamelCase,    __UpperCamelCase,    padding=__UpperCamelCase,    truncation="""only_first""",    return_tensors="""pt""",    )

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

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

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

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



def      UpperCAmelCase_   (     ):
    SCREAMING_SNAKE_CASE__       =HfArgumentParser(
        (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments),    description=__UpperCamelCase,    )

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

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

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

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

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

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

    SCREAMING_SNAKE_CASE__       =DistillationTrainer(
        model=__UpperCamelCase,    tokenizer=__UpperCamelCase,    args=__UpperCamelCase,    train_dataset=__UpperCamelCase,    compute_metrics=__UpperCamelCase,    )

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

    if training_args.do_eval:
        SCREAMING_SNAKE_CASE__       =trainer.evaluate(eval_dataset=__UpperCamelCase     )["""eval_agreement"""]
        logger.info(f"""Agreement of student and teacher predictions: {agreement * 100:0.2f}%"""     )

    trainer.save_model()


if __name__ == "__main__":
    main()






