"""Builds the Drama 3 / S2-Pro codec (configs/modded_dac_vq.yaml) without Hydra, and mirrors load_codec_model from fish_speech/models/text2semantic/inference.py.""" from functools import partial import torch from torch.nn.utils.parametrize import is_parametrized, remove_parametrizations from fish_speech.models.dac.modded_dac import DAC, ModelArgs, WindowLimitedTransformer from fish_speech.models.dac.rvq import DownsampleResidualVectorQuantize def _rvq_transformer() -> WindowLimitedTransformer: return WindowLimitedTransformer( causal=True, window_size=128, input_dim=1024, config=ModelArgs( block_size=2048, n_layer=8, n_head=16, dim=1024, intermediate_size=3072, n_local_heads=-1, head_dim=64, rope_base=10000, norm_eps=1e-5, dropout_rate=0.1, attn_dropout_rate=0.1, channels_first=True, ), ) def build_codec() -> DAC: quantizer = DownsampleResidualVectorQuantize( input_dim=1024, n_codebooks=9, codebook_size=1024, codebook_dim=8, quantizer_dropout=0.5, downsample_factor=[2, 2], post_module=_rvq_transformer(), pre_module=_rvq_transformer(), semantic_codebook_size=4096, ) return DAC( sample_rate=44100, encoder_dim=64, encoder_rates=[2, 4, 8, 8], decoder_dim=1536, decoder_rates=[8, 8, 4, 2], encoder_transformer_layers=[0, 0, 0, 4], decoder_transformer_layers=[4, 0, 0, 0], quantizer=quantizer, transformer_general_config=partial( ModelArgs, block_size=8192, n_local_heads=-1, head_dim=64, rope_base=10000, norm_eps=1e-5, dropout_rate=0.1, attn_dropout_rate=0.1, channels_first=True, ), ) @torch.no_grad() def load_codec(path: str, dtype: torch.dtype = torch.float32) -> DAC: """The codec in dtype, with weight norm folded into the convolution weights.""" codec = build_codec() state_dict = torch.load(path, map_location="cpu", mmap=False, weights_only=True) if "state_dict" in state_dict: state_dict = state_dict["state_dict"] if any("generator" in k for k in state_dict): state_dict = { k.replace("generator.", ""): v for k, v in state_dict.items() if "generator." in k } rebuilt_buffers = { f"{name}.{buffer}" if name else buffer for name, module in codec.named_modules() for buffer in module._non_persistent_buffers_set } # The checkpoint also stores the 32768 x 32768 causal masks this copy of the # codec no longer keeps (every codec transformer builds its own mask). state_dict = { k: v for k, v in state_dict.items() if k not in rebuilt_buffers and not k.endswith(".causal_mask") } codec.load_state_dict(state_dict, strict=True) codec.eval() for module in list(codec.modules()): if is_parametrized(module, "weight"): remove_parametrizations(module, "weight", leave_parametrized=True) elif hasattr(module, "weight_g"): torch.nn.utils.remove_weight_norm(module) return codec.to(dtype=dtype)