






'''simple docstring'''
# Note: if you intend to run this script make sure you look under scripts/fsmt/
# to locate the appropriate script to do the work correctly. There is a set of scripts to:
# - download and prepare data and run the conversion script
# - perform eval to get the best hparam into the config
# - generate model_cards - useful if you have multiple models from the same paper

import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname

import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary

from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging


logging.set_verbosity_warning()

a_					= 2

# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
a_					= {
    # fairseq:
    'wmt19-ru-en': {'length_penalty': 1.1},
    'wmt19-en-ru': {'length_penalty': 1.15},
    'wmt19-en-de': {'length_penalty': 1.0},
    'wmt19-de-en': {'length_penalty': 1.1},
    # allenai:
    'wmt16-en-de-dist-12-1': {'length_penalty': 0.6},
    'wmt16-en-de-dist-6-1': {'length_penalty': 0.6},
    'wmt16-en-de-12-1': {'length_penalty': 0.8},
    'wmt19-de-en-6-6-base': {'length_penalty': 0.6},
    'wmt19-de-en-6-6-big': {'length_penalty': 0.6},
}

# this remaps the different models to their organization names
a_					= {}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
  a_					= 'facebook'
for m in [
    "wmt16-en-de-dist-12-1",
    "wmt16-en-de-dist-6-1",
    "wmt16-en-de-12-1",
    "wmt19-de-en-6-6-base",
    "wmt19-de-en-6-6-big",
]:
  a_					= 'allenai'





def  _a(  UpperCamelCase__				:						str							):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__     :				Any									=dict((re.sub(R'''@@$''',	'''''',	UpperCamelCase__							), v) if k.endswith('''@@'''							) else (re.sub(R'''$''',	'''</w>''',	UpperCamelCase__							), v) for k, v in d.items()							)
      SCREAMING_SNAKE_CASE__     :				List[str]									='''<s> <pad> </s> <unk>'''.split()
      # restore the special tokens
      for k in keep_keys:
            del da[f"{k}</w>"]
            SCREAMING_SNAKE_CASE__     :				List[Any]									=d[k]  # restore
      return da





def  _a(  UpperCamelCase__				:						str,	UpperCamelCase__				:						Optional[Any]							):




      '''simple docstring'''






      assert os.path.exists(UpperCamelCase__							)
      os.makedirs(UpperCamelCase__,	exist_ok=UpperCamelCase__							)
      print(f"Writing results to {pytorch_dump_folder_path}"							)

      # handle various types of models

      SCREAMING_SNAKE_CASE__     :				Tuple									=basename(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				Tuple									=dirname(UpperCamelCase__							)

      SCREAMING_SNAKE_CASE__     :				Any									=fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
      SCREAMING_SNAKE_CASE__     :				List[Any]									=cls.hub_models()
      SCREAMING_SNAKE_CASE__     :				List[Any]									={'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''}
      SCREAMING_SNAKE_CASE__     :				Dict									='''.'''
      # note: since the model dump is old, fairseq has upgraded its model some
      # time later, and it does a whole lot of rewrites and splits on the saved
      # weights, therefore we can't use torch.load() directly on the model file.
      # see: upgrade_state_dict(state_dict) in fairseq_model.py
      print(f"using checkpoint {checkpoint_file}"							)
      SCREAMING_SNAKE_CASE__     :				Any									=hub_utils.from_pretrained(
          UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	archive_map=UpperCamelCase__,	**UpperCamelCase__							)

      SCREAMING_SNAKE_CASE__     :				Optional[Any]									=vars(chkpt['''args''']['''model''']							)

      SCREAMING_SNAKE_CASE__     :				str									=args['''source_lang''']
      SCREAMING_SNAKE_CASE__     :				List[Any]									=args['''target_lang''']

      SCREAMING_SNAKE_CASE__     :				Dict									=dirname(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				Optional[int]									=basename(UpperCamelCase__							)

      # dicts
      SCREAMING_SNAKE_CASE__     :				List[str]									=os.path.join(UpperCamelCase__,	f"dict.{src_lang}.txt"							)
      SCREAMING_SNAKE_CASE__     :				List[str]									=os.path.join(UpperCamelCase__,	f"dict.{tgt_lang}.txt"							)

      SCREAMING_SNAKE_CASE__     :				Tuple									=Dictionary.load(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				str									=rewrite_dict_keys(src_dict.indices							)
      SCREAMING_SNAKE_CASE__     :				List[str]									=len(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				List[Any]									=os.path.join(UpperCamelCase__,	'''vocab-src.json'''							)
      print(f"Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records"							)
      with open(UpperCamelCase__,	'''w''',	encoding='''utf-8'''							) as f:
            f.write(json.dumps(UpperCamelCase__,	ensure_ascii=UpperCamelCase__,	indent=UpperCamelCase__							)							)

      # detect whether this is a do_lower_case situation, which can be derived by checking whether we
      # have at least one uppercase letter in the source vocab
      SCREAMING_SNAKE_CASE__     :				Optional[int]									=True
      for k in src_vocab.keys():
            if not k.islower():
                  SCREAMING_SNAKE_CASE__     :				int									=False
                  break

      SCREAMING_SNAKE_CASE__     :				Dict									=Dictionary.load(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				Any									=rewrite_dict_keys(tgt_dict.indices							)
      SCREAMING_SNAKE_CASE__     :				Optional[int]									=len(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				List[str]									=os.path.join(UpperCamelCase__,	'''vocab-tgt.json'''							)
      print(f"Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records"							)
      with open(UpperCamelCase__,	'''w''',	encoding='''utf-8'''							) as f:
            f.write(json.dumps(UpperCamelCase__,	ensure_ascii=UpperCamelCase__,	indent=UpperCamelCase__							)							)

      # merges_file (bpecodes)
      SCREAMING_SNAKE_CASE__     :				Any									=os.path.join(UpperCamelCase__,	VOCAB_FILES_NAMES['''merges_file''']							)
      for fn in ["bpecodes", "code"]:  # older fairseq called the merges file "code"
            SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=os.path.join(UpperCamelCase__,	UpperCamelCase__							)
            if os.path.exists(UpperCamelCase__							):
                  break
      with open(UpperCamelCase__,	encoding='''utf-8'''							) as fin:
            SCREAMING_SNAKE_CASE__     :				Optional[Any]									=fin.read()
      SCREAMING_SNAKE_CASE__     :				Any									=re.sub(R''' \d+$''',	'''''',	UpperCamelCase__,	0,	re.M							)  # remove frequency number
      print(f"Generating {merges_file}"							)
      with open(UpperCamelCase__,	'''w''',	encoding='''utf-8'''							) as fout:
            fout.write(UpperCamelCase__							)

      # model config
      SCREAMING_SNAKE_CASE__     :				Optional[int]									=os.path.join(UpperCamelCase__,	'''config.json'''							)

      # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
      # may have to modify the tokenizer if a different type is used by a future model
      assert args["bpe"] == "fastbpe", f"need to extend tokenizer to support bpe={args['bpe']}"
      assert args["tokenizer"] == "moses", f"need to extend tokenizer to support bpe={args['tokenizer']}"

      SCREAMING_SNAKE_CASE__     :				List[Any]									={
          '''architectures''': ['''FSMTForConditionalGeneration'''],
          '''model_type''': '''fsmt''',
          '''activation_dropout''': args['''activation_dropout'''],
          '''activation_function''': '''relu''',
          '''attention_dropout''': args['''attention_dropout'''],
          '''d_model''': args['''decoder_embed_dim'''],
          '''dropout''': args['''dropout'''],
          '''init_std''': 0.0_2,
          '''max_position_embeddings''': args['''max_source_positions'''],
          '''num_hidden_layers''': args['''encoder_layers'''],
          '''src_vocab_size''': src_vocab_size,
          '''tgt_vocab_size''': tgt_vocab_size,
          '''langs''': [src_lang, tgt_lang],
          '''encoder_attention_heads''': args['''encoder_attention_heads'''],
          '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''],
          '''encoder_layerdrop''': args['''encoder_layerdrop'''],
          '''encoder_layers''': args['''encoder_layers'''],
          '''decoder_attention_heads''': args['''decoder_attention_heads'''],
          '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''],
          '''decoder_layerdrop''': args['''decoder_layerdrop'''],
          '''decoder_layers''': args['''decoder_layers'''],
          '''bos_token_id''': 0,
          '''pad_token_id''': 1,
          '''eos_token_id''': 2,
          '''is_encoder_decoder''': True,
          '''scale_embedding''': not args['''no_scale_embedding'''],
          '''tie_word_embeddings''': args['''share_all_embeddings'''],
      }

      # good hparam defaults to start with
      SCREAMING_SNAKE_CASE__     :				Optional[int]									=5
      SCREAMING_SNAKE_CASE__     :				Optional[Any]									=False
      if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
            SCREAMING_SNAKE_CASE__     :				List[str]									=best_score_hparams[model_dir]['''length_penalty''']
      else:
            SCREAMING_SNAKE_CASE__     :				List[str]									=1.0

      print(f"Generating {fsmt_model_config_file}"							)
      with open(UpperCamelCase__,	'''w''',	encoding='''utf-8'''							) as f:
            f.write(json.dumps(UpperCamelCase__,	ensure_ascii=UpperCamelCase__,	indent=UpperCamelCase__							)							)

      # tokenizer config
      SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=os.path.join(UpperCamelCase__,	UpperCamelCase__							)

      SCREAMING_SNAKE_CASE__     :				List[str]									={
          '''langs''': [src_lang, tgt_lang],
          '''model_max_length''': 1_0_2_4,
          '''do_lower_case''': do_lower_case,
      }

      print(f"Generating {fsmt_tokenizer_config_file}"							)
      with open(UpperCamelCase__,	'''w''',	encoding='''utf-8'''							) as f:
            f.write(json.dumps(UpperCamelCase__,	ensure_ascii=UpperCamelCase__,	indent=UpperCamelCase__							)							)

      # model
      SCREAMING_SNAKE_CASE__     :				Optional[Any]									=chkpt['''models'''][0]
      SCREAMING_SNAKE_CASE__     :				Any									=model.state_dict()

      # rename keys to start with 'model.'
      SCREAMING_SNAKE_CASE__     :				Optional[Any]									=OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items()							)

      # remove unneeded keys
      SCREAMING_SNAKE_CASE__     :				Tuple									=[
          '''model.model''',
          '''model.encoder.version''',
          '''model.decoder.version''',
          '''model.encoder_embed_tokens.weight''',
          '''model.decoder_embed_tokens.weight''',
          '''model.encoder.embed_positions._float_tensor''',
          '''model.decoder.embed_positions._float_tensor''',
      ]
      for k in ignore_keys:
            model_state_dict.pop(UpperCamelCase__,	UpperCamelCase__							)

      SCREAMING_SNAKE_CASE__     :				List[Any]									=FSMTConfig.from_pretrained(UpperCamelCase__							)
      SCREAMING_SNAKE_CASE__     :				str									=FSMTForConditionalGeneration(UpperCamelCase__							)

      # check that it loads ok
      model_new.load_state_dict(UpperCamelCase__,	strict=UpperCamelCase__							)

      # save
      SCREAMING_SNAKE_CASE__     :				Any									=os.path.join(UpperCamelCase__,	UpperCamelCase__							)
      print(f"Generating {pytorch_weights_dump_path}"							)
      torch.save(UpperCamelCase__,	UpperCamelCase__							)

      print('''Conversion is done!'''							)
      print('''\nLast step is to upload the files to s3'''							)
      print(f"cd {data_root}"							)
      print(f"transformers-cli upload {model_dir}"							)


if __name__ == "__main__":
  a_					= argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '--fsmt_checkpoint_path',
      default=None,
      type=str,
      required=True,
      help=(
          'Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,'
          ' bpecodes, etc.'
      ),
  )
  parser.add_argument(
      '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
  )
  a_					= parser.parse_args()
  convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)







'''simple docstring'''
import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import (
      MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
      TimesformerForVideoClassification,
      TimesformerModel,
  )
  from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from transformers import VideoMAEImageProcessor






class      __SCREAMING_SNAKE_CASE      :




 def __init__(      self	:							Optional[int]					,      __lowercase	:							Optional[int]					,      __lowercase	:							str=13					,      __lowercase	:							int=10					,      __lowercase	:							List[Any]=3					,      __lowercase	:							List[str]=2					,      __lowercase	:							int=2					,      __lowercase	:							Dict=True					,      __lowercase	:							Optional[Any]=True					,      __lowercase	:							int=32					,      __lowercase	:							List[Any]=5					,      __lowercase	:							Union[str, Any]=4					,      __lowercase	:							Any=37					,      __lowercase	:							Optional[Any]="gelu"					,      __lowercase	:							Union[str, Any]=0.1					,      __lowercase	:							Tuple=0.1					,      __lowercase	:							Dict=10					,      __lowercase	:							int=0.02					,      __lowercase	:							str="divided_space_time"					,      __lowercase	:							Union[str, Any]=None					,      )	->						Optional[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=parent
       SCREAMING_SNAKE_CASE__     :				List[str]									=batch_size
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=image_size
       SCREAMING_SNAKE_CASE__     :				List[Any]									=num_channels
       SCREAMING_SNAKE_CASE__     :				int									=patch_size
       SCREAMING_SNAKE_CASE__     :				Tuple									=num_frames
       SCREAMING_SNAKE_CASE__     :				List[Any]									=is_training
       SCREAMING_SNAKE_CASE__     :				List[str]									=use_labels
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=hidden_size
       SCREAMING_SNAKE_CASE__     :				str									=num_hidden_layers
       SCREAMING_SNAKE_CASE__     :				int									=num_attention_heads
       SCREAMING_SNAKE_CASE__     :				Tuple									=intermediate_size
       SCREAMING_SNAKE_CASE__     :				List[str]									=hidden_act
       SCREAMING_SNAKE_CASE__     :				Dict									=hidden_dropout_prob
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__     :				List[Any]									=attention_type
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=initializer_range
       SCREAMING_SNAKE_CASE__     :				Any									=scope
       SCREAMING_SNAKE_CASE__     :				int									=num_labels

       # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
       SCREAMING_SNAKE_CASE__     :				List[str]									=(image_size // patch_size) ** 2
       SCREAMING_SNAKE_CASE__     :				str									=(num_frames) * self.num_patches_per_frame + 1




 def      __magic_name__	(      self	:							Optional[int]      )	->						Tuple:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=floats_tensor(
           [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=None
       if self.use_labels:
             SCREAMING_SNAKE_CASE__     :				Any									=ids_tensor([self.batch_size]					,      self.num_labels      )

       SCREAMING_SNAKE_CASE__     :				int									=self.get_config()

       return config, pixel_values, labels




 def      __magic_name__	(      self	:							int      )	->						Any:
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=TimesformerConfig(
           image_size=self.image_size					,      patch_size=self.patch_size					,      num_channels=self.num_channels					,      num_frames=self.num_frames					,      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					,      attention_type=self.attention_type					,      )
       SCREAMING_SNAKE_CASE__     :				List[Any]									=self.num_labels
       return config




 def      __magic_name__	(      self	:							int					,      __lowercase	:							Optional[int]					,      __lowercase	:							Dict					,      __lowercase	:							List[Any]      )	->						int:
       SCREAMING_SNAKE_CASE__     :				Tuple									=TimesformerModel(config=__lowercase      )
       model.to(__lowercase      )
       model.eval()
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=model(__lowercase      )
       self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)      )




 def      __magic_name__	(      self	:							List[str]					,      __lowercase	:							str					,      __lowercase	:							Tuple					,      __lowercase	:							List[Any]      )	->						List[Any]:
       SCREAMING_SNAKE_CASE__     :				str									=TimesformerForVideoClassification(__lowercase      )
       model.to(__lowercase      )
       model.eval()

       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=model(__lowercase      )

       # verify the logits shape
       SCREAMING_SNAKE_CASE__     :				Tuple									=torch.Size((self.batch_size, self.num_labels)      )
       self.parent.assertEqual(result.logits.shape					,      __lowercase      )




 def      __magic_name__	(      self	:							Any      )	->						List[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				str									=config_and_inputs
       SCREAMING_SNAKE_CASE__     :				Any									={'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_torch
class      __SCREAMING_SNAKE_CASE      (			lowerCamelCase	,				lowerCamelCase	,				unittest.TestCase				):
 snake_case_  							=							(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
 snake_case_  							=							(
     {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
     if is_torch_available()
     else {}
 )

 snake_case_  							=							False
 snake_case_  							=							False
 snake_case_  							=							False
 snake_case_  							=							False




 def      __magic_name__	(      self	:							str      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				Dict									=TimesformerModelTester(self      )
       SCREAMING_SNAKE_CASE__     :				List[Any]									=ConfigTester(
           self					,      config_class=__lowercase					,      has_text_modality=__lowercase					,      hidden_size=37      )




 def      __magic_name__	(      self	:							str					,      __lowercase	:							Dict					,      __lowercase	:							str					,      __lowercase	:							Optional[int]=False      )	->						int:
       SCREAMING_SNAKE_CASE__     :				str									=copy.deepcopy(__lowercase      )

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

       return inputs_dict




 def      __magic_name__	(      self	:							List[Any]      )	->						Any:
       self.config_tester.run_common_tests()




 @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''      )
 def      __magic_name__	(      self	:							List[Any]      )	->						Optional[int]:
       pass




 def      __magic_name__	(      self	:							str      )	->						Tuple:
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				List[Any]									=self.model_tester.prepare_config_and_inputs_for_common()

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




 def      __magic_name__	(      self	:							Any      )	->						Any:
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				str									=self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__     :				Optional[Any]									=model_class(__lowercase      )
             SCREAMING_SNAKE_CASE__     :				str									=inspect.signature(model.forward      )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             SCREAMING_SNAKE_CASE__     :				List[str]									=[*signature.parameters.keys()]

             SCREAMING_SNAKE_CASE__     :				Dict									=['''pixel_values''']
             self.assertListEqual(arg_names[:1]					,      __lowercase      )




 def      __magic_name__	(      self	:							int      )	->						Dict:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowercase      )




 def      __magic_name__	(      self	:							List[str]      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*__lowercase      )




 @slow
 def      __magic_name__	(      self	:							Optional[int]      )	->						Optional[Any]:
       for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=TimesformerModel.from_pretrained(__lowercase      )
             self.assertIsNotNone(__lowercase      )




 def      __magic_name__	(      self	:							Union[str, Any]      )	->						List[str]:
       if not self.has_attentions:
             pass

       else:
             SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				Any									=self.model_tester.prepare_config_and_inputs_for_common()
             SCREAMING_SNAKE_CASE__     :				List[Any]									=True

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE__     :				List[Any]									=self.model_tester.seq_length
                   SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=self.model_tester.num_frames

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

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

                   # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                   self.assertListEqual(
                       list(attentions[0].shape[-3:]      )					,      [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,      )
                   SCREAMING_SNAKE_CASE__     :				Optional[int]									=len(__lowercase      )

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

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

                   SCREAMING_SNAKE_CASE__     :				List[str]									=outputs.attentions

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

                   # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
                   self.assertListEqual(
                       list(self_attentions[0].shape[-3:]      )					,      [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1]					,      )




 def      __magic_name__	(      self	:							Tuple      )	->						List[Any]:
       def check_hidden_states_output(__lowercase	:							Tuple					,      __lowercase	:							Dict					,      __lowercase	:							Optional[int]      ):
             SCREAMING_SNAKE_CASE__     :				List[Any]									=model_class(__lowercase      )
             model.to(__lowercase      )
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE__     :				int									=model(**self._prepare_for_class(__lowercase					,      __lowercase      )      )

             SCREAMING_SNAKE_CASE__     :				List[Any]									=outputs.hidden_states
             SCREAMING_SNAKE_CASE__     :				Tuple									=self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(__lowercase      )					,      __lowercase      )

             SCREAMING_SNAKE_CASE__     :				int									=self.model_tester.seq_length

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

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

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__     :				Tuple									=True
             check_hidden_states_output(__lowercase					,      __lowercase					,      __lowercase      )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__     :				List[str]									=True

             check_hidden_states_output(__lowercase					,      __lowercase					,      __lowercase      )





def  _a(  ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=hf_hub_download(
          repo_id='''hf-internal-testing/spaghetti-video''',	filename='''eating_spaghetti.npy''',	repo_type='''dataset'''							)
      SCREAMING_SNAKE_CASE__     :				Any									=np.load(UpperCamelCase__							)
      return list(UpperCamelCase__							)







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




 @cached_property
 def      __magic_name__	(      self	:							Any      )	->						List[str]:
       # logits were tested with a different mean and std, so we use the same here
       return (
           VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]					,      image_std=[0.5, 0.5, 0.5]      )
           if is_vision_available()
           else None
       )




 @slow
 def      __magic_name__	(      self	:							Any      )	->						Optional[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''      ).to(
           __lowercase      )

       SCREAMING_SNAKE_CASE__     :				List[str]									=self.default_image_processor
       SCREAMING_SNAKE_CASE__     :				Tuple									=prepare_video()
       SCREAMING_SNAKE_CASE__     :				Any									=image_processor(video[:8]					,      return_tensors='''pt'''      ).to(__lowercase      )

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

       # verify the logits
       SCREAMING_SNAKE_CASE__     :				List[str]									=torch.Size((1, 4_00)      )
       self.assertEqual(outputs.logits.shape					,      __lowercase      )

       SCREAMING_SNAKE_CASE__     :				List[Any]									=torch.tensor([-0.3016, -0.7713, -0.4205]      ).to(__lowercase      )

       self.assertTrue(torch.allclose(outputs.logits[0, :3]					,      __lowercase					,      atol=1e-4      )      )