
'''simple docstring'''





import argparse
import json
import os.path
from collections import OrderedDict

import numpy as np
import requests
import torch
from flax.training.checkpoints import restore_checkpoint
from huggingface_hub import hf_hub_download

from transformers import VivitConfig, VivitForVideoClassification, VivitImageProcessor
from transformers.image_utils import PILImageResampling







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					Union[str, Any]:
       lowercase							:  Optional[int] 			=   '''https://storage.googleapis.com/scenic-bucket/vivit/kinetics_400/vivit_base_16x2_unfactorized/checkpoint'''

       with open(SCREAMING_SNAKE_CASE__      ,			"""wb"""       ) as f:
              with requests.get(SCREAMING_SNAKE_CASE__      ,			stream=SCREAMING_SNAKE_CASE__       ) as req:
                     for chunk in req.iter_content(chunk_size=2_048       ):
                            f.write(SCREAMING_SNAKE_CASE__       )







def 		_snake_case(						)				->					VivitConfig:
       lowercase							:  int 			=   VivitConfig()

       lowercase							:  Dict 			=   400
       lowercase							:  Any 			=   '''huggingface/label-files'''
       lowercase							:  Optional[Any] 			=   '''kinetics400-id2label.json'''

       lowercase							:  Optional[Any] 			=   json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__      ,			repo_type="""dataset"""       )      ,			"""r"""       )       )
       lowercase							:  Dict 			=   {int(SCREAMING_SNAKE_CASE__       ): v for k, v in idalabel.items()}
       lowercase							:  Tuple 			=   idalabel
       lowercase							:  Optional[int] 			=   {v: k for k, v in idalabel.items()}
       return config







def 		_snake_case(						)				->					List[Any]:
       lowercase							:  Optional[int] 			=   hf_hub_download(
           repo_id="""hf-internal-testing/spaghetti-video"""      ,			filename="""eating_spaghetti_32_frames.npy"""      ,			repo_type="""dataset"""       )
       lowercase							:  Any 			=   np.load(SCREAMING_SNAKE_CASE__       )
       return list(SCREAMING_SNAKE_CASE__       )







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					Optional[Any]:
       if np.ndim(SCREAMING_SNAKE_CASE__       ) == 2:
              return transform_attention_bias(SCREAMING_SNAKE_CASE__       )

       elif np.ndim(SCREAMING_SNAKE_CASE__       ) == 3:
              return transform_attention_kernel(SCREAMING_SNAKE_CASE__       )

       else:
              raise Exception(f"Invalid number of dimesions: {np.ndim(SCREAMING_SNAKE_CASE__       )}"       )







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					Any:
       return current.flatten()







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					str:
       return np.reshape(SCREAMING_SNAKE_CASE__      ,			(current.shape[0], current.shape[1] * current.shape[2])       ).T







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					Optional[Any]:
       return np.reshape(SCREAMING_SNAKE_CASE__      ,			(current.shape[0] * current.shape[1], current.shape[2])       ).T







def 		_snake_case(						SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       )				->					Tuple:
       lowercase							:  Tuple 			=   state_dict['''optimizer''']['''target''']['''Transformer'''][f"encoderblock_{i}"]

       lowercase							:  List[str] 			=   f"encoder.layer.{i}."
       lowercase							:  Union[str, Any] 			=   {
           prefix + '''intermediate.dense.bias''': state['''MlpBlock_0''']['''Dense_0''']['''bias'''],
           prefix + '''intermediate.dense.weight''': np.transpose(state["""MlpBlock_0"""]["""Dense_0"""]["""kernel"""]       ),
           prefix + '''output.dense.bias''': state['''MlpBlock_0''']['''Dense_1''']['''bias'''],
           prefix + '''output.dense.weight''': np.transpose(state["""MlpBlock_0"""]["""Dense_1"""]["""kernel"""]       ),
           prefix + '''layernorm_before.bias''': state['''LayerNorm_0''']['''bias'''],
           prefix + '''layernorm_before.weight''': state['''LayerNorm_0''']['''scale'''],
           prefix + '''layernorm_after.bias''': state['''LayerNorm_1''']['''bias'''],
           prefix + '''layernorm_after.weight''': state['''LayerNorm_1''']['''scale'''],
           prefix
           + '''attention.attention.query.bias''': transform_attention(
               state["""MultiHeadDotProductAttention_0"""]["""query"""]["""bias"""]       ),
           prefix
           + '''attention.attention.query.weight''': transform_attention(
               state["""MultiHeadDotProductAttention_0"""]["""query"""]["""kernel"""]       ),
           prefix
           + '''attention.attention.key.bias''': transform_attention(state["""MultiHeadDotProductAttention_0"""]["""key"""]["""bias"""]       ),
           prefix
           + '''attention.attention.key.weight''': transform_attention(
               state["""MultiHeadDotProductAttention_0"""]["""key"""]["""kernel"""]       ),
           prefix
           + '''attention.attention.value.bias''': transform_attention(
               state["""MultiHeadDotProductAttention_0"""]["""value"""]["""bias"""]       ),
           prefix
           + '''attention.attention.value.weight''': transform_attention(
               state["""MultiHeadDotProductAttention_0"""]["""value"""]["""kernel"""]       ),
           prefix + '''attention.output.dense.bias''': state['''MultiHeadDotProductAttention_0''']['''out''']['''bias'''],
           prefix
           + '''attention.output.dense.weight''': transform_attention_output_weight(
               state["""MultiHeadDotProductAttention_0"""]["""out"""]["""kernel"""]       ),
       }

       return new_state







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					List[Any]:
       return sum([1 if """encoderblock_""" in k else 0 for k in state_dict["""optimizer"""]["""target"""]["""Transformer"""].keys()]       )







def 		_snake_case(						SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__=False       )				->					Optional[int]:
       lowercase							:  str 			=   get_n_layers(SCREAMING_SNAKE_CASE__       )

       lowercase							:  List[Any] 			=   OrderedDict()

       lowercase							:  Union[str, Any] 			=   state_dict['''optimizer''']['''target''']['''Transformer''']['''encoder_norm''']['''bias''']
       lowercase							:  List[Any] 			=   state_dict['''optimizer''']['''target''']['''Transformer''']['''encoder_norm''']['''scale''']

       lowercase							:  int 			=   np.transpose(
           state_dict["""optimizer"""]["""target"""]["""embedding"""]["""kernel"""]      ,			(4, 3, 0, 1, 2)       )
       lowercase							:  List[str] 			=   state_dict['''optimizer''']['''target''']['''embedding''']['''bias''']

       lowercase							:  int 			=   state_dict['''optimizer''']['''target''']['''cls''']
       lowercase							:  List[str] 			=   state_dict['''optimizer''']['''target''']['''Transformer''']['''posembed_input'''][
           '''pos_embedding'''
       ]

       for i in range(SCREAMING_SNAKE_CASE__       ):
              new_state.update(transform_state_encoder_block(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       )       )

       if classification_head:
              lowercase							:  int 			=   {'''vivit.''' + k: v for k, v in new_state.items()}
              lowercase							:  List[str] 			=   np.transpose(state_dict["""optimizer"""]["""target"""]["""output_projection"""]["""kernel"""]       )
              lowercase							:  str 			=   np.transpose(state_dict["""optimizer"""]["""target"""]["""output_projection"""]["""bias"""]       )

       return {k: torch.tensor(SCREAMING_SNAKE_CASE__       ) for k, v in new_state.items()}







def 		_snake_case(						)				->					VivitImageProcessor:
       lowercase							:  Tuple 			=   VivitImageProcessor()

       assert extractor.do_resize is True
       assert extractor.size == {"shortest_edge": 256}
       assert extractor.do_center_crop is True
       assert extractor.crop_size == {"width": 224, "height": 224}
       assert extractor.resample == PILImageResampling.BILINEAR

       # here: https://github.com/deepmind/dmvr/blob/master/dmvr/modalities.py
       # one can seen that add_image has default values for normalization_mean and normalization_std set to 0 and 1
       # which effectively means no normalization (and ViViT does not overwrite those when calling this func)
       assert extractor.do_normalize is False
       assert extractor.do_rescale is True
       assert extractor.rescale_factor == 1 / 255

       # zero-centering = True in original implementation
       assert extractor.do_zero_centering is True

       return extractor







def 		_snake_case(						SCREAMING_SNAKE_CASE__       )				->					Optional[Any]:
       lowercase							:  Optional[int] 			=   '''checkpoint'''

       if not os.path.exists(SCREAMING_SNAKE_CASE__       ):
              download_checkpoint(SCREAMING_SNAKE_CASE__       )

       lowercase							:  List[str] 			=   restore_checkpoint(SCREAMING_SNAKE_CASE__      ,			SCREAMING_SNAKE_CASE__       )
       lowercase							:  int 			=   transform_state(SCREAMING_SNAKE_CASE__      ,			classification_head=SCREAMING_SNAKE_CASE__       )

       lowercase							:  Optional[int] 			=   get_vivit_config()

       assert config.image_size == 224
       assert config.num_frames == 32

       lowercase							:  Tuple 			=   VivitForVideoClassification(SCREAMING_SNAKE_CASE__       )
       model.load_state_dict(SCREAMING_SNAKE_CASE__       )
       model.eval()

       lowercase							:  Tuple 			=   get_processor()

       lowercase							:  Tuple 			=   prepare_video()
       lowercase							:  Optional[int] 			=   extractor(SCREAMING_SNAKE_CASE__      ,			return_tensors="""pt"""       )

       lowercase							:  Dict 			=   model(**SCREAMING_SNAKE_CASE__       )

       lowercase							:  Optional[Any] 			=   torch.Size([1, 400]       )
       lowercase							:  Tuple 			=   torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]       )

       assert outputs.logits.shape == expected_shape
       assert torch.allclose(outputs.logits[0, :5]      ,			SCREAMING_SNAKE_CASE__      ,			atol=1e-4       ), outputs.logits[0, :5]

       model.save_pretrained(SCREAMING_SNAKE_CASE__       )
       extractor.save_pretrained(SCREAMING_SNAKE_CASE__       )


if __name__ == "__main__":
  lowercase						:      Optional[int]							=							argparse.ArgumentParser()

  parser.add_argument("""--output_model_name""", """-o""", type=str, help="""Output path for the converted HuggingFace model""")

  lowercase						:      str							=							parser.parse_args()
  convert(args.output_model_name)


import unittest

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


if is_torch_available():
  import torch

  from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer

@require_torch
class __snake_case	(   unittest.TestCase  ):
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  int 			=   XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""   )
           model.to(snake_case   )

           # encoder-decoder outputs
           lowercase							:  List[str] 			=   torch.tensor([[17, 96208, 103471, 2]]   ).to(snake_case   )
           lowercase							:  List[str] 			=   torch.tensor(
               [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]   ).to(snake_case   )
           lowercase							:  str 			=   model(
               input_ids=snake_case	,attention_mask=snake_case	,encoder_outputs=snake_case	,decoder_input_ids=snake_case   )
           lowercase							:  Tuple 			=   output[0]
           lowercase							:  int 			=   torch.Size((1, 14, 250012)   )
           self.assertEqual(output_predited_logis.shape	,snake_case   )
           lowercase							:  Union[str, Any] 			=   torch.tensor(
               [[[-6.3_986, -8.2_391, 12.5_189], [-6.3_289, -8.0_864, 12.6_211], [-6.2_418, -8.0_445, 12.7_968]]]   ).to(snake_case   )
           self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,snake_case	,atol=1e-4   )   )

           # encoder outputs
           lowercase							:  Tuple 			=   model.prophetnet.encoder(snake_case   )[0]
           lowercase							:  Any 			=   torch.tensor(
               [[[-1.4_260, -0.7_628, 0.8_453], [-1.4_719, -0.1_391, 0.7_807], [-1.7_678, 0.0_114, 0.4_646]]]   ).to(snake_case   )
           lowercase							:  Optional[Any] 			=   torch.Size((1, 4, 1024)   )
           self.assertEqual(encoder_outputs.shape	,snake_case   )
           self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]	,snake_case	,atol=1e-4   )   )

           # decoder outputs
           lowercase							:  Tuple 			=   model.prophetnet.decoder(
               snake_case	,encoder_hidden_states=snake_case	,)
           lowercase							:  Optional[int] 			=   decoder_outputs[1].view(1	,model.config.ngram	,14	,-1   )
           lowercase							:  Optional[int] 			=   model.lm_head(snake_case   )
           lowercase							:  List[Any] 			=   predicting_streams_logits[:, 0]
           self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]	,snake_case	,atol=1e-4   )   )
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Optional[Any] 			=   XLMProphetNetForConditionalGeneration.from_pretrained(
               """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )
           model.to(snake_case   )

           lowercase							:  Optional[int] 			=   torch.tensor([[17, 96208, 103471, 2]]   ).to(snake_case   )
           lowercase							:  Dict 			=   torch.tensor(
               [[2, 250, 9953, 34, 69489, 1620, 32, 118424, 624, 210, 105, 2913, 1032, 351]]   ).to(snake_case   )
           lowercase							:  Any 			=   model(
               input_ids=snake_case	,attention_mask=snake_case	,encoder_outputs=snake_case	,decoder_input_ids=snake_case   )
           lowercase							:  Optional[int] 			=   output[0]
           lowercase							:  Dict 			=   torch.Size((1, 14, 250012)   )
           self.assertEqual(output_predited_logis.shape	,snake_case   )
           # compare the actual values for a slice.
           lowercase							:  int 			=   torch.tensor(
               [[[-9.2_253, -9.7_173, -6.3_529], [-7.6_701, -9.0_145, -1.9_382], [-8.0_195, -7.0_004, -0.1_523]]]   ).to(snake_case   )

           self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,snake_case	,atol=1e-4   )   )
    @slow
    def    _SCREAMING_SNAKE_CASE (						self   ):



           '''simple docstring'''







           lowercase							:  Any 			=   XLMProphetNetForConditionalGeneration.from_pretrained(
               """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )
           model.to(snake_case   )
           lowercase							:  Optional[int] 			=   512

           lowercase							:  List[Any] 			=   XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""   )

           lowercase							:  int 			=   (
               """Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"""
               """ January 14, 2020, according to the official portal of the organization. From that day, users of this"""
               """ system will not be able to receive security updates, which could make their computers vulnerable to"""
               """ cyber attacks."""
           )
           lowercase							:  List[str] 			=   (
               """орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"""
               """ после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"""
               """ этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"""
               """ к кибератакам."""
           )
           lowercase							:  str 			=   (
               """根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"""
           )

           lowercase							:  Tuple 			=   tokenizer(
               [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]	,padding=snake_case	,max_length=255	,return_tensors="""pt"""   ).input_ids
           lowercase							:  Union[str, Any] 			=   input_ids.to(snake_case   )

           lowercase							:  Dict 			=   model.generate(
               snake_case	,num_beams=10	,length_penalty=1.0	,no_repeat_ngram_size=3	,early_stopping=snake_case   )
           lowercase							:  Any 			=   [tokenizer.decode(snake_case	,skip_special_tokens=snake_case   ) for g in summary_ids]
           lowercase							:  Union[str, Any] 			=   """Microsoft to end Windows 7 free support after January 14, 2020"""
           lowercase							:  Tuple 			=   """Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"""
           lowercase							:  Dict 			=   """微软打算终止对Windows 7操作系统的免费支持"""
           self.assertListEqual(
               [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]	,snake_case	,)

           lowercase							:  int 			=   model.generate(
               snake_case	,num_beams=1	,length_penalty=1.0	,no_repeat_ngram_size=3	,early_stopping=snake_case   )
           lowercase							:  List[Any] 			=   [
               tokenizer.convert_ids_to_tokens(snake_case	,skip_special_tokens=snake_case   ) for g in summary_ids_beama
           ]
           lowercase							:  List[str] 			=   """▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7""".split(""" """   )
           lowercase							:  Optional[Any] 			=   """▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года""".split(
               """ """   )
           lowercase							:  Optional[Any] 			=   """微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持""".split(""" """   )
           self.assertListEqual(
               [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]	,snake_case	,)
