


from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
  from ...processing_utils import ProcessorMixin
  from ...utils import TensorType


UpperCAmelCase    =					logging.get_logger(__name__)

UpperCAmelCase    =					{
    """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""",
}







class lowerCAmelCase_		(				lowerCamelCase__ ):

 '''simple docstring'''

 __snake_case				=						"layoutlmv3"



 def __init__(			self	,   _UpperCAmelCase=5_02_65	,   _UpperCAmelCase=7_68	,   _UpperCAmelCase=12	,   _UpperCAmelCase=12	,   _UpperCAmelCase=30_72	,   _UpperCAmelCase="gelu"	,   _UpperCAmelCase=0.1	,   _UpperCAmelCase=0.1	,   _UpperCAmelCase=5_12	,   _UpperCAmelCase=2	,   _UpperCAmelCase=0.02	,   _UpperCAmelCase=1E-5	,   _UpperCAmelCase=1	,   _UpperCAmelCase=0	,   _UpperCAmelCase=2	,   _UpperCAmelCase=10_24	,   _UpperCAmelCase=1_28	,   _UpperCAmelCase=1_28	,   _UpperCAmelCase=True	,   _UpperCAmelCase=32	,   _UpperCAmelCase=1_28	,   _UpperCAmelCase=64	,   _UpperCAmelCase=2_56	,   _UpperCAmelCase=True	,   _UpperCAmelCase=True	,   _UpperCAmelCase=True	,   _UpperCAmelCase=2_24	,   _UpperCAmelCase=3	,   _UpperCAmelCase=16	,   _UpperCAmelCase=None	,   **_UpperCAmelCase	,   ):
       super().__init__(
           vocab_size=_UpperCAmelCase	,   hidden_size=_UpperCAmelCase	,   num_hidden_layers=_UpperCAmelCase	,   num_attention_heads=_UpperCAmelCase	,   intermediate_size=_UpperCAmelCase	,   hidden_act=_UpperCAmelCase	,   hidden_dropout_prob=_UpperCAmelCase	,   attention_probs_dropout_prob=_UpperCAmelCase	,   max_position_embeddings=_UpperCAmelCase	,   type_vocab_size=_UpperCAmelCase	,   initializer_range=_UpperCAmelCase	,   layer_norm_eps=_UpperCAmelCase	,   pad_token_id=_UpperCAmelCase	,   bos_token_id=_UpperCAmelCase	,   eos_token_id=_UpperCAmelCase	,   **_UpperCAmelCase	,   )
       snake_case_ =   max_ad_position_embeddings
       snake_case_ =   coordinate_size
       snake_case_ =   shape_size
       snake_case_ =   has_relative_attention_bias
       snake_case_ =   rel_pos_bins
       snake_case_ =   max_rel_pos
       snake_case_ =   has_spatial_attention_bias
       snake_case_ =   rel_ad_pos_bins
       snake_case_ =   max_rel_ad_pos
       snake_case_ =   text_embed
       snake_case_ =   visual_embed
       snake_case_ =   input_size
       snake_case_ =   num_channels
       snake_case_ =   patch_size
       snake_case_ =   classifier_dropout







class lowerCAmelCase_		(				lowerCamelCase__ ):

 '''simple docstring'''

 __snake_case				=						version.parse("1.12" )



 @property
 def 		UpperCamelCase__  (			self      ):
       # The order of inputs is different for question answering and sequence classification
       if self.task in ["question-answering", "sequence-classification"]:
             return OrderedDict(
                 [
                     ('''input_ids''', {0: '''batch''', 1: '''sequence'''}),
                     ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}),
                     ('''bbox''', {0: '''batch''', 1: '''sequence'''}),
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                 ]      )
       else:
             return OrderedDict(
                 [
                     ('''input_ids''', {0: '''batch''', 1: '''sequence'''}),
                     ('''bbox''', {0: '''batch''', 1: '''sequence'''}),
                     ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}),
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}),
                 ]      )



 @property
 def 		UpperCamelCase__  (			self      ):
       return 1E-5



 @property
 def 		UpperCamelCase__  (			self      ):
       return 12





 def 		UpperCamelCase__  (			self	,   _UpperCAmelCase	,   _UpperCAmelCase = -1	,   _UpperCAmelCase = -1	,   _UpperCAmelCase = False	,   _UpperCAmelCase = None	,   _UpperCAmelCase = 3	,   _UpperCAmelCase = 40	,   _UpperCAmelCase = 40	,   ):
       setattr(processor.image_processor	,   '''apply_ocr'''	,   _UpperCAmelCase      )

       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       snake_case_ =   compute_effective_axis_dimension(
           _UpperCAmelCase	,   fixed_dimension=OnnxConfig.default_fixed_batch	,   num_token_to_add=0      )
       # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
       snake_case_ =   processor.tokenizer.num_special_tokens_to_add(_UpperCAmelCase      )
       snake_case_ =   compute_effective_axis_dimension(
           _UpperCAmelCase	,   fixed_dimension=OnnxConfig.default_fixed_sequence	,   num_token_to_add=_UpperCAmelCase      )
       # Generate dummy inputs according to compute batch and sequence
       snake_case_ =   [[''' '''.join([processor.tokenizer.unk_token]      ) * seq_length]] * batch_size

       # Generate dummy bounding boxes
       snake_case_ =   [[[48, 84, 73, 1_28]]] * batch_size

       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
       snake_case_ =   self._generate_dummy_images(_UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase	,   _UpperCAmelCase      )

       snake_case_ =   dict(
           processor(
               _UpperCAmelCase	,   text=_UpperCAmelCase	,   boxes=_UpperCAmelCase	,   return_tensors=_UpperCAmelCase	,   )      )

       return inputs



import argparse

import fairseq
import torch

from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging


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

UpperCAmelCase    =					{
    """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""",
    """encoder.layer_norm_for_extract""": """layer_norm_for_extract""",
    """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""",
    """label_embs_concat""": """label_embeddings_concat""",
    """mask_emb""": """masked_spec_embed""",
    """spk_proj""": """speaker_proj""",
}
UpperCAmelCase    =					[
    """lm_head""",
    """quantizer.weight_proj""",
    """quantizer.codevectors""",
    """project_q""",
    """project_hid""",
    """label_embeddings_concat""",
    """speaker_proj""",
    """layer_norm_for_extract""",
]






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )->						Tuple:




      """simple docstring"""

      for attribute in key.split('''.'''      ):
            snake_case_ =   getattr(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )

      if weight_type is not None:
            snake_case_ =   getattr(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ).shape
      else:
            snake_case_ =   hf_pointer.shape

      if hf_shape != value.shape:
            raise ValueError(
                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_ =   value
      elif weight_type == "weight_g":
            snake_case_ =   value
      elif weight_type == "weight_v":
            snake_case_ =   value
      elif weight_type == "bias":
            snake_case_ =   value
      else:
            snake_case_ =   value

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






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )->						Any:




      """simple docstring"""

      snake_case_ =   []
      snake_case_ =   fairseq_model.state_dict()

      snake_case_ =   hf_model.unispeech_sat.feature_extractor

      for name, value in fairseq_dict.items():
            snake_case_ =   False
            if "conv_layers" in name:
                  load_conv_layer(
                      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      hf_model.config.feat_extract_norm == '''group'''      ,      )
                  snake_case_ =   True
            else:
                  for key, mapped_key in MAPPING.items():
                        snake_case_ =   '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
                        if key in name or key.split('''w2v_model.'''      )[-1] == name.split('''.'''      )[0]:
                              if "layer_norm_for_extract" in name and (".".join(name.split('''.'''      )[:-1]      ) != key):
                                    # special case since naming is very similar
                                    continue
                              snake_case_ =   True
                              if "*" in mapped_key:
                                    snake_case_ =   name.split(SCREAMING_SNAKE_CASE      )[0].split('''.'''      )[-2]
                                    snake_case_ =   mapped_key.replace('''*'''      ,      SCREAMING_SNAKE_CASE      )
                              if "weight_g" in name:
                                    snake_case_ =   '''weight_g'''
                              elif "weight_v" in name:
                                    snake_case_ =   '''weight_v'''
                              elif "bias" in name:
                                    snake_case_ =   '''bias'''
                              elif "weight" in name:
                                    # TODO: don't match quantizer.weight_proj
                                    snake_case_ =   '''weight'''
                              else:
                                    snake_case_ =   None
                              set_recursively(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )
                        continue
            if not is_used:
                  unused_weights.append(SCREAMING_SNAKE_CASE      )

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






def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )->						Tuple:




      """simple docstring"""

      snake_case_ =   full_name.split('''conv_layers.'''      )[-1]
      snake_case_ =   name.split('''.'''      )
      snake_case_ =   int(items[0]      )
      snake_case_ =   int(items[1]      )

      if type_id == 0:
            if "bias" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape:
                        raise ValueError(
                            f'''{full_name} has size {value.shape}, but'''
                            f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''      )
                  snake_case_ =   value
                  logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''      )
            elif "weight" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape:
                        raise ValueError(
                            f'''{full_name} has size {value.shape}, but'''
                            f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''      )
                  snake_case_ =   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:
                  if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape:
                        raise ValueError(
                            f'''{full_name} has size {value.shape}, but'''
                            f''' {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.'''      )
                  snake_case_ =   value
                  logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''      )
            elif "weight" in name:
                  if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
                        raise ValueError(
                            f'''{full_name} has size {value.shape}, but'''
                            f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''      )
                  snake_case_ =   value
                  logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''      )
      else:
            unused_weights.append(SCREAMING_SNAKE_CASE      )






@torch.no_grad()
def  __lowerCAmelCase					(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE=None      ,      SCREAMING_SNAKE_CASE=None      ,      SCREAMING_SNAKE_CASE=True      )->						Dict:




      """simple docstring"""

      if config_path is not None:
            snake_case_ =   UniSpeechSatConfig.from_pretrained(SCREAMING_SNAKE_CASE      )
      else:
            snake_case_ =   UniSpeechSatConfig()

      snake_case_ =   ''''''

      if is_finetuned:
            snake_case_ =   UniSpeechSatForCTC(SCREAMING_SNAKE_CASE      )
      else:
            snake_case_ =   UniSpeechSatForPreTraining(SCREAMING_SNAKE_CASE      )

      snake_case_ ,					snake_case_ ,					snake_case_ =   fairseq.checkpoint_utils.load_model_ensemble_and_task(
          [checkpoint_path]      ,      arg_overrides={'''data''': '''/'''.join(dict_path.split('''/'''      )[:-1]      )}      )
      snake_case_ =   model[0].eval()

      recursively_load_weights(SCREAMING_SNAKE_CASE      ,      SCREAMING_SNAKE_CASE      )

      hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE      )


if __name__ == "__main__":
   UpperCAmelCase    =					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("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
   parser.add_argument(
       """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
   )
   UpperCAmelCase    =					parser.parse_args()
   convert_unispeech_sat_checkpoint(
       args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
   )