


import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor


if is_torch_available():
     import torch
     from torch import nn

     from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
     from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from transformers import VivitImageProcessor



class 							lowercase__:






      '''simple docstring'''







      def __init__(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE=2   ,			__SCREAMING_SNAKE_CASE=True   ,			__SCREAMING_SNAKE_CASE=True   ,			__SCREAMING_SNAKE_CASE=10   ,			__SCREAMING_SNAKE_CASE=10   ,			__SCREAMING_SNAKE_CASE=8   ,			__SCREAMING_SNAKE_CASE=[2, 4, 4]   ,			__SCREAMING_SNAKE_CASE=3   ,			__SCREAMING_SNAKE_CASE=7_68   ,			__SCREAMING_SNAKE_CASE=5   ,			__SCREAMING_SNAKE_CASE=4   ,			__SCREAMING_SNAKE_CASE=37   ,			__SCREAMING_SNAKE_CASE="gelu_fast"   ,			__SCREAMING_SNAKE_CASE=0.0   ,			__SCREAMING_SNAKE_CASE=0.0   ,			__SCREAMING_SNAKE_CASE=0.02   ,			__SCREAMING_SNAKE_CASE=1E-06   ,			__SCREAMING_SNAKE_CASE=True   ,			__SCREAMING_SNAKE_CASE=None   ,			)					->						Union[str, Any]:







         """simple docstring"""







         UpperCamelCase__ :			int 						=parent
         UpperCamelCase__ :			List[str] 						=batch_size
         UpperCamelCase__ :			Any 						=is_training
         UpperCamelCase__ :			Optional[int] 						=use_labels
         UpperCamelCase__ :			Tuple 						=num_labels
         UpperCamelCase__ :			Tuple 						=image_size
         UpperCamelCase__ :			str 						=num_frames
         UpperCamelCase__ :			Any 						=tubelet_size
         UpperCamelCase__ :			Optional[Any] 						=num_channels
         UpperCamelCase__ :			List[Any] 						=hidden_size
         UpperCamelCase__ :			Any 						=num_hidden_layers
         UpperCamelCase__ :			Any 						=num_attention_heads
         UpperCamelCase__ :			Dict 						=intermediate_size
         UpperCamelCase__ :			Any 						=hidden_act
         UpperCamelCase__ :			Any 						=hidden_dropout_prob
         UpperCamelCase__ :			Optional[int] 						=attention_probs_dropout_prob
         UpperCamelCase__ :			Optional[Any] 						=initializer_range
         UpperCamelCase__ :			Tuple 						=layer_norm_eps
         UpperCamelCase__ :			Tuple 						=qkv_bias
         UpperCamelCase__ :			Optional[Any] 						=scope

         UpperCamelCase__ :			List[Any] 						=(
             (self.image_size // self.tubelet_size[2])
             * (self.image_size // self.tubelet_size[1])
             * (self.num_frames // self.tubelet_size[0])
         ) + 1  # CLS token




      def    UpperCAmelCase							(		self)					->						List[str]:







         """simple docstring"""







         UpperCamelCase__ :			Optional[int] 						=floats_tensor(
             [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size])

         UpperCamelCase__ :			List[str] 						=None
         if self.use_labels:
            UpperCamelCase__ :			int 						=ids_tensor([self.batch_size]   ,			self.num_labels)

         UpperCamelCase__ :			Any 						=self.get_config()

         return config, pixel_values, labels




      def    UpperCAmelCase							(		self)					->						Optional[int]:







         """simple docstring"""







         UpperCamelCase__ :			Optional[int] 						=VivitConfig(
             num_frames=self.num_frames   ,			image_size=self.image_size   ,			tubelet_size=self.tubelet_size   ,			num_channels=self.num_channels   ,			hidden_size=self.hidden_size   ,			num_hidden_layers=self.num_hidden_layers   ,			num_attention_heads=self.num_attention_heads   ,			intermediate_size=self.intermediate_size   ,			hidden_act=self.hidden_act   ,			hidden_dropout_prob=self.hidden_dropout_prob   ,			attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,			initializer_range=self.initializer_range   ,			layer_norm_eps=self.layer_norm_eps   ,			qkv_bias=self.qkv_bias   ,			)
         UpperCamelCase__ :			int 						=self.num_labels
         return config




      def    UpperCAmelCase							(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE)					->						str:







         """simple docstring"""







         UpperCamelCase__ :			List[Any] 						=VivitModel(config=__SCREAMING_SNAKE_CASE)
         model.to(__SCREAMING_SNAKE_CASE)
         model.eval()
         UpperCamelCase__ :			int 						=model(__SCREAMING_SNAKE_CASE)
         self.parent.assertEqual(result.last_hidden_state.shape   ,			(self.batch_size, self.seq_length, self.hidden_size))




      def    UpperCAmelCase							(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE)					->						Any:







         """simple docstring"""







         UpperCamelCase__ :			Union[str, Any] 						=VivitForVideoClassification(__SCREAMING_SNAKE_CASE)
         model.to(__SCREAMING_SNAKE_CASE)
         model.eval()

         UpperCamelCase__ :			Dict 						=model(__SCREAMING_SNAKE_CASE)

         # verify the logits shape
         UpperCamelCase__ :			Optional[int] 						=torch.Size((self.batch_size, self.num_labels))
         self.parent.assertEqual(result.logits.shape   ,			__SCREAMING_SNAKE_CASE)




      def    UpperCAmelCase							(		self)					->						List[str]:







         """simple docstring"""







         UpperCamelCase__ :			str 						=self.prepare_config_and_inputs()
         UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ :			str 						=config_and_inputs
         UpperCamelCase__ :			Optional[Any] 						={"pixel_values": pixel_values}
         return config, inputs_dict




@require_torch
class 							lowercase__(						snake_case__			,							unittest.TestCase			):






      '''simple docstring'''







      snake_case__       =					(VivitModel, VivitForVideoClassification) if is_torch_available() else ()

      snake_case__       =					False
      snake_case__       =					False
      snake_case__       =					False
      snake_case__       =					False




      def    UpperCAmelCase							(		self)					->						str:







         """simple docstring"""







         UpperCamelCase__ :			int 						=VivitModelTester(self)
         UpperCamelCase__ :			List[str] 						=ConfigTester(self   ,			config_class=__SCREAMING_SNAKE_CASE   ,			has_text_modality=__SCREAMING_SNAKE_CASE   ,			hidden_size=37)




      def    UpperCAmelCase							(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE=False)					->						List[Any]:







         """simple docstring"""







         UpperCamelCase__ :			Any 						=copy.deepcopy(__SCREAMING_SNAKE_CASE)

         if return_labels:
            if model_class in get_values(__SCREAMING_SNAKE_CASE):
               UpperCamelCase__ :			Any 						=torch.zeros(
                   self.model_tester.batch_size   ,			dtype=torch.long   ,			device=__SCREAMING_SNAKE_CASE)

         return inputs_dict




      def    UpperCAmelCase							(		self)					->						Dict:







         """simple docstring"""







         self.config_tester.run_common_tests()




      @unittest.skip(reason="Vivit does not use inputs_embeds")
      def    UpperCAmelCase							(		self)					->						Optional[Any]:







         """simple docstring"""







         pass




      def    UpperCAmelCase							(		self)					->						Optional[Any]:







         """simple docstring"""







         UpperCamelCase__						,	UpperCamelCase__ :			Optional[Any] 						=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCamelCase__ :			List[Any] 						=model_class(__SCREAMING_SNAKE_CASE)
            self.assertIsInstance(model.get_input_embeddings()   ,			(nn.Module))
            UpperCamelCase__ :			List[str] 						=model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE   ,			nn.Linear))




      def    UpperCAmelCase							(		self)					->						str:







         """simple docstring"""







         UpperCamelCase__						,	UpperCamelCase__ :			List[str] 						=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCamelCase__ :			int 						=model_class(__SCREAMING_SNAKE_CASE)
            UpperCamelCase__ :			Dict 						=inspect.signature(model.forward)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCamelCase__ :			Optional[Any] 						=[*signature.parameters.keys()]

            UpperCamelCase__ :			Tuple 						=["pixel_values", "head_mask"]
            self.assertListEqual(arg_names[:2]   ,			__SCREAMING_SNAKE_CASE)




      def    UpperCAmelCase							(		self)					->						List[Any]:







         """simple docstring"""







         UpperCamelCase__ :			Optional[Any] 						=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE)




      def    UpperCAmelCase							(		self)					->						Optional[Any]:







         """simple docstring"""







         UpperCamelCase__ :			Dict 						=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_video_classification(*__SCREAMING_SNAKE_CASE)




      @slow
      def    UpperCAmelCase							(		self)					->						Tuple:







         """simple docstring"""







         for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCamelCase__ :			Optional[Any] 						=VivitModel.from_pretrained(__SCREAMING_SNAKE_CASE)
            self.assertIsNotNone(__SCREAMING_SNAKE_CASE)




      def    UpperCAmelCase							(		self)					->						List[Any]:







         """simple docstring"""







         UpperCamelCase__						,	UpperCamelCase__ :			Any 						=self.model_tester.prepare_config_and_inputs_for_common()
         UpperCamelCase__ :			Any 						=True

         for model_class in self.all_model_classes:
            UpperCamelCase__ :			str 						=self.model_tester.seq_length

            UpperCamelCase__ :			List[Any] 						=True
            UpperCamelCase__ :			Dict 						=False
            UpperCamelCase__ :			List[str] 						=True
            UpperCamelCase__ :			Union[str, Any] 						=model_class(__SCREAMING_SNAKE_CASE)
            model.to(__SCREAMING_SNAKE_CASE)
            model.eval()
            with torch.no_grad():
               UpperCamelCase__ :			str 						=model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE))
            UpperCamelCase__ :			Dict 						=outputs.attentions
            self.assertEqual(len(__SCREAMING_SNAKE_CASE)   ,			self.model_tester.num_hidden_layers)

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            UpperCamelCase__ :			Optional[int] 						=True
            UpperCamelCase__ :			Tuple 						=model_class(__SCREAMING_SNAKE_CASE)
            model.to(__SCREAMING_SNAKE_CASE)
            model.eval()
            with torch.no_grad():
               UpperCamelCase__ :			str 						=model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE))
            UpperCamelCase__ :			Dict 						=outputs.attentions
            self.assertEqual(len(__SCREAMING_SNAKE_CASE)   ,			self.model_tester.num_hidden_layers)

            self.assertListEqual(
                list(attentions[0].shape[-3:])   ,			[self.model_tester.num_attention_heads, seq_len, seq_len]   ,			)
            UpperCamelCase__ :			Optional[int] 						=len(__SCREAMING_SNAKE_CASE)

            # Check attention is always last and order is fine
            UpperCamelCase__ :			Optional[Any] 						=True
            UpperCamelCase__ :			Optional[Any] 						=True
            UpperCamelCase__ :			Optional[Any] 						=model_class(__SCREAMING_SNAKE_CASE)
            model.to(__SCREAMING_SNAKE_CASE)
            model.eval()
            with torch.no_grad():
               UpperCamelCase__ :			Optional[Any] 						=model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE))

            self.assertEqual(out_len + 1   ,			len(__SCREAMING_SNAKE_CASE))

            UpperCamelCase__ :			List[str] 						=outputs.attentions

            self.assertEqual(len(__SCREAMING_SNAKE_CASE)   ,			self.model_tester.num_hidden_layers)

            self.assertListEqual(
                list(self_attentions[0].shape[-3:])   ,			[self.model_tester.num_attention_heads, seq_len, seq_len]   ,			)




      def    UpperCAmelCase							(		self)					->						str:







         """simple docstring"""







         def check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE):
            UpperCamelCase__ :			Optional[Any] 						=model_class(__SCREAMING_SNAKE_CASE)
            model.to(__SCREAMING_SNAKE_CASE)
            model.eval()

            with torch.no_grad():
               UpperCamelCase__ :			Union[str, Any] 						=model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE))

            UpperCamelCase__ :			List[str] 						=outputs.hidden_states
            UpperCamelCase__ :			Union[str, Any] 						=self.model_tester.num_hidden_layers + 1
            self.assertEqual(len(__SCREAMING_SNAKE_CASE)   ,			__SCREAMING_SNAKE_CASE)

            UpperCamelCase__ :			List[str] 						=self.model_tester.seq_length

            self.assertListEqual(
                list(hidden_states[0].shape[-2:])   ,			[seq_length, self.model_tester.hidden_size]   ,			)

         UpperCamelCase__						,	UpperCamelCase__ :			Dict 						=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCamelCase__ :			Optional[Any] 						=True
            check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            UpperCamelCase__ :			Optional[int] 						=True

            check_hidden_states_output(__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE)




      @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
      def    UpperCAmelCase							(		self)					->						List[str]:







         """simple docstring"""







         pass




def 	_lowerCamelCase  (		)			->			Optional[int]:

   '''simple docstring'''






   UpperCamelCase__ :			Tuple 						=hf_hub_download(
       repo_id="hf-internal-testing/spaghetti-video"							,  filename="eating_spaghetti_32_frames.npy"							,  repo_type="dataset"      )
   UpperCamelCase__ :			List[Any] 						=np.load(A_      )
   return list(A_      )



@require_torch
@require_vision
class 							lowercase__(						unittest.TestCase			):






      '''simple docstring'''







      @cached_property
      def    UpperCAmelCase							(		self)					->						Any:







         """simple docstring"""







         return VivitImageProcessor() if is_vision_available() else None




      @slow
      def    UpperCAmelCase							(		self)					->						Optional[int]:







         """simple docstring"""







         UpperCamelCase__ :			Dict 						=VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400").to(__SCREAMING_SNAKE_CASE)

         UpperCamelCase__ :			Union[str, Any] 						=self.default_image_processor
         UpperCamelCase__ :			List[Any] 						=prepare_video()
         UpperCamelCase__ :			int 						=image_processor(__SCREAMING_SNAKE_CASE   ,			return_tensors="pt").to(__SCREAMING_SNAKE_CASE)

         # forward pass
         with torch.no_grad():
            UpperCamelCase__ :			List[Any] 						=model(**__SCREAMING_SNAKE_CASE)

         # verify the logits
         UpperCamelCase__ :			Any 						=torch.Size((1, 4_00))
         self.assertEqual(outputs.logits.shape   ,			__SCREAMING_SNAKE_CASE)

         # taken from original model
         UpperCamelCase__ :			int 						=torch.tensor([-1.05_43, 2.07_64, -0.21_04, 0.44_39, -0.96_58]).to(__SCREAMING_SNAKE_CASE)

         self.assertTrue(torch.allclose(outputs.logits[0, :5]   ,			__SCREAMING_SNAKE_CASE   ,			atol=1E-4))





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

__UpperCAmelCase      			=  logging.getLogger(__name__)



@dataclass
class 							lowercase__:






      '''simple docstring'''







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




@dataclass
class 							lowercase__:






      '''simple docstring'''







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




@dataclass
class 							lowercase__:






      '''simple docstring'''







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




@dataclass
class 							lowercase__(						snake_case__			):






      '''simple docstring'''







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






      '''simple docstring'''







      def    UpperCAmelCase							(		self   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE   ,			__SCREAMING_SNAKE_CASE=False)					->						int:







         """simple docstring"""







         UpperCamelCase__ :			str 						=inputs["labels"]
         UpperCamelCase__ :			List[Any] 						=model(inputs["input_ids"]   ,			attention_mask=inputs["attention_mask"])
         UpperCamelCase__ :			List[str] 						=outputs[0]

         UpperCamelCase__ :			Optional[Any] 						=-torch.sum(target_p * logits.log_softmax(dim=-1)   ,			axis=-1).mean()

         if return_outputs:
            return loss, outputs

         return loss




def 	_lowerCamelCase  (		A_  :	List[Any]      )			->			List[Any]:

   '''simple docstring'''






   UpperCamelCase__ :			int 						=[]
   with open(A_							,  "r"      ) as f:
      for line in f:
         UpperCamelCase__ :			Any 						=line.strip()
         if len(A_      ) > 0:
            lines.append(A_      )
   return lines
def 	_lowerCamelCase  (		A_  :	Tuple							,  A_  :	Dict							,  A_  :	Tuple      )			->			Tuple:

   '''simple docstring'''






   UpperCamelCase__ :			Optional[int] 						=[]
   UpperCamelCase__ :			List[str] 						=[]
   for example in examples:
      for name in class_names:
         premises.append(A_      )
         hypotheses.append(hypothesis_template.format(A_      )      )
   return premises, hypotheses
def 	_lowerCamelCase  (		A_  :	int      )			->			Optional[Any]:

   '''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  (		A_  :	str							,  A_  :	List[str]							,  A_  :	List[str]							,  A_  :	str							,  A_  :	int							,  A_  :	float							,  A_  :	bool							,  A_  :	bool							,  A_  :	bool							,  A_  :	bool							,  )			->			Tuple:

   '''simple docstring'''






   UpperCamelCase__ :			Any 						=AutoModelForSequenceClassification.from_pretrained(A_      )
   UpperCamelCase__ :			Any 						=model.config
   if not no_cuda and torch.cuda.is_available():
      UpperCamelCase__ :			Union[str, Any] 						=nn.DataParallel(model.cuda()      )
      batch_size *= len(model.device_ids      )
   UpperCamelCase__ :			Dict 						=AutoTokenizer.from_pretrained(A_							,  use_fast=A_      )

   UpperCamelCase__						,	UpperCamelCase__ :			Any 						=get_premise_hypothesis_pairs(A_							,  A_							,  A_      )
   UpperCamelCase__ :			Union[str, Any] 						=[]

   for i in tqdm(range(0							,  len(A_      )							,  A_      )      ):
      UpperCamelCase__ :			Any 						=premises[i : i + batch_size]
      UpperCamelCase__ :			Optional[int] 						=hypotheses[i : i + batch_size]

      UpperCamelCase__ :			Tuple 						=tokenizer(
          A_							,  A_							,  padding=A_							,  truncation="only_first"							,  return_tensors="pt"							,  )

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

   UpperCamelCase__ :			Any 						=get_entailment_id(A_      )
   UpperCamelCase__ :			Union[str, Any] 						=-1 if entail_id == 0 else 0
   UpperCamelCase__ :			Optional[int] 						=torch.cat(A_							,  dim=0      )  # N*K x 3
   UpperCamelCase__ :			List[Any] 						=logits.reshape(len(A_      )							,  len(A_      )							,  -1      )[..., [contr_id, entail_id]]  # N x K x 2

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

   return nli_prob[..., 1]  # N x K
def 	_lowerCamelCase  (		)			->			Any:

   '''simple docstring'''






   UpperCamelCase__ :			Optional[Any] 						=HfArgumentParser(
       (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)							,  description=A_							,  )

   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__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ :			Union[str, Any] 						=parser.parse_json_file(
          json_file=os.path.abspath(sys.argv[1]      )      )
   else:
      UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__ :			Optional[Any] 						=parser.parse_args_into_dataclasses()

   # Detecting last checkpoint.
   UpperCamelCase__ :			str 						=None
   if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
      UpperCamelCase__ :			str 						=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__ :			Dict 						=read_lines(data_args.data_file      )
   UpperCamelCase__ :			Any 						=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__ :			Union[str, Any] 						=get_teacher_predictions(
       teacher_args.teacher_name_or_path							,  A_							,  A_							,  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__ :			Any 						=Dataset.from_dict(
       {
           "text": examples,
           "labels": teacher_soft_preds,
       }      )

   # 3. create student
   logger.info("Initializing student model"      )
   UpperCamelCase__ :			str 						=AutoModelForSequenceClassification.from_pretrained(
       student_args.student_name_or_path							,  num_labels=len(A_      )      )
   UpperCamelCase__ :			str 						=AutoTokenizer.from_pretrained(student_args.student_name_or_path							,  use_fast=data_args.use_fast_tokenizer      )
   UpperCamelCase__ :			List[Any] 						=dict(enumerate(A_      )      )
   UpperCamelCase__ :			str 						={label: i for i, label in enumerate(A_      )}

   # 4. train student on teacher predictions
   UpperCamelCase__ :			Any 						=dataset.map(A_							,  input_columns="text"      )
   dataset.set_format("torch"      )

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

   UpperCamelCase__ :			str 						=DistillationTrainer(
       model=A_							,  tokenizer=A_							,  args=A_							,  train_dataset=A_							,  compute_metrics=A_							,  )

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

   if training_args.do_eval:
      UpperCamelCase__ :			Any 						=trainer.evaluate(eval_dataset=A_      )["eval_agreement"]
      logger.info(f'''Agreement of student and teacher predictions: {agreement * 1_0_0:0.2f}%'''      )

   trainer.save_model()


if __name__ == "__main__":
     main()

