


import argparse
import logging
import os
from datetime import datetime

import numpy as np
import torch
from torch import nn
from torch.utils.data import DataLoader, SequentialSampler, Subset
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    GlueDataset,
    default_data_collator,
    glue_compute_metrics,
    glue_output_modes,
    glue_processors,
    set_seed,
)
from transformers.trainer_utils import is_main_process


A :       List[Any]						=   logging.getLogger(__name__)

def  lowercase_						(						_A     :       Tuple		):

      """simple docstring"""




      lowerCamelCase__						:							Union[str, Any]       =    p * torch.log(_A		)
      lowerCamelCase__						:							str       =    0
      return -plogp.sum(dim=-1		)

def  lowercase_						(						_A     :       List[str]		):

      """simple docstring"""




      logger.info("lv, h >\t" + "\t".join(F"{x + 1}" for x in range(len(_A		)		)		)		)
      for row in range(len(_A		)		):
            if tensor.dtype != torch.long:
                  logger.info(F"layer {row + 1}:\t" + "\t".join(F"{x:.5f}" for x in tensor[row].cpu().data		)		)
            else:
                  logger.info(F"layer {row + 1}:\t" + "\t".join(F"{x:d}" for x in tensor[row].cpu().data		)		)

def  lowercase_						(						_A     :       Union[str, Any]       ,   _A     :       Union[str, Any]       ,   _A     :       Dict       ,   _A     :       List[Any]=True       ,   _A     :       Any=True       ,   _A     :       str=None       ,   _A     :       Tuple=False		):

      """simple docstring"""




      lowerCamelCase__       ,  lowerCamelCase__						:							Optional[int]       =    model.config.num_hidden_layers, model.config.num_attention_heads
      lowerCamelCase__						:							Dict       =    torch.zeros(_A       ,   _A		).to(args.device		)
      lowerCamelCase__						:							Optional[int]       =    torch.zeros(_A       ,   _A		).to(args.device		)

      if head_mask is None:
            lowerCamelCase__						:							int       =    torch.ones(_A       ,   _A		).to(args.device		)

      head_mask.requires_grad_(requires_grad=_A		)
      # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch
      if actually_pruned:
            lowerCamelCase__						:							List[str]       =    None

      lowerCamelCase__						:							List[Any]       =    None
      lowerCamelCase__						:							Any       =    None
      lowerCamelCase__						:							Any       =    0.0

      for step, inputs in enumerate(tqdm(_A       ,   desc="Iteration"       ,   disable=args.local_rank not in [-1, 0]		)		):
            for k, v in inputs.items():
                  lowerCamelCase__						:							List[Any]       =    v.to(args.device		)

            # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below)
            lowerCamelCase__						:							str       =    model(**_A       ,   head_mask=_A		)
            lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__						:							Dict       =    (
                outputs[0],
                outputs[1],
                outputs[-1],
            )  # Loss and logits are the first, attention the last
            loss.backward()  # Backpropagate to populate the gradients in the head mask

            if compute_entropy:
                  for layer, attn in enumerate(_A		):
                        lowerCamelCase__						:							Tuple       =    entropy(attn.detach()		) * inputs["attention_mask"].float().unsqueeze(1		)
                        attn_entropy[layer] += masked_entropy.sum(-1		).sum(0		).detach()

            if compute_importance:
                  head_importance += head_mask.grad.abs().detach()

            # Also store our logits/labels if we want to compute metrics afterwards
            if preds is None:
                  lowerCamelCase__						:							List[Any]       =    logits.detach().cpu().numpy()
                  lowerCamelCase__						:							Optional[Any]       =    inputs["labels"].detach().cpu().numpy()
            else:
                  lowerCamelCase__						:							Optional[int]       =    np.append(_A       ,   logits.detach().cpu().numpy()       ,   axis=0		)
                  lowerCamelCase__						:							Tuple       =    np.append(_A       ,   inputs["labels"].detach().cpu().numpy()       ,   axis=0		)

            tot_tokens += inputs["attention_mask"].float().detach().sum().data

      # Normalize
      attn_entropy /= tot_tokens
      head_importance /= tot_tokens
      # Layerwise importance normalization
      if not args.dont_normalize_importance_by_layer:
            lowerCamelCase__						:							Optional[int]       =    2
            lowerCamelCase__						:							Optional[int]       =    torch.pow(torch.pow(_A       ,   _A		).sum(-1		)       ,   1 / exponent		)
            head_importance /= norm_by_layer.unsqueeze(-1		) + 1E-20

      if not args.dont_normalize_global_importance:
            lowerCamelCase__						:							int       =    (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min())

      # Print/save matrices
      np.save(os.path.join(args.output_dir       ,   "attn_entropy.npy"		)       ,   attn_entropy.detach().cpu().numpy()		)
      np.save(os.path.join(args.output_dir       ,   "head_importance.npy"		)       ,   head_importance.detach().cpu().numpy()		)

      logger.info("Attention entropies"		)
      print_ad_tensor(_A		)
      logger.info("Head importance scores"		)
      print_ad_tensor(_A		)
      logger.info("Head ranked by importance scores"		)
      lowerCamelCase__						:							int       =    torch.zeros(head_importance.numel()       ,   dtype=torch.long       ,   device=args.device		)
      lowerCamelCase__						:							str       =    torch.arange(
          head_importance.numel()       ,   device=args.device		)
      lowerCamelCase__						:							Dict       =    head_ranks.view_as(_A		)
      print_ad_tensor(_A		)

      return attn_entropy, head_importance, preds, labels

def  lowercase_						(						_A     :       Union[str, Any]       ,   _A     :       List[Any]       ,   _A     :       Tuple		):

      """simple docstring"""




      lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__						:							Any       =    compute_heads_importance(_A       ,   _A       ,   _A       ,   compute_entropy=_A		)
      lowerCamelCase__						:							Dict       =    np.argmax(_A       ,   axis=1		) if args.output_mode == "classification" else np.squeeze(_A		)
      lowerCamelCase__						:							Union[str, Any]       =    glue_compute_metrics(args.task_name       ,   _A       ,   _A		)[args.metric_name]
      logger.info("Pruning: original score: %f, threshold: %f"       ,   _A       ,   original_score * args.masking_threshold		)

      lowerCamelCase__						:							Tuple       =    torch.ones_like(_A		)
      lowerCamelCase__						:							int       =    max(1       ,   int(new_head_mask.numel() * args.masking_amount		)		)

      lowerCamelCase__						:							int       =    original_score
      while current_score >= original_score * args.masking_threshold:
            lowerCamelCase__						:							List[Any]       =    new_head_mask.clone()  # save current head mask
            # heads from least important to most - keep only not-masked heads
            lowerCamelCase__						:							Dict       =    float("Inf"		)
            lowerCamelCase__						:							List[str]       =    head_importance.view(-1		).sort()[1]

            if len(_A		) <= num_to_mask:
                  break

            # mask heads
            lowerCamelCase__						:							int       =    current_heads_to_mask[:num_to_mask]
            logger.info("Heads to mask: %s"       ,   str(current_heads_to_mask.tolist()		)		)
            lowerCamelCase__						:							Optional[int]       =    new_head_mask.view(-1		)
            lowerCamelCase__						:							Dict       =    0.0
            lowerCamelCase__						:							Union[str, Any]       =    new_head_mask.view_as(_A		)
            lowerCamelCase__						:							List[str]       =    new_head_mask.clone().detach()
            print_ad_tensor(_A		)

            # Compute metric and head importance again
            lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__						:							List[str]       =    compute_heads_importance(
                _A       ,   _A       ,   _A       ,   compute_entropy=_A       ,   head_mask=_A		)
            lowerCamelCase__						:							str       =    np.argmax(_A       ,   axis=1		) if args.output_mode == "classification" else np.squeeze(_A		)
            lowerCamelCase__						:							Union[str, Any]       =    glue_compute_metrics(args.task_name       ,   _A       ,   _A		)[args.metric_name]
            logger.info(
                "Masking: current score: %f, remaining heads %d (%.1f percents)"       ,   _A       ,   new_head_mask.sum()       ,   new_head_mask.sum() / new_head_mask.numel() * 100       ,   )

      logger.info("Final head mask"		)
      print_ad_tensor(_A		)
      np.save(os.path.join(args.output_dir       ,   "head_mask.npy"		)       ,   head_mask.detach().cpu().numpy()		)

      return head_mask

def  lowercase_						(						_A     :       Tuple       ,   _A     :       Tuple       ,   _A     :       Optional[Any]       ,   _A     :       Tuple		):

      """simple docstring"""




      lowerCamelCase__						:							Optional[int]       =    datetime.now()
      lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__						:							Any       =    compute_heads_importance(
          _A       ,   _A       ,   _A       ,   compute_entropy=_A       ,   compute_importance=_A       ,   head_mask=_A		)
      lowerCamelCase__						:							Optional[int]       =    np.argmax(_A       ,   axis=1		) if args.output_mode == "classification" else np.squeeze(_A		)
      lowerCamelCase__						:							Union[str, Any]       =    glue_compute_metrics(args.task_name       ,   _A       ,   _A		)[args.metric_name]
      lowerCamelCase__						:							Optional[int]       =    datetime.now() - before_time

      lowerCamelCase__						:							Optional[int]       =    sum(p.numel() for p in model.parameters()		)
      lowerCamelCase__						:							Union[str, Any]       =    {
          layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(_A		)		)
      }

      assert sum(len(_A		) for h in heads_to_prune.values()		) == (1 - head_mask.long()).sum().item()
      model.prune_heads(_A		)
      lowerCamelCase__						:							str       =    sum(p.numel() for p in model.parameters()		)

      lowerCamelCase__						:							List[Any]       =    datetime.now()
      lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__       ,  lowerCamelCase__						:							int       =    compute_heads_importance(
          _A       ,   _A       ,   _A       ,   compute_entropy=_A       ,   compute_importance=_A       ,   head_mask=_A       ,   actually_pruned=_A       ,   )
      lowerCamelCase__						:							List[str]       =    np.argmax(_A       ,   axis=1		) if args.output_mode == "classification" else np.squeeze(_A		)
      lowerCamelCase__						:							Any       =    glue_compute_metrics(args.task_name       ,   _A       ,   _A		)[args.metric_name]
      lowerCamelCase__						:							Optional[int]       =    datetime.now() - before_time

      logger.info(
          "Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)"       ,   _A       ,   _A       ,   pruned_num_params / original_num_params * 100       ,   )
      logger.info("Pruning: score with masking: %f score with pruning: %f"       ,   _A       ,   _A		)
      logger.info("Pruning: speed ratio (new timing / original timing): %f percents"       ,   original_time / new_time * 100		)

def  lowercase_						(						):

      """simple docstring"""




      lowerCamelCase__						:							Optional[Any]       =    argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          "--data_dir"       ,   default=_A       ,   type=_A       ,   required=_A       ,   help="The input data dir. Should contain the .tsv files (or other data files) for the task."       ,   )
      parser.add_argument(
          "--model_name_or_path"       ,   default=_A       ,   type=_A       ,   required=_A       ,   help="Path to pretrained model or model identifier from huggingface.co/models"       ,   )
      parser.add_argument(
          "--task_name"       ,   default=_A       ,   type=_A       ,   required=_A       ,   help="The name of the task to train selected in the list: " + ", ".join(glue_processors.keys()		)       ,   )
      parser.add_argument(
          "--output_dir"       ,   default=_A       ,   type=_A       ,   required=_A       ,   help="The output directory where the model predictions and checkpoints will be written."       ,   )

      # Other parameters
      parser.add_argument(
          "--config_name"       ,   default=""       ,   type=_A       ,   help="Pretrained config name or path if not the same as model_name_or_path"       ,   )
      parser.add_argument(
          "--tokenizer_name"       ,   default=""       ,   type=_A       ,   help="Pretrained tokenizer name or path if not the same as model_name_or_path"       ,   )
      parser.add_argument(
          "--cache_dir"       ,   default=_A       ,   type=_A       ,   help="Where do you want to store the pre-trained models downloaded from huggingface.co"       ,   )
      parser.add_argument(
          "--data_subset"       ,   type=_A       ,   default=-1       ,   help="If > 0: limit the data to a subset of data_subset instances."		)
      parser.add_argument(
          "--overwrite_output_dir"       ,   action="store_true"       ,   help="Whether to overwrite data in output directory"		)
      parser.add_argument(
          "--overwrite_cache"       ,   action="store_true"       ,   help="Overwrite the cached training and evaluation sets"		)

      parser.add_argument(
          "--dont_normalize_importance_by_layer"       ,   action="store_true"       ,   help="Don't normalize importance score by layers"		)
      parser.add_argument(
          "--dont_normalize_global_importance"       ,   action="store_true"       ,   help="Don't normalize all importance scores between 0 and 1"       ,   )

      parser.add_argument(
          "--try_masking"       ,   action="store_true"       ,   help="Whether to try to mask head until a threshold of accuracy."		)
      parser.add_argument(
          "--masking_threshold"       ,   default=0.9       ,   type=_A       ,   help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)."       ,   )
      parser.add_argument(
          "--masking_amount"       ,   default=0.1       ,   type=_A       ,   help="Amount to heads to masking at each masking step."		)
      parser.add_argument("--metric_name"       ,   default="acc"       ,   type=_A       ,   help="Metric to use for head masking."		)

      parser.add_argument(
          "--max_seq_length"       ,   default=128       ,   type=_A       ,   help=(
              "The maximum total input sequence length after WordPiece tokenization. \n"
              "Sequences longer than this will be truncated, sequences shorter padded."
          )       ,   )
      parser.add_argument("--batch_size"       ,   default=1       ,   type=_A       ,   help="Batch size."		)

      parser.add_argument("--seed"       ,   type=_A       ,   default=42		)
      parser.add_argument("--local_rank"       ,   type=_A       ,   default=-1       ,   help="local_rank for distributed training on gpus"		)
      parser.add_argument("--no_cuda"       ,   action="store_true"       ,   help="Whether not to use CUDA when available"		)
      parser.add_argument("--server_ip"       ,   type=_A       ,   default=""       ,   help="Can be used for distant debugging."		)
      parser.add_argument("--server_port"       ,   type=_A       ,   default=""       ,   help="Can be used for distant debugging."		)
      lowerCamelCase__						:							str       =    parser.parse_args()

      if args.server_ip and args.server_port:
            # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
            import ptvsd

            print("Waiting for debugger attach"		)
            ptvsd.enable_attach(address=(args.server_ip, args.server_port)       ,   redirect_output=_A		)
            ptvsd.wait_for_attach()

      # Setup devices and distributed training
      if args.local_rank == -1 or args.no_cuda:
            lowerCamelCase__						:							Tuple       =    torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"		)
            lowerCamelCase__						:							List[str]       =    0 if args.no_cuda else torch.cuda.device_count()
      else:
            torch.cuda.set_device(args.local_rank		)
            lowerCamelCase__						:							Optional[int]       =    torch.device("cuda"       ,   args.local_rank		)
            lowerCamelCase__						:							Tuple       =    1
            torch.distributed.init_process_group(backend="nccl"		)  # Initializes the distributed backend

      # Setup logging
      logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN		)
      logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device       ,   args.n_gpu       ,   bool(args.local_rank != -1		)		)		)
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(args.local_rank		):
            transformers.utils.logging.set_verbosity_info()
            transformers.utils.logging.enable_default_handler()
            transformers.utils.logging.enable_explicit_format()

      # Set seeds
      set_seed(args.seed		)

      # Prepare GLUE task
      lowerCamelCase__						:							str       =    args.task_name.lower()
      if args.task_name not in glue_processors:
            raise ValueError("Task not found: %s" % (args.task_name)		)
      lowerCamelCase__						:							Union[str, Any]       =    glue_processors[args.task_name]()
      lowerCamelCase__						:							int       =    glue_output_modes[args.task_name]
      lowerCamelCase__						:							Any       =    processor.get_labels()
      lowerCamelCase__						:							List[Any]       =    len(_A		)

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.

      lowerCamelCase__						:							str       =    AutoConfig.from_pretrained(
          args.config_name if args.config_name else args.model_name_or_path       ,   num_labels=_A       ,   finetuning_task=args.task_name       ,   output_attentions=_A       ,   cache_dir=args.cache_dir       ,   )
      lowerCamelCase__						:							Union[str, Any]       =    AutoTokenizer.from_pretrained(
          args.tokenizer_name if args.tokenizer_name else args.model_name_or_path       ,   cache_dir=args.cache_dir       ,   )
      lowerCamelCase__						:							str       =    AutoModelForSequenceClassification.from_pretrained(
          args.model_name_or_path       ,   from_tf=bool(".ckpt" in args.model_name_or_path		)       ,   config=_A       ,   cache_dir=args.cache_dir       ,   )

      # Distributed and parallel training
      model.to(args.device		)
      if args.local_rank != -1:
            lowerCamelCase__						:							Any       =    nn.parallel.DistributedDataParallel(
                _A       ,   device_ids=[args.local_rank]       ,   output_device=args.local_rank       ,   find_unused_parameters=_A		)
      elif args.n_gpu > 1:
            lowerCamelCase__						:							Dict       =    nn.DataParallel(_A		)

      # Print/save training arguments
      os.makedirs(args.output_dir       ,   exist_ok=_A		)
      torch.save(_A       ,   os.path.join(args.output_dir       ,   "run_args.bin"		)		)
      logger.info("Training/evaluation parameters %s"       ,   _A		)

      # Prepare dataset for the GLUE task
      lowerCamelCase__						:							Any       =    GlueDataset(_A       ,   tokenizer=_A       ,   mode="dev"		)
      if args.data_subset > 0:
            lowerCamelCase__						:							List[Any]       =    Subset(_A       ,   list(range(min(args.data_subset       ,   len(_A		)		)		)		)		)
      lowerCamelCase__						:							Optional[Any]       =    SequentialSampler(_A		) if args.local_rank == -1 else DistributedSampler(_A		)
      lowerCamelCase__						:							str       =    DataLoader(
          _A       ,   sampler=_A       ,   batch_size=args.batch_size       ,   collate_fn=_A		)

      # Compute head entropy and importance score
      compute_heads_importance(_A       ,   _A       ,   _A		)

      # Try head masking (set heads to zero until the score goes under a threshole)
      # and head pruning (remove masked heads and see the effect on the network)
      if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0:
            lowerCamelCase__						:							Optional[int]       =    mask_heads(_A       ,   _A       ,   _A		)
            prune_heads(_A       ,   _A       ,   _A       ,   _A		)


if __name__ == "__main__":
    main()






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				:     Union[str, Any]   , __lowerCamelCase				:     List[Any]   , __lowerCamelCase				:     int=2   , __lowerCamelCase				:     Any=True   , __lowerCamelCase				:     Union[str, Any]=True   , __lowerCamelCase				:     int=10   , __lowerCamelCase				:     str=10   , __lowerCamelCase				:     int=8   , __lowerCamelCase				:     Optional[int]=[2, 4, 4]   , __lowerCamelCase				:     List[Any]=3   , __lowerCamelCase				:     str=768   , __lowerCamelCase				:     int=5   , __lowerCamelCase				:     Any=4   , __lowerCamelCase				:     int=37   , __lowerCamelCase				:     int="gelu_fast"   , __lowerCamelCase				:     int=0.0   , __lowerCamelCase				:     Optional[int]=0.0   , __lowerCamelCase				:     Union[str, Any]=0.0_2   , __lowerCamelCase				:     Any=1E-0_6   , __lowerCamelCase				:     Optional[int]=True   , __lowerCamelCase				:     Tuple=None   , ):


             '''simple docstring'''



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

             lowerCamelCase__						:							Union[str, 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 		lowerCAmelCase	(  self				:     List[Any]			):


             '''simple docstring'''



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

             lowerCamelCase__						:							Optional[int]       =    None
             if self.use_labels:
                   lowerCamelCase__						:							Optional[Any]       =    ids_tensor([self.batch_size]   , self.num_labels			)

             lowerCamelCase__						:							Any       =    self.get_config()

             return config, pixel_values, labels





       def 		lowerCAmelCase	(  self				:     Union[str, Any]			):


             '''simple docstring'''



             lowerCamelCase__						:							Dict       =    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   , )
             lowerCamelCase__						:							Union[str, Any]       =    self.num_labels
             return config





       def 		lowerCAmelCase	(  self				:     Optional[int]   , __lowerCamelCase				:     List[str]   , __lowerCamelCase				:     Union[str, Any]   , __lowerCamelCase				:     Union[str, Any]			):


             '''simple docstring'''



             lowerCamelCase__						:							Tuple       =    VivitModel(config=__lowerCamelCase			)
             model.to(__lowerCamelCase			)
             model.eval()
             lowerCamelCase__						:							Any       =    model(__lowerCamelCase			)
             self.parent.assertEqual(result.last_hidden_state.shape   , (self.batch_size, self.seq_length, self.hidden_size)			)





       def 		lowerCAmelCase	(  self				:     int   , __lowerCamelCase				:     Union[str, Any]   , __lowerCamelCase				:     Optional[int]   , __lowerCamelCase				:     Optional[int]			):


             '''simple docstring'''



             lowerCamelCase__						:							Dict       =    VivitForVideoClassification(__lowerCamelCase			)
             model.to(__lowerCamelCase			)
             model.eval()

             lowerCamelCase__						:							List[str]       =    model(__lowerCamelCase			)

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





       def 		lowerCAmelCase	(  self				:     Optional[Any]			):


             '''simple docstring'''



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







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


       """simple docstring"""




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

       A__   		=     False
       A__   		=     False
       A__   		=     False
       A__   		=     False





       def 		lowerCAmelCase	(  self				:     Optional[int]			):


             '''simple docstring'''



             lowerCamelCase__						:							Any       =    VivitModelTester(self			)
             lowerCamelCase__						:							Any       =    ConfigTester(self   , config_class=__lowerCamelCase   , has_text_modality=__lowerCamelCase   , hidden_size=37			)





       def 		lowerCAmelCase	(  self				:     int   , __lowerCamelCase				:     List[str]   , __lowerCamelCase				:     Dict   , __lowerCamelCase				:     Union[str, Any]=False			):


             '''simple docstring'''



             lowerCamelCase__						:							int       =    copy.deepcopy(__lowerCamelCase			)

             if return_labels:
                   if model_class in get_values(__lowerCamelCase			):
                         lowerCamelCase__						:							List[Any]       =    torch.zeros(
                             self.model_tester.batch_size   , dtype=torch.long   , device=__lowerCamelCase			)

             return inputs_dict





       def 		lowerCAmelCase	(  self				:     List[str]			):


             '''simple docstring'''



             self.config_tester.run_common_tests()





       @unittest.skip(reason="Vivit does not use inputs_embeds"			)
       def 		lowerCAmelCase	(  self				:     int			):


             '''simple docstring'''



             pass





       def 		lowerCAmelCase	(  self				:     Union[str, Any]			):


             '''simple docstring'''



             lowerCamelCase__       ,  lowerCamelCase__						:							int       =    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   lowerCamelCase__						:							str       =    model_class(__lowerCamelCase			)
                   self.assertIsInstance(model.get_input_embeddings()   , (nn.Module)			)
                   lowerCamelCase__						:							Dict       =    model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(__lowerCamelCase   , nn.Linear			)			)





       def 		lowerCAmelCase	(  self				:     List[str]			):


             '''simple docstring'''



             lowerCamelCase__       ,  lowerCamelCase__						:							str       =    self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   lowerCamelCase__						:							Tuple       =    model_class(__lowerCamelCase			)
                   lowerCamelCase__						:							List[Any]       =    inspect.signature(model.forward			)
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   lowerCamelCase__						:							int       =    [*signature.parameters.keys()]

                   lowerCamelCase__						:							Any       =    ["pixel_values", "head_mask"]
                   self.assertListEqual(arg_names[:2]   , __lowerCamelCase			)





       def 		lowerCAmelCase	(  self				:     Dict			):


             '''simple docstring'''



             lowerCamelCase__						:							str       =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__lowerCamelCase			)





       def 		lowerCAmelCase	(  self				:     Tuple			):


             '''simple docstring'''



             lowerCamelCase__						:							int       =    self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase			)





       @slow
       def 		lowerCAmelCase	(  self				:     List[Any]			):


             '''simple docstring'''



             for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   lowerCamelCase__						:							str       =    VivitModel.from_pretrained(__lowerCamelCase			)
                   self.assertIsNotNone(__lowerCamelCase			)





       def 		lowerCAmelCase	(  self				:     Tuple			):


             '''simple docstring'''



             lowerCamelCase__       ,  lowerCamelCase__						:							Dict       =    self.model_tester.prepare_config_and_inputs_for_common()
             lowerCamelCase__						:							List[str]       =    True

             for model_class in self.all_model_classes:
                   lowerCamelCase__						:							Any       =    self.model_tester.seq_length

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

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

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

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

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

                   lowerCamelCase__						:							Any       =    outputs.attentions

                   self.assertEqual(len(__lowerCamelCase			)   , 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 		lowerCAmelCase	(  self				:     List[str]			):


             '''simple docstring'''



             def check_hidden_states_output(__lowerCamelCase				:     str   , __lowerCamelCase				:     List[str]   , __lowerCamelCase				:     Tuple			):
                   lowerCamelCase__						:							Union[str, Any]       =    model_class(__lowerCamelCase			)
                   model.to(__lowerCamelCase			)
                   model.eval()

                   with torch.no_grad():
                         lowerCamelCase__						:							Optional[Any]       =    model(**self._prepare_for_class(__lowerCamelCase   , __lowerCamelCase			)			)

                   lowerCamelCase__						:							List[Any]       =    outputs.hidden_states
                   lowerCamelCase__						:							Optional[int]       =    self.model_tester.num_hidden_layers + 1
                   self.assertEqual(len(__lowerCamelCase			)   , __lowerCamelCase			)

                   lowerCamelCase__						:							Optional[int]       =    self.model_tester.seq_length

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

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

             for model_class in self.all_model_classes:
                   lowerCamelCase__						:							Tuple       =    True
                   check_hidden_states_output(__lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase			)

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

                   check_hidden_states_output(__lowerCamelCase   , __lowerCamelCase   , __lowerCamelCase			)





       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."			)
       def 		lowerCAmelCase	(  self				:     Tuple			):


             '''simple docstring'''



             pass



def  lowercase_						(						):

      """simple docstring"""




      lowerCamelCase__						:							str       =    hf_hub_download(
          repo_id="hf-internal-testing/spaghetti-video"       ,   filename="eating_spaghetti_32_frames.npy"       ,   repo_type="dataset"		)
      lowerCamelCase__						:							Union[str, Any]       =    np.load(_A		)
      return list(_A		)







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


       """simple docstring"""




       @cached_property
       def 		lowerCAmelCase	(  self				:     str			):


             '''simple docstring'''



             return VivitImageProcessor() if is_vision_available() else None





       @slow
       def 		lowerCAmelCase	(  self				:     Tuple			):


             '''simple docstring'''



             lowerCamelCase__						:							Optional[int]       =    VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400"			).to(__lowerCamelCase			)

             lowerCamelCase__						:							Tuple       =    self.default_image_processor
             lowerCamelCase__						:							List[str]       =    prepare_video()
             lowerCamelCase__						:							Optional[int]       =    image_processor(__lowerCamelCase   , return_tensors="pt"			).to(__lowerCamelCase			)

             # forward pass
             with torch.no_grad():
                   lowerCamelCase__						:							Optional[int]       =    model(**__lowerCamelCase			)

             # verify the logits
             lowerCamelCase__						:							str       =    torch.Size((1, 400)			)
             self.assertEqual(outputs.logits.shape   , __lowerCamelCase			)

             # taken from original model
             lowerCamelCase__						:							str       =    torch.tensor([-1.0_5_4_3, 2.0_7_6_4, -0.2_1_0_4, 0.4_4_3_9, -0.9_6_5_8]			).to(__lowerCamelCase			)

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


