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

_SCREAMING_SNAKE_CASE	:		Tuple   =   logging.getLogger(__name__)






@dataclass
class      _SCREAMING_SNAKE_CASE							:



   '''simple docstring'''



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






@dataclass
class      _SCREAMING_SNAKE_CASE							:



   '''simple docstring'''



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






@dataclass
class      _SCREAMING_SNAKE_CASE							:



   '''simple docstring'''



   __UpperCAmelCase	:							str    =    field(metadata={"help": "Text file with one unlabeled instance per line."}				)
   __UpperCAmelCase	:							str    =    field(metadata={"help": "Text file with one class name per line."}				)
   __UpperCAmelCase	:							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      _SCREAMING_SNAKE_CASE							(			_SCREAMING_SNAKE_CASE				):



   '''simple docstring'''



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



   '''simple docstring'''



   def    _A				(	self ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE ,				_SCREAMING_SNAKE_CASE=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__    (	lowercase_     :	List[Any]						)  ->							Dict:
   __lowerCamelCase    		=					[]
   with open(lowercase_      , 'r'						) as f:
      for line in f:
         __lowerCamelCase    		=					line.strip()
         if len(lowercase_						) > 0:
            lines.append(lowercase_						)
   return lines



def       A__    (	lowercase_     :	Dict      , lowercase_     :	Tuple      , lowercase_     :	Dict						)  ->							Optional[Any]:
   __lowerCamelCase    		=					[]
   __lowerCamelCase    		=					[]
   for example in examples:
      for name in class_names:
         premises.append(lowercase_						)
         hypotheses.append(hypothesis_template.format(lowercase_						)						)
   return premises, hypotheses



def       A__    (	lowercase_     :	int						)  ->							List[str]:


   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__    (	lowercase_     :	List[Any]      , lowercase_     :	Optional[int]      , lowercase_     :	int      , lowercase_     :	str      , lowercase_     :	Optional[Any]      , lowercase_     :	int      , lowercase_     :	int      , lowercase_     :	Tuple      , lowercase_     :	int      , lowercase_     :	Dict      , )  ->							int:
   __lowerCamelCase    		=					AutoModelForSequenceClassification.from_pretrained(lowercase_						)
   __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(lowercase_      , use_fast=lowercase_						)

   __lowerCamelCase		,__lowerCamelCase    		=					get_premise_hypothesis_pairs(lowercase_      , lowercase_      , lowercase_						)
   __lowerCamelCase    		=					[]

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

      __lowerCamelCase    		=					tokenizer(
          lowercase_      , lowercase_      , padding=lowercase_      , truncation='only_first'      , return_tensors='pt'      , )

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

   __lowerCamelCase    		=					get_entailment_id(lowercase_						)
   __lowerCamelCase    		=					-1 if entail_id == 0 else 0
   __lowerCamelCase    		=					torch.cat(lowercase_      , dim=0						)  # N*K x 3
   __lowerCamelCase    		=					logits.reshape(len(lowercase_						)      , len(lowercase_						)      , -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__    (	)  ->							Optional[Any]:
   __lowerCamelCase    		=					HfArgumentParser(
       (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)      , description=lowercase_      , )

   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      , lowercase_      , lowercase_      , 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(lowercase_						)						)
   __lowerCamelCase    		=					AutoTokenizer.from_pretrained(student_args.student_name_or_path      , use_fast=data_args.use_fast_tokenizer						)
   __lowerCamelCase    		=					dict(enumerate(lowercase_						)						)
   __lowerCamelCase    		=					{label: i for i, label in enumerate(lowercase_						)}

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

   def compute_metrics(lowercase_     :	Optional[Any]      , lowercase_     :	List[Any]=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=lowercase_      , tokenizer=lowercase_      , args=lowercase_      , train_dataset=lowercase_      , compute_metrics=lowercase_      , )

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

   trainer.save_model()


if __name__ == "__main__":
     main()












import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


a_ 		=  logging.get_logger(__name__)

a_ 		=  [
    "yjernite/retribert-base-uncased",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]

class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      lowerCAmelCase__      :			Optional[Any]     =       RetriBertConfig
      lowerCAmelCase__      :			Optional[Any]     =       None
      lowerCAmelCase__      :			Dict     =       "retribert"







      def    snake_case						(  self       :			Dict			,							snake_case       :			Optional[Any]					):
          if isinstance(snake_case			,							nn.Linear					):
              module.weight.data.normal_(mean=0.0			,							std=self.config.initializer_range					)
              if module.bias is not None:
                  module.bias.data.zero_()
          elif isinstance(snake_case			,							nn.Embedding					):
              module.weight.data.normal_(mean=0.0			,							std=self.config.initializer_range					)
              if module.padding_idx is not None:
                  module.weight.data[module.padding_idx].zero_()
          elif isinstance(snake_case			,							nn.LayerNorm					):
              module.bias.data.zero_()
              module.weight.data.fill_(1.0					)







a_ 		=  R"\n\n    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads\n    etc.)\n\n    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.\n    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage\n    and behavior.\n\n    Parameters:\n        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."				,      _SCREAMING_SNAKE_CASE				,      )
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE ):

      """simple docstring"""

      def __init__(  self       :			List[Any]			,							snake_case       :			RetriBertConfig					):
          super().__init__(snake_case					)
          __UpperCamelCase			=    config.projection_dim

          __UpperCamelCase			=    BertModel(snake_case					)
          __UpperCamelCase			=    None if config.share_encoders else BertModel(snake_case					)
          __UpperCamelCase			=    nn.Dropout(config.hidden_dropout_prob					)
          __UpperCamelCase			=    nn.Linear(config.hidden_size			,							config.projection_dim			,							bias=snake_case					)
          __UpperCamelCase			=    nn.Linear(config.hidden_size			,							config.projection_dim			,							bias=snake_case					)

          __UpperCamelCase			=    nn.CrossEntropyLoss(reduction='''mean'''					)

          # Initialize weights and apply final processing
          self.post_init()







      def    snake_case						(  self       :			Dict			,							snake_case       :			Dict			,							snake_case       :			List[str]			,							snake_case       :			Dict			,							snake_case       :			Any=-1			,							):
          # reproduces BERT forward pass with checkpointing
          if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
              return sent_encoder(snake_case			,							attention_mask=snake_case					)[1]
          else:
              # prepare implicit variables
              __UpperCamelCase			=    input_ids.device
              __UpperCamelCase			=    input_ids.size()
              __UpperCamelCase			=    torch.zeros(snake_case			,							dtype=torch.long			,							device=snake_case					)
              __UpperCamelCase			=    [None] * sent_encoder.config.num_hidden_layers
              __UpperCamelCase			=    sent_encoder.get_extended_attention_mask(
                  snake_case			,							snake_case					)

              # define function for checkpointing
              def partial_encode(*snake_case       :			Optional[Any]					):
                  __UpperCamelCase			=    sent_encoder.encoder(
                      inputs[0]			,							attention_mask=inputs[1]			,							head_mask=snake_case			,							)
                  __UpperCamelCase			=    encoder_outputs[0]
                  __UpperCamelCase			=    sent_encoder.pooler(snake_case					)
                  return pooled_output

              # run embedding layer on everything at once
              __UpperCamelCase			=    sent_encoder.embeddings(
                  input_ids=snake_case			,							position_ids=snake_case			,							token_type_ids=snake_case			,							inputs_embeds=snake_case					)
              # run encoding and pooling on one mini-batch at a time
              __UpperCamelCase			=    []
              for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size					)					):
                  __UpperCamelCase			=    embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                  __UpperCamelCase			=    extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
                  __UpperCamelCase			=    checkpoint.checkpoint(snake_case			,							snake_case			,							snake_case					)
                  pooled_output_list.append(snake_case					)
              return torch.cat(snake_case			,							dim=0					)







      def    snake_case						(  self       :			Dict			,							snake_case       :			Any			,							snake_case       :			Union[str, Any]=None			,							snake_case       :			List[str]=-1			,							):
          __UpperCamelCase			=    self.embed_sentences_checkpointed(
              snake_case			,							snake_case			,							self.bert_query			,							snake_case			,							)
          return self.project_query(snake_case					)







      def    snake_case						(  self       :			Optional[Any]			,							snake_case       :			Optional[Any]			,							snake_case       :			Optional[int]=None			,							snake_case       :			Optional[Any]=-1			,							):
          __UpperCamelCase			=    self.embed_sentences_checkpointed(
              snake_case			,							snake_case			,							self.bert_query if self.bert_doc is None else self.bert_doc			,							snake_case			,							)
          return self.project_doc(snake_case					)







      def    snake_case						(  self       :			List[str]			,							snake_case       :			torch.LongTensor			,							snake_case       :			Optional[torch.FloatTensor]			,							snake_case       :			torch.LongTensor			,							snake_case       :			Optional[torch.FloatTensor]			,							snake_case       :			int = -1			,							):
          __UpperCamelCase			=    input_ids_query.device
          __UpperCamelCase			=    self.embed_questions(snake_case			,							snake_case			,							snake_case					)
          __UpperCamelCase			=    self.embed_answers(snake_case			,							snake_case			,							snake_case					)
          __UpperCamelCase			=    torch.mm(snake_case			,							a_reps.t()					)
          __UpperCamelCase			=    self.ce_loss(snake_case			,							torch.arange(compare_scores.shape[1]					).to(snake_case					)					)
          __UpperCamelCase			=    self.ce_loss(compare_scores.t()			,							torch.arange(compare_scores.shape[0]					).to(snake_case					)					)
          __UpperCamelCase			=    (loss_qa + loss_aq) / 2
          return loss






