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


UpperCamelCase      :							str          =					"\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"

UpperCamelCase      :							int          =					logging.getLogger(__name__)

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


@dataclass
class __lowerCAmelCase						:
     lowercase		  =		field(
         default="distilbert-base-uncased"     ,    metadata={"help": "The NLI/zero-shot teacher model to be distilled."}     )


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


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





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase      ,	__UpperCAmelCase=False ):

      '''simple docstring'''




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

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

      if return_outputs:
       return loss, outputs

      return loss






def 				A		(							snake_case :Optional[int]						) ->      Any:
 __UpperCamelCase							    =			[]
 with open(__UpperCamelCase							,   'r'						) as f:
  for line in f:
   __UpperCamelCase							    =			line.strip()
   if len(__UpperCamelCase						) > 0:
    lines.append(__UpperCamelCase						)
 return lines






def 				A		(							snake_case :str							,   snake_case :Any							,   snake_case :Dict						) ->      Optional[Any]:
 __UpperCamelCase							    =			[]
 __UpperCamelCase							    =			[]
 for example in examples:
  for name in class_names:
   premises.append(__UpperCamelCase						)
   hypotheses.append(hypothesis_template.format(__UpperCamelCase						)						)
 return premises, hypotheses






def 				A		(							snake_case :Union[str, Any]						) ->      List[Any]:
 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		(							snake_case :List[Any]							,   snake_case :Optional[int]							,   snake_case :Any							,   snake_case :Tuple							,   snake_case :Dict							,   snake_case :List[Any]							,   snake_case :Optional[int]							,   snake_case :Tuple							,   snake_case :int							,   snake_case :int							,   ) ->      Optional[Any]:
 __UpperCamelCase							    =			AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase						)
 __UpperCamelCase							    =			model.config
 if not no_cuda and torch.cuda.is_available():
  __UpperCamelCase							    =			nn.DataParallel(model.cuda()						)
  batch_size *= len(model.device_ids						)
 __UpperCamelCase							    =			AutoTokenizer.from_pretrained(__UpperCamelCase							,   use_fast=__UpperCamelCase						)

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

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

  __UpperCamelCase							    =			tokenizer(
      __UpperCamelCase							,   __UpperCamelCase							,   padding=__UpperCamelCase							,   truncation='only_first'							,   return_tensors='pt'							,   )

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

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

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






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

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

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

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

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

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

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

 trainer.save_model()


if __name__ == "__main__":
      main()







import unittest

from transformers import SpeechaTextaConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers.models.speech_to_text_a.modeling_speech_to_text_a import (
           SpeechaTextaDecoder,
           SpeechaTextaForCausalLM,
       )


@require_torch
class 	a__						:

       def __init__( self   :  Dict   ,				lowerCamelCase_   :  Any   ,				lowerCamelCase_   :  Dict=9_9   ,				lowerCamelCase_   :  List[Any]=1_3   ,				lowerCamelCase_   :  Dict=1_6   ,				lowerCamelCase_   :  Any=7   ,				lowerCamelCase_   :  Dict=True   ,				lowerCamelCase_   :  List[str]=True   ,				lowerCamelCase_   :  Tuple=True   ,				lowerCamelCase_   :  Any=False   ,				lowerCamelCase_   :  Union[str, Any]=True   ,				lowerCamelCase_   :  int=2   ,				lowerCamelCase_   :  Tuple=3_2   ,				lowerCamelCase_   :  int=4   ,				lowerCamelCase_   :  Dict=4   ,				lowerCamelCase_   :  str=3_0   ,				lowerCamelCase_   :  Optional[int]=0   ,				lowerCamelCase_   :  Optional[Any]=1   ,				lowerCamelCase_   :  Any=2   ,				lowerCamelCase_   :  Optional[int]=None   ,				):
            a_     :  Optional[Any]				      =     parent
            a_     :  Union[str, Any]				      =     batch_size
            a_     :  Tuple				      =     decoder_seq_length
            # For common tests
            a_     :  Union[str, Any]				      =     self.decoder_seq_length
            a_     :  List[str]				      =     is_training
            a_     :  int				      =     use_attention_mask
            a_     :  Dict				      =     use_labels

            a_     :  List[str]				      =     vocab_size
            a_     :  Optional[int]				      =     d_model
            a_     :  str				      =     d_model
            a_     :  Any				      =     decoder_layers
            a_     :  Tuple				      =     decoder_layers
            a_     :  Dict				      =     decoder_ffn_dim
            a_     :  List[str]				      =     decoder_attention_heads
            a_     :  List[Any]				      =     decoder_attention_heads
            a_     :  List[str]				      =     eos_token_id
            a_     :  Any				      =     bos_token_id
            a_     :  List[Any]				      =     pad_token_id
            a_     :  Dict				      =     decoder_start_token_id
            a_     :  Tuple				      =     use_cache
            a_     :  List[Any]				      =     max_position_embeddings

            a_     :  List[str]				      =     None
            a_     :  Any				      =     decoder_seq_length
            a_     :  List[Any]				      =     2
            a_     :  Optional[Any]				      =     1

       def     UpperCAmelCase( self   :  str     ):
            a_     :  Any				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  Any				      =     None
            if self.use_attention_mask:
                 a_     :  Optional[Any]				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				vocab_size=2     )

            a_     :  Tuple				      =     None
            if self.use_labels:
                 a_     :  int				      =     ids_tensor([self.batch_size, self.decoder_seq_length]   ,				self.vocab_size     )

            a_     :  int				      =     SpeechaTextaConfig(
                vocab_size=self.vocab_size   ,				d_model=self.d_model   ,				decoder_layers=self.decoder_layers   ,				decoder_ffn_dim=self.decoder_ffn_dim   ,				decoder_attention_heads=self.decoder_attention_heads   ,				eos_token_id=self.eos_token_id   ,				bos_token_id=self.bos_token_id   ,				use_cache=self.use_cache   ,				pad_token_id=self.pad_token_id   ,				decoder_start_token_id=self.decoder_start_token_id   ,				max_position_embeddings=self.max_position_embeddings   ,				)

            return (
                config,
                input_ids,
                attention_mask,
                lm_labels,
            )

       def     UpperCAmelCase( self   :  Tuple   ,				lowerCamelCase_   :  List[str]   ,				lowerCamelCase_   :  str   ,				lowerCamelCase_   :  Optional[int]   ,				lowerCamelCase_   :  List[str]   ,				):
            a_     :  List[Any]				      =     True
            a_     :  Optional[int]				      =     SpeechaTextaDecoder(config=lowerCamelCase_     ).to(lowerCamelCase_     ).eval()
            a_     :  Optional[int]				      =     input_ids[:2]

            input_ids[input_ids == 0] += 1
            # first forward pass
            a_     :  Union[str, Any]				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )
            a_     :  Tuple				      =     model(lowerCamelCase_     )
            a_     :  str				      =     model(lowerCamelCase_   ,				use_cache=lowerCamelCase_     )

            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     )     )
            self.parent.assertTrue(len(lowerCamelCase_     ) == len(lowerCamelCase_     ) + 1     )

            a_     :  Tuple				      =     outputs["""past_key_values"""]

            # create hypothetical next token and extent to next_input_ids
            a_     :  Any				      =     ids_tensor((2, 1)   ,				config.vocab_size - 1     ) + 1

            # append to next input_ids and
            a_     :  str				      =     torch.cat([input_ids, next_tokens]   ,				dim=-1     )

            print(lowerCamelCase_     )

            a_     :  Any				      =     model(lowerCamelCase_     )["""last_hidden_state"""]
            a_     :  int				      =     model(lowerCamelCase_   ,				past_key_values=lowerCamelCase_     )["""last_hidden_state"""]

            # select random slice
            a_     :  Tuple				      =     ids_tensor((1,)   ,				output_from_past.shape[-1]     ).item()
            a_     :  List[str]				      =     output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
            a_     :  List[Any]				      =     output_from_past[:, 0, random_slice_idx].detach()

            # test that outputs are equal for slice
            assert torch.allclose(lowerCamelCase_   ,				lowerCamelCase_   ,				atol=1E-3     )

       def     UpperCAmelCase( self   :  Any     ):
            a_     :  List[Any]				      =     self.prepare_config_and_inputs()
            (
                (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      (
                a_
            )      ,      
            )     :  Optional[int]				      =     config_and_inputs

            a_     :  Tuple				      =     {
                """input_ids""": input_ids,
                """attention_mask""": attention_mask,
            }
            return config, inputs_dict


@require_torch
class 	a__						(    lowerCAmelCase_    ,							lowerCAmelCase_    ,							lowerCAmelCase_    ,							unittest.TestCase     ):
       lowerCamelCase__:  int				     =  (SpeechaTextaDecoder, SpeechaTextaForCausalLM) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  (SpeechaTextaForCausalLM,) if is_torch_available() else ()
       lowerCamelCase__:  int				     =  {"""text-generation""": SpeechaTextaForCausalLM} if is_torch_available() else {}
       lowerCamelCase__:  Dict				     =  True
       lowerCamelCase__:  List[Any]				     =  False

       def     UpperCAmelCase( self   :  List[str]   ,				):
            a_     :  Optional[int]				      =     SpeechaTextaStandaloneDecoderModelTester(self   ,				is_training=lowerCamelCase_     )
            a_     :  str				      =     ConfigTester(self   ,				config_class=lowerCamelCase_     )

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  Optional[Any]     ):
            pass

       def     UpperCAmelCase( self   :  str     ):
            self.config_tester.run_common_tests()

       def     UpperCAmelCase( self   :  Dict     ):
            a_     :  int				      =     self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase_     )

       def     UpperCAmelCase( self   :  int     ):
            return



