




"""simple docstring"""







import operator as op


_UpperCamelCase					      =  """scaler.pt"""
_UpperCamelCase					      =  """pytorch_model"""
_UpperCamelCase					      =  """random_states"""
_UpperCamelCase					      =  """optimizer"""
_UpperCamelCase					      =  """scheduler"""
_UpperCamelCase					      =  """pytorch_model.bin"""
_UpperCamelCase					      =  """pytorch_model.bin.index.json"""
_UpperCamelCase					      =  """model.safetensors"""
_UpperCamelCase					      =  """model.safetensors.index.json"""
_UpperCamelCase					      =  """1.10.2"""
_UpperCamelCase					      =  """py38"""
_UpperCamelCase					      =  """4.17.0"""
_UpperCamelCase					      =  ["""ml.p3.16xlarge""", """ml.p3dn.24xlarge""", """ml.p4dn.24xlarge"""]
_UpperCamelCase					      =  ["""FULL_SHARD""", """SHARD_GRAD_OP""", """NO_SHARD""", """HYBRID_SHARD""", """HYBRID_SHARD_ZERO2"""]
_UpperCamelCase					      =  ["""TRANSFORMER_BASED_WRAP""", """SIZE_BASED_WRAP""", """NO_WRAP"""]
_UpperCamelCase					      =  ["""BACKWARD_PRE""", """BACKWARD_POST""", """NO_PREFETCH"""]
_UpperCamelCase					      =  ["""FULL_STATE_DICT""", """LOCAL_STATE_DICT""", """SHARDED_STATE_DICT"""]
_UpperCamelCase					      =  """2.0.1"""
_UpperCamelCase					      =  ["""pdsh""", """standard""", """openmpi""", """mvapich"""]
_UpperCamelCase					      =  ["""default""", """reduce-overhead""", """max-autotune"""]

_UpperCamelCase					      =  {""">""": op.gt, """>=""": op.ge, """==""": op.eq, """!=""": op.ne, """<=""": op.le, """<""": op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
_UpperCamelCase					      =  [
    """nnodes""",
    """nproc_per_node""",
    """rdzv_backend""",
    """rdzv_endpoint""",
    """rdzv_id""",
    """rdzv_conf""",
    """standalone""",
    """max_restarts""",
    """monitor_interval""",
    """start_method""",
    """role""",
    """module""",
    """m""",
    """no_python""",
    """run_path""",
    """log_dir""",
    """r""",
    """redirects""",
    """t""",
    """tee""",
    """node_rank""",
    """master_addr""",
    """master_port""",
]

_UpperCamelCase					      =  ["""DEEPSPEED""", """MULTI_GPU""", """FSDP""", """MEGATRON_LM"""]
_UpperCamelCase					      =  ["""DEEPSPEED""", """MULTI_XPU""", """FSDP"""]











"""simple docstring"""







import argparse
import re

import torch
from CLAP import create_model

from transformers import AutoFeatureExtractor, ClapConfig, ClapModel


_UpperCamelCase					      =  {
    """text_branch""": """text_model""",
    """audio_branch""": """audio_model.audio_encoder""",
    """attn""": """attention.self""",
    """self.proj""": """output.dense""",
    """attention.self_mask""": """attn_mask""",
    """mlp.fc1""": """intermediate.dense""",
    """mlp.fc2""": """output.dense""",
    """norm1""": """layernorm_before""",
    """norm2""": """layernorm_after""",
    """bn0""": """batch_norm""",
}

_UpperCamelCase					      =  AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""")

def _a			(		_snake_case				,	_snake_case=False							):







      """simple docstring"""






      UpperCAmelCase      , UpperCAmelCase          =	create_model(
          """HTSAT-tiny"""				,	"""roberta"""				,	_snake_case				,	precision="""fp32"""				,	device="""cuda:0""" if torch.cuda.is_available() else """cpu"""				,	enable_fusion=_snake_case				,	fusion_type="""aff_2d""" if enable_fusion else None				,	)
      return model, model_cfg

def _a			(		_snake_case							):







      """simple docstring"""






      UpperCAmelCase          =	{}

      UpperCAmelCase          =	R""".*sequential.(\d+).*"""
      UpperCAmelCase          =	R""".*_projection.(\d+).*"""

      for key, value in state_dict.items():
            # check if any key needs to be modified
            for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
                  if key_to_modify in key:
                        UpperCAmelCase          =	key.replace(_snake_case				,	_snake_case							)

            if re.match(_snake_case				,	_snake_case							):
                  # replace sequential layers with list
                  UpperCAmelCase          =	re.match(_snake_case				,	_snake_case							).group(1							)

                  UpperCAmelCase          =	key.replace(F'''sequential.{sequential_layer}.'''				,	F'''layers.{int(_snake_case							)//3}.linear.'''							)
            elif re.match(_snake_case				,	_snake_case							):
                  UpperCAmelCase          =	int(re.match(_snake_case				,	_snake_case							).group(1							)							)

                  # Because in CLAP they use `nn.Sequential`...
                  UpperCAmelCase          =	1 if projecton_layer == 0 else 2

                  UpperCAmelCase          =	key.replace(F'''_projection.{projecton_layer}.'''				,	F'''_projection.linear{transformers_projection_layer}.'''							)

            if "audio" and "qkv" in key:
                  # split qkv into query key and value
                  UpperCAmelCase          =	value
                  UpperCAmelCase          =	mixed_qkv.size(0							) // 3

                  UpperCAmelCase          =	mixed_qkv[:qkv_dim]
                  UpperCAmelCase          =	mixed_qkv[qkv_dim : qkv_dim * 2]
                  UpperCAmelCase          =	mixed_qkv[qkv_dim * 2 :]

                  UpperCAmelCase          =	query_layer
                  UpperCAmelCase          =	key_layer
                  UpperCAmelCase          =	value_layer
            else:
                  UpperCAmelCase          =	value

      return model_state_dict

def _a			(		_snake_case				,	_snake_case				,	_snake_case				,	_snake_case=False							):







      """simple docstring"""






      UpperCAmelCase      , UpperCAmelCase          =	init_clap(_snake_case				,	enable_fusion=_snake_case							)

      clap_model.eval()
      UpperCAmelCase          =	clap_model.state_dict()
      UpperCAmelCase          =	rename_state_dict(_snake_case							)

      UpperCAmelCase          =	ClapConfig()
      UpperCAmelCase          =	enable_fusion
      UpperCAmelCase          =	ClapModel(_snake_case							)

      # ignore the spectrogram embedding layer
      model.load_state_dict(_snake_case				,	strict=_snake_case							)

      model.save_pretrained(_snake_case							)
      transformers_config.save_pretrained(_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("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
  parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""")
  _UpperCamelCase					      =  parser.parse_args()

  convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)



