



'''simple docstring'''





import argparse
import json

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    VideoMAEConfig,
    VideoMAEForPreTraining,
    VideoMAEForVideoClassification,
    VideoMAEImageProcessor,
)





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[Any]:
      snake_case__  :    Union[str, Any]    						=      VideoMAEConfig()

      set_architecture_configs(_lowerCAmelCase     ,   _lowerCAmelCase		)

      if "finetuned" not in model_name:
            snake_case__  :    Tuple    						=      False

      if "finetuned" in model_name:
            snake_case__  :    Any    						=      """huggingface/label-files"""
            if "kinetics" in model_name:
                  snake_case__  :    Union[str, Any]    						=      400
                  snake_case__  :    Tuple    						=      """kinetics400-id2label.json"""
            elif "ssv2" in model_name:
                  snake_case__  :    Optional[Any]    						=      174
                  snake_case__  :    List[str]    						=      """something-something-v2-id2label.json"""
            else:
                  raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned."""		)
            snake_case__  :    Any    						=      json.load(open(hf_hub_download(_lowerCAmelCase     ,   _lowerCAmelCase     ,   repo_type="""dataset"""		)     ,   """r"""		)		)
            snake_case__  :    Optional[Any]    						=      {int(_lowerCAmelCase		): v for k, v in idalabel.items()}
            snake_case__  :    str    						=      idalabel
            snake_case__  :    List[Any]    						=      {v: k for k, v in idalabel.items()}

      return config





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> str:
      if "small" in model_name:
            snake_case__  :    Any    						=      384
            snake_case__  :    Optional[int]    						=      1_536
            snake_case__  :    Optional[int]    						=      12
            snake_case__  :    Dict    						=      16
            snake_case__  :    Optional[Any]    						=      12
            snake_case__  :    Union[str, Any]    						=      3
            snake_case__  :    str    						=      192
            snake_case__  :    List[str]    						=      768
      elif "large" in model_name:
            snake_case__  :    Optional[int]    						=      1_024
            snake_case__  :    Optional[Any]    						=      4_096
            snake_case__  :    str    						=      24
            snake_case__  :    Optional[Any]    						=      16
            snake_case__  :    int    						=      12
            snake_case__  :    Tuple    						=      8
            snake_case__  :    List[Any]    						=      512
            snake_case__  :    Union[str, Any]    						=      2_048
      elif "huge" in model_name:
            snake_case__  :    Optional[int]    						=      1_280
            snake_case__  :    Tuple    						=      5_120
            snake_case__  :    Dict    						=      32
            snake_case__  :    Tuple    						=      16
            snake_case__  :    Tuple    						=      12
            snake_case__  :    Tuple    						=      8
            snake_case__  :    Union[str, Any]    						=      640
            snake_case__  :    Optional[Any]    						=      2_560
      elif "base" not in model_name:
            raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\""""		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      if "encoder." in name:
            snake_case__  :    int    						=      name.replace("""encoder."""     ,   """"""		)
      if "cls_token" in name:
            snake_case__  :    Any    						=      name.replace("""cls_token"""     ,   """videomae.embeddings.cls_token"""		)
      if "decoder_pos_embed" in name:
            snake_case__  :    Tuple    						=      name.replace("""decoder_pos_embed"""     ,   """decoder.decoder_pos_embed"""		)
      if "pos_embed" in name and "decoder" not in name:
            snake_case__  :    str    						=      name.replace("""pos_embed"""     ,   """videomae.embeddings.position_embeddings"""		)
      if "patch_embed.proj" in name:
            snake_case__  :    Optional[int]    						=      name.replace("""patch_embed.proj"""     ,   """videomae.embeddings.patch_embeddings.projection"""		)
      if "patch_embed.norm" in name:
            snake_case__  :    int    						=      name.replace("""patch_embed.norm"""     ,   """videomae.embeddings.norm"""		)
      if "decoder.blocks" in name:
            snake_case__  :    List[Any]    						=      name.replace("""decoder.blocks"""     ,   """decoder.decoder_layers"""		)
      if "blocks" in name:
            snake_case__  :    Optional[Any]    						=      name.replace("""blocks"""     ,   """videomae.encoder.layer"""		)
      if "attn.proj" in name:
            snake_case__  :    Any    						=      name.replace("""attn.proj"""     ,   """attention.output.dense"""		)
      if "attn" in name and "bias" not in name:
            snake_case__  :    List[Any]    						=      name.replace("""attn"""     ,   """attention.self"""		)
      if "attn" in name:
            snake_case__  :    List[str]    						=      name.replace("""attn"""     ,   """attention.attention"""		)
      if "norm1" in name:
            snake_case__  :    Dict    						=      name.replace("""norm1"""     ,   """layernorm_before"""		)
      if "norm2" in name:
            snake_case__  :    List[Any]    						=      name.replace("""norm2"""     ,   """layernorm_after"""		)
      if "mlp.fc1" in name:
            snake_case__  :    List[Any]    						=      name.replace("""mlp.fc1"""     ,   """intermediate.dense"""		)
      if "mlp.fc2" in name:
            snake_case__  :    Any    						=      name.replace("""mlp.fc2"""     ,   """output.dense"""		)
      if "decoder_embed" in name:
            snake_case__  :    str    						=      name.replace("""decoder_embed"""     ,   """decoder.decoder_embed"""		)
      if "decoder_norm" in name:
            snake_case__  :    Dict    						=      name.replace("""decoder_norm"""     ,   """decoder.decoder_norm"""		)
      if "decoder_pred" in name:
            snake_case__  :    Any    						=      name.replace("""decoder_pred"""     ,   """decoder.decoder_pred"""		)
      if "norm.weight" in name and "decoder" not in name and "fc" not in name:
            snake_case__  :    int    						=      name.replace("""norm.weight"""     ,   """videomae.layernorm.weight"""		)
      if "norm.bias" in name and "decoder" not in name and "fc" not in name:
            snake_case__  :    Tuple    						=      name.replace("""norm.bias"""     ,   """videomae.layernorm.bias"""		)
      if "head" in name and "decoder" not in name:
            snake_case__  :    Any    						=      name.replace("""head"""     ,   """classifier"""		)

      return name





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> List[Any]:
      for key in orig_state_dict.copy().keys():
            snake_case__  :    str    						=      orig_state_dict.pop(_lowerCAmelCase		)

            if key.startswith("""encoder."""		):
                  snake_case__  :    Dict    						=      key.replace("""encoder."""     ,   """"""		)

            if "qkv" in key:
                  snake_case__  :    Tuple    						=      key.split("""."""		)
                  if key.startswith("""decoder.blocks"""		):
                        snake_case__  :    Optional[Any]    						=      config.decoder_hidden_size
                        snake_case__  :    Optional[int]    						=      int(key_split[2]		)
                        snake_case__  :    Any    						=      """decoder.decoder_layers."""
                        if "weight" in key:
                              snake_case__  :    str    						=      val[:dim, :]
                              snake_case__  :    Dict    						=      val[dim : dim * 2, :]
                              snake_case__  :    List[str]    						=      val[-dim:, :]
                  else:
                        snake_case__  :    List[str]    						=      config.hidden_size
                        snake_case__  :    List[str]    						=      int(key_split[1]		)
                        snake_case__  :    int    						=      """videomae.encoder.layer."""
                        if "weight" in key:
                              snake_case__  :    Optional[int]    						=      val[:dim, :]
                              snake_case__  :    Optional[int]    						=      val[dim : dim * 2, :]
                              snake_case__  :    Tuple    						=      val[-dim:, :]
            else:
                  snake_case__  :    List[Any]    						=      val

      return orig_state_dict





def 						__snake_case(				)		-> Any:
      snake_case__  :    List[Any]    						=      hf_hub_download(
          repo_id="""hf-internal-testing/spaghetti-video"""     ,   filename="""eating_spaghetti.npy"""     ,   repo_type="""dataset"""		)
      snake_case__  :    List[str]    						=      np.load(_lowerCAmelCase		)
      return list(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)		-> List[Any]:
      snake_case__  :    Optional[Any]    						=      get_videomae_config(_lowerCAmelCase		)

      if "finetuned" in model_name:
            snake_case__  :    Tuple    						=      VideoMAEForVideoClassification(_lowerCAmelCase		)
      else:
            snake_case__  :    str    						=      VideoMAEForPreTraining(_lowerCAmelCase		)

      # download original checkpoint, hosted on Google Drive
      snake_case__  :    Dict    						=      """pytorch_model.bin"""
      gdown.cached_download(_lowerCAmelCase     ,   _lowerCAmelCase     ,   quiet=_lowerCAmelCase		)
      snake_case__  :    Optional[Any]    						=      torch.load(_lowerCAmelCase     ,   map_location="""cpu"""		)
      if "model" in files:
            snake_case__  :    int    						=      files["""model"""]
      else:
            snake_case__  :    Tuple    						=      files["""module"""]
      snake_case__  :    Optional[int]    						=      convert_state_dict(_lowerCAmelCase     ,   _lowerCAmelCase		)

      model.load_state_dict(_lowerCAmelCase		)
      model.eval()

      # verify model on basic input
      snake_case__  :    str    						=      VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5]     ,   image_std=[0.5, 0.5, 0.5]		)
      snake_case__  :    int    						=      prepare_video()
      snake_case__  :    int    						=      image_processor(_lowerCAmelCase     ,   return_tensors="""pt"""		)

      if "finetuned" not in model_name:
            snake_case__  :    Optional[int]    						=      hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos"""     ,   filename="""bool_masked_pos.pt"""		)
            snake_case__  :    Dict    						=      torch.load(_lowerCAmelCase		)

      snake_case__  :    int    						=      model(**_lowerCAmelCase		)
      snake_case__  :    str    						=      outputs.logits

      snake_case__  :    Union[str, Any]    						=      [
          """videomae-small-finetuned-kinetics""",
          """videomae-small-finetuned-ssv2""",
          # Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
          """videomae-base-short""",
          """videomae-base-short-finetuned-kinetics""",
          """videomae-base""",
          """videomae-base-finetuned-kinetics""",
          """videomae-large""",
          """videomae-large-finetuned-kinetics""",
          """videomae-huge-finetuned-kinetics""",
          # Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
          """videomae-base-short-ssv2""",
          """videomae-base-short-finetuned-ssv2""",
          """videomae-base-ssv2""",
          """videomae-base-finetuned-ssv2""",
      ]

      # NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
      if model_name == "videomae-small-finetuned-kinetics":
            snake_case__  :    str    						=      torch.Size([1, 400]		)
            snake_case__  :    Union[str, Any]    						=      torch.tensor([-0.9291, -0.4061, -0.9307]		)
      elif model_name == "videomae-small-finetuned-ssv2":
            snake_case__  :    List[str]    						=      torch.Size([1, 174]		)
            snake_case__  :    List[Any]    						=      torch.tensor([0.2671, -0.4689, -0.8235]		)
      elif model_name == "videomae-base":
            snake_case__  :    Union[str, Any]    						=      torch.Size([1, 1_408, 1_536]		)
            snake_case__  :    int    						=      torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]]		)
      elif model_name == "videomae-base-short":
            snake_case__  :    List[Any]    						=      torch.Size([1, 1_408, 1_536]		)
            snake_case__  :    List[Any]    						=      torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]]		)
            # we verified the loss both for normalized and unnormalized targets for this one
            snake_case__  :    List[Any]    						=      torch.tensor([0.5142]		) if config.norm_pix_loss else torch.tensor([0.6469]		)
      elif model_name == "videomae-large":
            snake_case__  :    Any    						=      torch.Size([1, 1_408, 1_536]		)
            snake_case__  :    Tuple    						=      torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]]		)
      elif model_name == "videomae-large-finetuned-kinetics":
            snake_case__  :    List[Any]    						=      torch.Size([1, 400]		)
            snake_case__  :    int    						=      torch.tensor([0.0771, 0.0011, -0.3625]		)
      elif model_name == "videomae-huge-finetuned-kinetics":
            snake_case__  :    List[Any]    						=      torch.Size([1, 400]		)
            snake_case__  :    str    						=      torch.tensor([0.2433, 0.1632, -0.4894]		)
      elif model_name == "videomae-base-short-finetuned-kinetics":
            snake_case__  :    Dict    						=      torch.Size([1, 400]		)
            snake_case__  :    List[Any]    						=      torch.tensor([0.6588, 0.0990, -0.2493]		)
      elif model_name == "videomae-base-finetuned-kinetics":
            snake_case__  :    Tuple    						=      torch.Size([1, 400]		)
            snake_case__  :    str    						=      torch.tensor([0.3669, -0.0688, -0.2421]		)
      elif model_name == "videomae-base-short-ssv2":
            snake_case__  :    Any    						=      torch.Size([1, 1_408, 1_536]		)
            snake_case__  :    Optional[Any]    						=      torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]]		)
      elif model_name == "videomae-base-short-finetuned-ssv2":
            snake_case__  :    Union[str, Any]    						=      torch.Size([1, 174]		)
            snake_case__  :    Optional[Any]    						=      torch.tensor([-0.0537, -0.1539, -0.3266]		)
      elif model_name == "videomae-base-ssv2":
            snake_case__  :    int    						=      torch.Size([1, 1_408, 1_536]		)
            snake_case__  :    Dict    						=      torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]]		)
      elif model_name == "videomae-base-finetuned-ssv2":
            snake_case__  :    Optional[Any]    						=      torch.Size([1, 174]		)
            snake_case__  :    Dict    						=      torch.tensor([0.1961, -0.8337, -0.6389]		)
      else:
            raise ValueError(f"Model name not supported. Should be one of {model_names}"		)

      # verify logits
      assert logits.shape == expected_shape
      if "finetuned" in model_name:
            assert torch.allclose(logits[0, :3]     ,   _lowerCAmelCase     ,   atol=1e-4		)
      else:
            print("""Logits:"""     ,   logits[0, :3, :3]		)
            assert torch.allclose(logits[0, :3, :3]     ,   _lowerCAmelCase     ,   atol=1e-4		)
      print("""Logits ok!"""		)

      # verify loss, if applicable
      if model_name == "videomae-base-short":
            snake_case__  :    Any    						=      outputs.loss
            assert torch.allclose(_lowerCAmelCase     ,   _lowerCAmelCase     ,   atol=1e-4		)
            print("""Loss ok!"""		)

      if pytorch_dump_folder_path is not None:
            print(f"Saving model and image processor to {pytorch_dump_folder_path}"		)
            image_processor.save_pretrained(_lowerCAmelCase		)
            model.save_pretrained(_lowerCAmelCase		)

      if push_to_hub:
            print("""Pushing to the hub..."""		)
            model.push_to_hub(_lowerCAmelCase     ,   organization="""nielsr"""		)


if __name__ == "__main__":
       __a          =		argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           "--checkpoint_url",
           default="https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&amp;export=download&amp;confirm=t&amp;uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4",
           type=str,
           help=(
               "URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct"
               " download link."
           ),
       )
       parser.add_argument(
           "--pytorch_dump_folder_path",
           default="/Users/nielsrogge/Documents/VideoMAE/Test",
           type=str,
           help="Path to the output PyTorch model directory.",
       )
       parser.add_argument("--model_name", default="videomae-base", type=str, help="Name of the model.")
       parser.add_argument(
           "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
       )

       __a          =		parser.parse_args()
       convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)





'''simple docstring'''





import argparse
import json
import os

import fairseq
import torch
from torch import nn

from transformers import (
    SpeechaTextaConfig,
    SpeechaTextaForCausalLM,
    SpeechaTextaTokenizer,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


logging.set_verbosity_info()
__a          =		logging.get_logger(__name__)

__a          =		{
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "self_attn.k_proj": "encoder.layers.*.attention.k_proj",
    "self_attn.v_proj": "encoder.layers.*.attention.v_proj",
    "self_attn.q_proj": "encoder.layers.*.attention.q_proj",
    "self_attn.out_proj": "encoder.layers.*.attention.out_proj",
    "self_attn_layer_norm": "encoder.layers.*.layer_norm",
    "fc1": "encoder.layers.*.feed_forward.intermediate_dense",
    "fc2": "encoder.layers.*.feed_forward.output_dense",
    "final_layer_norm": "encoder.layers.*.final_layer_norm",
    "encoder.layer_norm": "encoder.layer_norm",
    "w2v_model.layer_norm": "feature_projection.layer_norm",
    "quantizer.weight_proj": "quantizer.weight_proj",
    "quantizer.vars": "quantizer.codevectors",
    "project_q": "project_q",
    "final_proj": "project_hid",
    "w2v_encoder.proj": "lm_head",
    "mask_emb": "masked_spec_embed",
}
__a          =		[
    "lm_head",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
]





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)		-> Union[str, Any]:
      for attribute in key.split("""."""		):
            snake_case__  :    Dict    						=      getattr(_lowerCAmelCase     ,   _lowerCAmelCase		)

      if weight_type is not None:
            snake_case__  :    List[Any]    						=      getattr(_lowerCAmelCase     ,   _lowerCAmelCase		).shape
      else:
            snake_case__  :    Union[str, Any]    						=      hf_pointer.shape

      assert hf_shape == value.shape, (
          f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
          f" {value.shape} for {full_name}"
      )

      if weight_type == "weight":
            snake_case__  :    int    						=      value
      elif weight_type == "weight_g":
            snake_case__  :    List[str]    						=      value
      elif weight_type == "weight_v":
            snake_case__  :    List[str]    						=      value
      elif weight_type == "bias":
            snake_case__  :    Optional[Any]    						=      value
      else:
            snake_case__  :    str    						=      value

      logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}."		)





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase		)		-> Any:
      snake_case__  :    Union[str, Any]    						=      []
      snake_case__  :    Dict    						=      fairseq_model.state_dict()

      snake_case__  :    List[Any]    						=      hf_model.feature_extractor

      # if encoder has different dim to decoder -> use proj_weight
      snake_case__  :    Optional[int]    						=      None

      for name, value in fairseq_dict.items():
            snake_case__  :    List[Any]    						=      False
            if "conv_layers" in name:
                  load_conv_layer(
                      _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   hf_model.config.feat_extract_norm == """group"""     ,   )
                  snake_case__  :    Union[str, Any]    						=      True
            elif name.split("""."""		)[0] == "proj":
                  snake_case__  :    Tuple    						=      fairseq_model.proj
                  snake_case__  :    int    						=      True
            else:
                  for key, mapped_key in MAPPING.items():
                        if key in name or key.split("""w2v_model."""		)[-1] == name.split("""."""		)[0]:
                              snake_case__  :    Optional[Any]    						=      True
                              if "*" in mapped_key:
                                    snake_case__  :    Optional[int]    						=      name.split(_lowerCAmelCase		)[0].split("""."""		)[-2]
                                    snake_case__  :    Tuple    						=      mapped_key.replace("""*"""     ,   _lowerCAmelCase		)
                              if "weight_g" in name:
                                    snake_case__  :    str    						=      """weight_g"""
                              elif "weight_v" in name:
                                    snake_case__  :    int    						=      """weight_v"""
                              elif "bias" in name:
                                    snake_case__  :    Dict    						=      """bias"""
                              elif "weight" in name:
                                    snake_case__  :    Union[str, Any]    						=      """weight"""
                              else:
                                    snake_case__  :    Union[str, Any]    						=      None
                              set_recursively(_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)
                        continue
            if not is_used:
                  unused_weights.append(_lowerCAmelCase		)

      logger.warning(f"Unused weights: {unused_weights}"		)

      return proj_weight





def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase		)		-> Dict:
      snake_case__  :    int    						=      full_name.split("""conv_layers."""		)[-1]
      snake_case__  :    Dict    						=      name.split("""."""		)
      snake_case__  :    Any    						=      int(items[0]		)
      snake_case__  :    Optional[Any]    						=      int(items[1]		)

      if type_id == 0:
            if "bias" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
                      f"{full_name} has size {value.shape}, but"
                      f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
                  )
                  snake_case__  :    int    						=      value
                  logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."		)
            elif "weight" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
                      f"{full_name} has size {value.shape}, but"
                      f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
                  )
                  snake_case__  :    str    						=      value
                  logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."		)
      elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
            if "bias" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
                      f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
                      " found."
                  )
                  snake_case__  :    Union[str, Any]    						=      value
                  logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."		)
            elif "weight" in name:
                  assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
                      f"{full_name} has size {value.shape}, but"
                      f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
                  )
                  snake_case__  :    int    						=      value
                  logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."		)
      else:
            unused_weights.append(_lowerCAmelCase		)





def 						__snake_case(				_lowerCAmelCase		)		-> List[str]:
      snake_case__						,				snake_case__  :    str    						=      emb.weight.shape
      snake_case__  :    List[str]    						=      nn.Linear(_lowerCAmelCase     ,   _lowerCAmelCase     ,   bias=_lowerCAmelCase		)
      snake_case__  :    List[str]    						=      emb.weight.data
      return lin_layer





def 						__snake_case(				_lowerCAmelCase		)		-> Optional[Any]:
      with open(_lowerCAmelCase     ,   """r"""     ,   encoding="""utf-8"""		) as f:
            snake_case__  :    int    						=      f.readlines()
            snake_case__  :    List[Any]    						=      [line.split(""" """		)[0] for line in lines]

      snake_case__  :    Union[str, Any]    						=      len(_lowerCAmelCase		)

      snake_case__  :    Any    						=      {
          """<s>""": 0,
          """<pad>""": 1,
          """</s>""": 2,
          """<unk>""": 3,
      }

      vocab_dict.update(dict(zip(_lowerCAmelCase     ,   range(4     ,   num_words + 4		)		)		)		)
      return vocab_dict





@torch.no_grad()
def 						__snake_case(				_lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   _lowerCAmelCase     ,   )		-> int:
      snake_case__  :    Optional[Any]    						=      WavaVecaConfig.from_pretrained(_lowerCAmelCase		)
      snake_case__  :    Optional[Any]    						=      SpeechaTextaConfig.from_pretrained(
          _lowerCAmelCase     ,   vocab_size=_lowerCAmelCase     ,   decoder_layers=_lowerCAmelCase     ,   do_stable_layer_norm=_lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      WavaVecaFeatureExtractor(
          feature_size=1     ,   sampling_rate=16_000     ,   padding_value=0     ,   do_normalize=_lowerCAmelCase     ,   return_attention_mask=_lowerCAmelCase     ,   )

      snake_case__						,				snake_case__						,				snake_case__  :    Union[str, Any]    						=      fairseq.checkpoint_utils.load_model_ensemble_and_task(
          [checkpoint_path]     ,   arg_overrides={"""data""": """/""".join(dict_path.split("""/"""		)[:-1]		)}		)
      snake_case__  :    Tuple    						=      model[0].eval()

      # set weights for wav2vec2 encoder
      snake_case__  :    Optional[Any]    						=      WavaVecaModel(_lowerCAmelCase		)
      snake_case__  :    Dict    						=      recursively_load_weights_wavaveca(model.encoder     ,   _lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      SpeechaTextaForCausalLM(_lowerCAmelCase		)
      snake_case__						,				snake_case__  :    Tuple    						=      hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()     ,   strict=_lowerCAmelCase		)

      # set output linear layer
      unexpected_keys.remove("""embed_out"""		)
      snake_case__  :    Tuple    						=      nn.Parameter(model.decoder.embed_out.detach()		)

      # layer norm is init to identity matrix so leaving it is fine
      logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}"		)
      logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}"		)

      snake_case__  :    List[Any]    						=      SpeechEncoderDecoderModel(encoder=_lowerCAmelCase     ,   decoder=_lowerCAmelCase		)
      snake_case__  :    Tuple    						=      False

      # add projection layer
      snake_case__  :    Union[str, Any]    						=      nn.Parameter(projection_layer.weight		)
      snake_case__  :    int    						=      nn.Parameter(projection_layer.bias		)

      snake_case__  :    Tuple    						=      create_vocab_dict(_lowerCAmelCase		)

      with open(os.path.join(_lowerCAmelCase     ,   """vocab.json"""		)     ,   """w"""		) as fp:
            json.dump(_lowerCAmelCase     ,   _lowerCAmelCase		)

      snake_case__  :    Tuple    						=      SpeechaTextaTokenizer(os.path.join(_lowerCAmelCase     ,   """vocab.json"""		)		)
      tokenizer.save_pretrained(_lowerCAmelCase		)

      snake_case__  :    Optional[Any]    						=      hf_wavavec.config.to_dict()
      snake_case__  :    Tuple    						=      tokenizer.pad_token_id
      snake_case__  :    Optional[Any]    						=      tokenizer.bos_token_id
      snake_case__  :    int    						=      tokenizer.eos_token_id
      snake_case__  :    str    						=      """speech_to_text_2"""
      snake_case__  :    List[Any]    						=      """wav2vec2"""

      snake_case__  :    List[str]    						=      SpeechEncoderDecoderConfig.from_dict(_lowerCAmelCase		)

      hf_wavavec.save_pretrained(_lowerCAmelCase		)
      feature_extractor.save_pretrained(_lowerCAmelCase		)


if __name__ == "__main__":
       __a          =		argparse.ArgumentParser()
       parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.")
       parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint")
       parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model")
       parser.add_argument(
           "--encoder_config_path",
           default="facebook/wav2vec2-large-lv60",
           type=str,
           help="Path to hf encoder wav2vec2 checkpoint config",
       )
       parser.add_argument(
           "--decoder_config_path",
           default="facebook/s2t-small-mustc-en-fr-st",
           type=str,
           help="Path to hf decoder s2t checkpoint config",
       )
       parser.add_argument("--vocab_size", default=1_0224, type=int, help="Vocab size of decoder")
       parser.add_argument("--num_decoder_layers", default=7, type=int, help="Number of decoder layers")

       __a          =		parser.parse_args()
       convert_wavaveca_checkpoint(
           args.checkpoint_path,
           args.pytorch_dump_folder_path,
           args.dict_path,
           encoder_config_path=args.encoder_config_path,
           decoder_config_path=args.decoder_config_path,
           vocab_size=args.vocab_size,
           num_decoder_layers=args.num_decoder_layers,
       )
