




"""simple docstring"""

import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
  import bitsandbytes as bnb
  import torch
  import torch.nn as nn

  from ..pytorch_utils import ConvaD

if is_accelerate_available():
  from accelerate import init_empty_weights
  from accelerate.utils import find_tied_parameters

__magic_name__				     =     logging.get_logger(__name__)




def     _A					( __lowercase							,     __lowercase							,     __lowercase							,     __lowercase=None							,     __lowercase=None    ):





       """simple docstring"""



       if "." in tensor_name:
              lowerCamelCase__          =						tensor_name.split("""."""    )
              for split in splits[:-1]:
                     lowerCamelCase__          =						getattr(_lowerCAmelCase							,     _lowerCAmelCase    )
                     if new_module is None:
                            raise ValueError(f"""{module} has no attribute {split}."""    )
                     lowerCamelCase__          =						new_module
              lowerCamelCase__          =						splits[-1]

       if tensor_name not in module._parameters and tensor_name not in module._buffers:
              raise ValueError(f"""{module} does not have a parameter or a buffer named {tensor_name}."""    )
       lowerCamelCase__          =						tensor_name in module._buffers
       lowerCamelCase__          =						getattr(_lowerCAmelCase							,     _lowerCAmelCase    )

       if old_value.device == torch.device("""meta"""    ) and device not in ["meta", torch.device("""meta"""    )] and value is None:
              raise ValueError(f"""{tensor_name} is on the meta device, we need a `value` to put in on {device}."""    )

       lowerCamelCase__          =						False
       lowerCamelCase__          =						False
       if is_buffer or not is_bitsandbytes_available():
              lowerCamelCase__          =						False
              lowerCamelCase__          =						False
       else:
              lowerCamelCase__          =						hasattr(bnb.nn							,     """Params4bit"""    ) and isinstance(module._parameters[tensor_name]							,     bnb.nn.Paramsabit    )
              lowerCamelCase__          =						isinstance(module._parameters[tensor_name]							,     bnb.nn.IntaParams    )

       if is_abit or is_abit:
              lowerCamelCase__          =						module._parameters[tensor_name]
              if param.device.type != "cuda":
                     if value is None:
                            lowerCamelCase__          =						old_value.to(_lowerCAmelCase    )
                     elif isinstance(_lowerCAmelCase							,     torch.Tensor    ):
                            lowerCamelCase__          =						value.to("""cpu"""    )
                            if value.dtype == torch.inta:
                                   lowerCamelCase__          =						version.parse(importlib.metadata.version("""bitsandbytes"""    )    ) > version.parse(
                                       """0.37.2"""    )
                                   if not is_abit_serializable:
                                          raise ValueError(
                                              """Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. """
                                              """Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."""    )
                     else:
                            lowerCamelCase__          =						torch.tensor(_lowerCAmelCase							,     device="""cpu"""    )

                     # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
                     # Since weights are saved in the correct "orientation", we skip transposing when loading.
                     if issubclass(module.source_cls							,     _lowerCAmelCase    ) and fpaa_statistics is None:
                            lowerCamelCase__          =						new_value.T

                     lowerCamelCase__          =						old_value.__dict__
                     if is_abit:
                            lowerCamelCase__          =						bnb.nn.IntaParams(_lowerCAmelCase							,     requires_grad=_lowerCAmelCase							,     **_lowerCAmelCase    ).to(_lowerCAmelCase    )
                     elif is_abit:
                            lowerCamelCase__          =						bnb.nn.Paramsabit(_lowerCAmelCase							,     requires_grad=_lowerCAmelCase							,     **_lowerCAmelCase    ).to(_lowerCAmelCase    )

                     lowerCamelCase__          =						new_value
                     if fpaa_statistics is not None:
                            setattr(module.weight							,     """SCB"""							,     fpaa_statistics.to(_lowerCAmelCase    )    )

       else:
              if value is None:
                     lowerCamelCase__          =						old_value.to(_lowerCAmelCase    )
              elif isinstance(_lowerCAmelCase							,     torch.Tensor    ):
                     lowerCamelCase__          =						value.to(_lowerCAmelCase    )
              else:
                     lowerCamelCase__          =						torch.tensor(_lowerCAmelCase							,     device=_lowerCAmelCase    )

              if is_buffer:
                     lowerCamelCase__          =						new_value
              else:
                     lowerCamelCase__          =						nn.Parameter(_lowerCAmelCase							,     requires_grad=old_value.requires_grad    )
                     lowerCamelCase__          =						new_value




def     _A					( __lowercase							,     __lowercase=None							,     __lowercase=None							,     __lowercase=None							,     __lowercase=False    ):





       """simple docstring"""



       for name, module in model.named_children():
              if current_key_name is None:
                     lowerCamelCase__          =						[]
              current_key_name.append(_lowerCAmelCase    )

              if (isinstance(_lowerCAmelCase							,     nn.Linear    ) or isinstance(_lowerCAmelCase							,     _lowerCAmelCase    )) and name not in modules_to_not_convert:
                     # Check if the current key is not in the `modules_to_not_convert`
                     if not any(key in """.""".join(_lowerCAmelCase    ) for key in modules_to_not_convert    ):
                            with init_empty_weights():
                                   if isinstance(_lowerCAmelCase							,     _lowerCAmelCase    ):
                                          lowerCamelCase__          =						module.weight.shape
                                   else:
                                          lowerCamelCase__          =						module.in_features
                                          lowerCamelCase__          =						module.out_features

                                   if quantization_config.quantization_method() == "llm_int8":
                                          lowerCamelCase__          =						bnb.nn.LinearabitLt(
                                              _lowerCAmelCase							,     _lowerCAmelCase							,     module.bias is not None							,     has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight							,     threshold=quantization_config.llm_inta_threshold							,     )
                                          lowerCamelCase__          =						True
                                   else:
                                          if (
                                              quantization_config.llm_inta_skip_modules is not None
                                              and name in quantization_config.llm_inta_skip_modules
                                          ):
                                                 pass
                                          else:
                                                 lowerCamelCase__          =						bnb.nn.Linearabit(
                                                     _lowerCAmelCase							,     _lowerCAmelCase							,     module.bias is not None							,     quantization_config.bnb_abit_compute_dtype							,     compress_statistics=quantization_config.bnb_abit_use_double_quant							,     quant_type=quantization_config.bnb_abit_quant_type							,     )
                                                 lowerCamelCase__          =						True
                    # Store the module class in case we need to transpose the weight later
                                   lowerCamelCase__          =						type(_lowerCAmelCase    )
                                   # Force requires grad to False to avoid unexpected errors
                                   model._modules[name].requires_grad_(_lowerCAmelCase    )
              if len(list(module.children()    )    ) > 0:
                     lowerCamelCase__          =						_replace_with_bnb_linear(
                         _lowerCAmelCase							,     _lowerCAmelCase							,     _lowerCAmelCase							,     _lowerCAmelCase							,     has_been_replaced=_lowerCAmelCase							,     )
              # Remove the last key for recursion
              current_key_name.pop(-1    )
       return model, has_been_replaced




def     _A					( __lowercase							,     __lowercase=None							,     __lowercase=None							,     __lowercase=None    ):





       """simple docstring"""



       lowerCamelCase__          =						["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
       lowerCamelCase__          =						_replace_with_bnb_linear(
           _lowerCAmelCase							,     _lowerCAmelCase							,     _lowerCAmelCase							,     _lowerCAmelCase    )

       if not has_been_replaced:
              logger.warning(
                  """You are loading your model in 8bit or 4bit but no linear modules were found in your model."""
                  """ Please double check your model architecture, or submit an issue on github if you think this is"""
                  """ a bug."""    )

       return model




def     _A					( *__lowercase							,     **__lowercase    ):





       """simple docstring"""



       warnings.warn(
           """`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead"""							,     _lowerCAmelCase							,     )
       return replace_with_bnb_linear(*_lowerCAmelCase							,     **_lowerCAmelCase    )




def     _A					( *__lowercase							,     **__lowercase    ):





       """simple docstring"""



       warnings.warn(
           """`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead"""							,     _lowerCAmelCase							,     )
       return set_module_quantized_tensor_to_device(*_lowerCAmelCase							,     **_lowerCAmelCase    )




def     _A					( __lowercase    ):





       """simple docstring"""



       lowerCamelCase__          =						deepcopy(_lowerCAmelCase    )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
       tied_model.tie_weights()

       lowerCamelCase__          =						find_tied_parameters(_lowerCAmelCase    )
       # For compatibility with Accelerate < 0.18
       if isinstance(_lowerCAmelCase							,     _lowerCAmelCase    ):
              lowerCamelCase__          =						sum(list(tied_params.values()    )							,     []    ) + list(tied_params.keys()    )
       else:
              lowerCamelCase__          =						sum(_lowerCAmelCase							,     []    )
       lowerCamelCase__          =						len(_lowerCAmelCase    ) > 0

       # Check if it is a base model
       lowerCamelCase__          =						not hasattr(_lowerCAmelCase							,     model.base_model_prefix    )

       # Ignore this for base models (BertModel, GPT2Model, etc.)
       if (not has_tied_params) and is_base_model:
              return []

       # otherwise they have an attached head
       lowerCamelCase__          =						list(model.named_children()    )
       lowerCamelCase__          =						[list_modules[-1][0]]

       # add last module together with tied weights
       lowerCamelCase__          =						set(_lowerCAmelCase    ) - set(_lowerCAmelCase    )
       lowerCamelCase__          =						list(set(_lowerCAmelCase    )    ) + list(_lowerCAmelCase    )

       # remove ".weight" from the keys
       lowerCamelCase__          =						[""".weight""", """.bias"""]
       lowerCamelCase__          =						[]
       for name in list_untouched:
              for name_to_remove in names_to_remove:
                     if name_to_remove in name:
                            lowerCamelCase__          =						name.replace(_lowerCAmelCase							,     """"""    )
              filtered_module_names.append(_lowerCAmelCase    )

       return filtered_module_names











'''simple docstring'''





import argparse
import os

import jax as jnp
import numpy as onp
import torch
import torch.nn as nn
from music_spectrogram_diffusion import inference
from tax import checkpoints

from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder


__a  			=						"base_with_context"





def 		__snake_case(							_lowerCAmelCase	,  _lowerCAmelCase						)						->					Union[str, Any]:
      snake_case__    :       Optional[Any]       		= nn.Parameter(torch.FloatTensor(weights["""token_embedder"""]["""embedding"""]						)						)
      snake_case__    :       Dict       		= nn.Parameter(
          torch.FloatTensor(weights["""Embed_0"""]["""embedding"""]						)	,  requires_grad=_lowerCAmelCase						)
      for lyr_num, lyr in enumerate(model.encoders						):
            snake_case__    :       List[str]       		= weights[f"layers_{lyr_num}"]
            snake_case__    :       Dict       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""]						)						)

            snake_case__    :       List[str]       		= ly_weight["""attention"""]
            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T						)						)
            snake_case__    :       Optional[Any]       		= nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T						)						)
            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T						)						)
            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T						)						)

            snake_case__    :       int       		= nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""]						)						)

            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T						)						)
            snake_case__    :       Optional[Any]       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T						)						)
            snake_case__    :       Union[str, Any]       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T						)						)

      snake_case__    :       Tuple       		= nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""]						)						)
      return model





def 		__snake_case(							_lowerCAmelCase	,  _lowerCAmelCase						)						->					List[Any]:
      snake_case__    :       Tuple       		= nn.Parameter(torch.FloatTensor(weights["""input_proj"""]["""kernel"""].T						)						)

      snake_case__    :       str       		= nn.Parameter(
          torch.FloatTensor(weights["""Embed_0"""]["""embedding"""]						)	,  requires_grad=_lowerCAmelCase						)

      for lyr_num, lyr in enumerate(model.encoders						):
            snake_case__    :       List[Any]       		= weights[f"layers_{lyr_num}"]
            snake_case__    :       List[str]       		= ly_weight["""attention"""]

            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T						)						)
            snake_case__    :       Dict       		= nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T						)						)
            snake_case__    :       Tuple       		= nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T						)						)
            snake_case__    :       Any       		= nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T						)						)
            snake_case__    :       Optional[Any]       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""pre_attention_layer_norm"""]["""scale"""]						)						)

            snake_case__    :       Dict       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T						)						)
            snake_case__    :       Optional[Any]       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T						)						)
            snake_case__    :       Dict       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T						)						)
            snake_case__    :       Dict       		= nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""]						)						)

      snake_case__    :       str       		= nn.Parameter(torch.FloatTensor(weights["""encoder_norm"""]["""scale"""]						)						)

      return model





def 		__snake_case(							_lowerCAmelCase	,  _lowerCAmelCase						)						->					List[str]:
      snake_case__    :       int       		= nn.Parameter(torch.FloatTensor(weights["""time_emb_dense0"""]["""kernel"""].T						)						)
      snake_case__    :       List[Any]       		= nn.Parameter(torch.FloatTensor(weights["""time_emb_dense1"""]["""kernel"""].T						)						)

      snake_case__    :       List[Any]       		= nn.Parameter(
          torch.FloatTensor(weights["""Embed_0"""]["""embedding"""]						)	,  requires_grad=_lowerCAmelCase						)

      snake_case__    :       Optional[Any]       		= nn.Parameter(
          torch.FloatTensor(weights["""continuous_inputs_projection"""]["""kernel"""].T						)						)

      for lyr_num, lyr in enumerate(model.decoders						):
            snake_case__    :       List[Any]       		= weights[f"layers_{lyr_num}"]
            snake_case__    :       Optional[int]       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""pre_self_attention_layer_norm"""]["""scale"""]						)						)

            snake_case__    :       List[str]       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""FiLMLayer_0"""]["""DenseGeneral_0"""]["""kernel"""].T						)						)

            snake_case__    :       Any       		= ly_weight["""self_attention"""]
            snake_case__    :       Union[str, Any]       		= nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T						)						)
            snake_case__    :       List[str]       		= nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T						)						)
            snake_case__    :       Tuple       		= nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T						)						)
            snake_case__    :       Optional[Any]       		= nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T						)						)

            snake_case__    :       int       		= ly_weight["""MultiHeadDotProductAttention_0"""]
            snake_case__    :       int       		= nn.Parameter(torch.FloatTensor(attention_weights["""query"""]["""kernel"""].T						)						)
            snake_case__    :       List[Any]       		= nn.Parameter(torch.FloatTensor(attention_weights["""key"""]["""kernel"""].T						)						)
            snake_case__    :       Any       		= nn.Parameter(torch.FloatTensor(attention_weights["""value"""]["""kernel"""].T						)						)
            snake_case__    :       List[Any]       		= nn.Parameter(torch.FloatTensor(attention_weights["""out"""]["""kernel"""].T						)						)
            snake_case__    :       List[str]       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""pre_cross_attention_layer_norm"""]["""scale"""]						)						)

            snake_case__    :       Any       		= nn.Parameter(torch.FloatTensor(ly_weight["""pre_mlp_layer_norm"""]["""scale"""]						)						)
            snake_case__    :       Union[str, Any]       		= nn.Parameter(
                torch.FloatTensor(ly_weight["""FiLMLayer_1"""]["""DenseGeneral_0"""]["""kernel"""].T						)						)
            snake_case__    :       str       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_0"""]["""kernel"""].T						)						)
            snake_case__    :       Any       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wi_1"""]["""kernel"""].T						)						)
            snake_case__    :       Union[str, Any]       		= nn.Parameter(torch.FloatTensor(ly_weight["""mlp"""]["""wo"""]["""kernel"""].T						)						)

      snake_case__    :       Tuple       		= nn.Parameter(torch.FloatTensor(weights["""decoder_norm"""]["""scale"""]						)						)

      snake_case__    :       int       		= nn.Parameter(torch.FloatTensor(weights["""spec_out_dense"""]["""kernel"""].T						)						)

      return model





def 		__snake_case(							_lowerCAmelCase						)						->					Union[str, Any]:
      snake_case__    :       Tuple       		= checkpoints.load_tax_checkpoint(args.checkpoint_path						)
      snake_case__    :       List[str]       		= jnp.tree_util.tree_map(onp.array	,  _lowerCAmelCase						)

      snake_case__    :       int       		= [
          """from __gin__ import dynamic_registration""",
          """from music_spectrogram_diffusion.models.diffusion import diffusion_utils""",
          """diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0""",
          """diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()""",
      ]

      snake_case__    :       Any       		= os.path.join(args.checkpoint_path	,  """.."""	,  """config.gin"""						)
      snake_case__    :       Dict       		= inference.parse_training_gin_file(_lowerCAmelCase	,  _lowerCAmelCase						)
      snake_case__    :       int       		= inference.InferenceModel(args.checkpoint_path	,  _lowerCAmelCase						)

      snake_case__    :       Optional[int]       		= DDPMScheduler(beta_schedule="""squaredcos_cap_v2"""	,  variance_type="""fixed_large"""						)

      snake_case__    :       Union[str, Any]       		= SpectrogramNotesEncoder(
          max_length=synth_model.sequence_length["""inputs"""]	,  vocab_size=synth_model.model.module.config.vocab_size	,  d_model=synth_model.model.module.config.emb_dim	,  dropout_rate=synth_model.model.module.config.dropout_rate	,  num_layers=synth_model.model.module.config.num_encoder_layers	,  num_heads=synth_model.model.module.config.num_heads	,  d_kv=synth_model.model.module.config.head_dim	,  d_ff=synth_model.model.module.config.mlp_dim	,  feed_forward_proj="""gated-gelu"""	,  )

      snake_case__    :       Union[str, Any]       		= SpectrogramContEncoder(
          input_dims=synth_model.audio_codec.n_dims	,  targets_context_length=synth_model.sequence_length["""targets_context"""]	,  d_model=synth_model.model.module.config.emb_dim	,  dropout_rate=synth_model.model.module.config.dropout_rate	,  num_layers=synth_model.model.module.config.num_encoder_layers	,  num_heads=synth_model.model.module.config.num_heads	,  d_kv=synth_model.model.module.config.head_dim	,  d_ff=synth_model.model.module.config.mlp_dim	,  feed_forward_proj="""gated-gelu"""	,  )

      snake_case__    :       Any       		= TaFilmDecoder(
          input_dims=synth_model.audio_codec.n_dims	,  targets_length=synth_model.sequence_length["""targets_context"""]	,  max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time	,  d_model=synth_model.model.module.config.emb_dim	,  num_layers=synth_model.model.module.config.num_decoder_layers	,  num_heads=synth_model.model.module.config.num_heads	,  d_kv=synth_model.model.module.config.head_dim	,  d_ff=synth_model.model.module.config.mlp_dim	,  dropout_rate=synth_model.model.module.config.dropout_rate	,  )

      snake_case__    :       Optional[int]       		= load_notes_encoder(ta_checkpoint["""target"""]["""token_encoder"""]	,  _lowerCAmelCase						)
      snake_case__    :       Union[str, Any]       		= load_continuous_encoder(ta_checkpoint["""target"""]["""continuous_encoder"""]	,  _lowerCAmelCase						)
      snake_case__    :       Optional[Any]       		= load_decoder(ta_checkpoint["""target"""]["""decoder"""]	,  _lowerCAmelCase						)

      snake_case__    :       str       		= OnnxRuntimeModel.from_pretrained("""kashif/soundstream_mel_decoder"""						)

      snake_case__    :       Dict       		= SpectrogramDiffusionPipeline(
          notes_encoder=_lowerCAmelCase	,  continuous_encoder=_lowerCAmelCase	,  decoder=_lowerCAmelCase	,  scheduler=_lowerCAmelCase	,  melgan=_lowerCAmelCase	,  )
      if args.save:
            pipe.save_pretrained(args.output_path						)


if __name__ == "__main__":
       __a  			=						argparse.ArgumentParser()

       parser.add_argument("--output_path", default=None, type=str, required=True, help="Path to the converted model.")
       parser.add_argument(
           "--save", default=True, type=bool, required=False, help="Whether to save the converted model or not."
       )
       parser.add_argument(
           "--checkpoint_path",
           default=F"{MODEL}/checkpoint_500000",
           type=str,
           required=False,
           help="Path to the original jax model checkpoint.",
       )
       __a  			=						parser.parse_args()

       main(args)
