|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2026 The HuggingFace Team. All rights reserved. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +# Usage: |
| 17 | +# python scripts/convert_kvae_audio_to_diffusers.py \ |
| 18 | +# --checkpoint_path /path/to/kvae-1/release_checkpoints/KVAE-Audio \ |
| 19 | +# --output_path /path/to/output |
| 20 | + |
| 21 | +""" |
| 22 | +Converts a `kandinskylab/KVAE-Audio` checkpoint (the `kvae.models.kvae_1d.KVAEAudio` architecture) into an |
| 23 | +`AutoencoderKLKVAEAudio`. |
| 24 | +
|
| 25 | +Key mapping, `encoder`/`decoder` (reference `Encoder1D`/`Decoder1D` -> `KVAEAudioEncoder`/`KVAEAudioDecoder`): |
| 26 | + {enc,dec}.model.0 -> {encoder,decoder}.conv1 (stem conv) |
| 27 | + {enc,dec}.model.{1..5}.block.<i>.block.<j> |
| 28 | + -> {encoder,decoder}.block.<stride-1>.res_unit<i+1>.{snake1,conv1,snake2,conv2} |
| 29 | + (encoder: i in {0,1,2}; decoder: i in {2,3,4}, since decoder's block.0/block.1 are its own |
| 30 | + snake1/conv_t1, not a res_unit) |
| 31 | + encoder.model.{1..5}.block.3 -> encoder.block.<stride-1>.snake1 (pre-downsample activation) |
| 32 | + encoder.model.{1..5}.block.4 -> encoder.block.<stride-1>.conv1 (strided downsample conv) |
| 33 | + decoder.model.{1..5}.block.0 -> decoder.block.<stride-1>.snake1 |
| 34 | + decoder.model.{1..5}.block.1 -> decoder.block.<stride-1>.conv_t1 (strided upsample conv) |
| 35 | + {enc,dec}.model.6 -> {encoder,decoder}.snake1 (final activation) |
| 36 | + {enc,dec}.model.7 -> {encoder,decoder}.conv2 (final conv) |
| 37 | + in_proj / out_proj -> unchanged (same attribute names on both sides) |
| 38 | + attn.in_proj_{weight,bias} -> attn.to_{q,k,v}.{weight,bias} (equal 3-way chunk, nn.MultiheadAttention layout) |
| 39 | + attn.out_proj.{weight,bias} -> attn.to_out.0.{weight,bias} |
| 40 | +
|
| 41 | +`bias` / `alpha` / `weight_g` / `weight_v` suffixes are copied unchanged. The reference uses |
| 42 | +`torch.nn.utils.weight_norm`; the diffusers module uses `torch.nn.utils.parametrizations.weight_norm`. |
| 43 | +The two store the reparametrization under different keys (`weight_g`/`weight_v` vs. |
| 44 | +`parametrizations.weight.original0`/`original1`), but `load_state_dict` on the new-style module |
| 45 | +accepts the legacy key names directly and reconstructs the same weights, so no explicit rename is |
| 46 | +needed here. |
| 47 | +""" |
| 48 | + |
| 49 | +import argparse |
| 50 | +import json |
| 51 | +from pathlib import Path |
| 52 | + |
| 53 | +import torch |
| 54 | +from safetensors.torch import load_file |
| 55 | + |
| 56 | +from diffusers import AutoencoderKLKVAEAudio |
| 57 | + |
| 58 | + |
| 59 | +RES_UNIT_NAMES = {0: "res_unit1", 1: "res_unit2", 2: "res_unit3"} |
| 60 | +RES_UNIT_SUB_NAMES = {0: "snake1", 1: "conv1", 2: "snake2", 3: "conv2"} |
| 61 | + |
| 62 | + |
| 63 | +def convert_encoder_decoder_key(prefix: str, idx: int, rest: list[str]) -> str: |
| 64 | + if idx == 0: |
| 65 | + return f"{prefix}.conv1." + ".".join(rest) |
| 66 | + if idx == 6: |
| 67 | + return f"{prefix}.snake1." + ".".join(rest) |
| 68 | + if idx == 7: |
| 69 | + return f"{prefix}.conv2." + ".".join(rest) |
| 70 | + |
| 71 | + # idx in {1..5}: one per-stride block, nested under an extra "block" level in the reference |
| 72 | + # (an `OrderedDict([("block", block)])` wrapper used to keep the reference's own state-dict layout). |
| 73 | + block_idx = idx - 1 |
| 74 | + assert rest[0] == "block", f"expected 'block', got {rest}" |
| 75 | + inner = int(rest[1]) |
| 76 | + remaining = rest[2:] |
| 77 | + |
| 78 | + if prefix == "encoder": |
| 79 | + if inner in RES_UNIT_NAMES: |
| 80 | + res_unit = RES_UNIT_NAMES[inner] |
| 81 | + assert remaining[0] == "block", f"expected 'block', got {remaining}" |
| 82 | + sub_name = RES_UNIT_SUB_NAMES[int(remaining[1])] |
| 83 | + param = ".".join(remaining[2:]) |
| 84 | + return f"encoder.block.{block_idx}.{res_unit}.{sub_name}.{param}" |
| 85 | + if inner == 3: |
| 86 | + return f"encoder.block.{block_idx}.snake1." + ".".join(remaining) |
| 87 | + if inner == 4: |
| 88 | + return f"encoder.block.{block_idx}.conv1." + ".".join(remaining) |
| 89 | + else: |
| 90 | + if inner == 0: |
| 91 | + return f"decoder.block.{block_idx}.snake1." + ".".join(remaining) |
| 92 | + if inner == 1: |
| 93 | + return f"decoder.block.{block_idx}.conv_t1." + ".".join(remaining) |
| 94 | + if inner - 2 in RES_UNIT_NAMES: |
| 95 | + res_unit = RES_UNIT_NAMES[inner - 2] |
| 96 | + assert remaining[0] == "block", f"expected 'block', got {remaining}" |
| 97 | + sub_name = RES_UNIT_SUB_NAMES[int(remaining[1])] |
| 98 | + param = ".".join(remaining[2:]) |
| 99 | + return f"decoder.block.{block_idx}.{res_unit}.{sub_name}.{param}" |
| 100 | + |
| 101 | + raise ValueError(f"Unhandled {prefix}.model.{idx}.{'.'.join(rest)}") |
| 102 | + |
| 103 | + |
| 104 | +def convert_kvae_audio_state_dict(original_state_dict: dict) -> dict: |
| 105 | + converted_state_dict = {} |
| 106 | + |
| 107 | + for key, value in original_state_dict.items(): |
| 108 | + parts = key.split(".") |
| 109 | + |
| 110 | + if parts[0] in ("encoder", "decoder") and parts[1] == "model": |
| 111 | + new_key = convert_encoder_decoder_key(parts[0], int(parts[2]), parts[3:]) |
| 112 | + elif key.startswith("in_proj.") or key.startswith("out_proj."): |
| 113 | + new_key = key |
| 114 | + elif key == "attn.in_proj_weight": |
| 115 | + query, key_, value_ = torch.chunk(value, 3, dim=0) |
| 116 | + converted_state_dict["attn.to_q.weight"] = query |
| 117 | + converted_state_dict["attn.to_k.weight"] = key_ |
| 118 | + converted_state_dict["attn.to_v.weight"] = value_ |
| 119 | + continue |
| 120 | + elif key == "attn.in_proj_bias": |
| 121 | + query, key_, value_ = torch.chunk(value, 3, dim=0) |
| 122 | + converted_state_dict["attn.to_q.bias"] = query |
| 123 | + converted_state_dict["attn.to_k.bias"] = key_ |
| 124 | + converted_state_dict["attn.to_v.bias"] = value_ |
| 125 | + continue |
| 126 | + elif key == "attn.out_proj.weight": |
| 127 | + new_key = "attn.to_out.0.weight" |
| 128 | + elif key == "attn.out_proj.bias": |
| 129 | + new_key = "attn.to_out.0.bias" |
| 130 | + else: |
| 131 | + raise ValueError(f"Unhandled key: {key}") |
| 132 | + |
| 133 | + converted_state_dict[new_key] = value |
| 134 | + |
| 135 | + return converted_state_dict |
| 136 | + |
| 137 | + |
| 138 | +def convert_kvae_audio(checkpoint_path: str, output_path: str, dtype: str = "fp32"): |
| 139 | + dtype_map = {"fp32": torch.float32, "fp16": torch.float16, "bf16": torch.bfloat16} |
| 140 | + torch_dtype = dtype_map[dtype] |
| 141 | + |
| 142 | + checkpoint_dir = Path(checkpoint_path) |
| 143 | + with open(checkpoint_dir / "config.json") as f: |
| 144 | + config = json.load(f) |
| 145 | + config.pop("model_type", None) |
| 146 | + config.pop("use_attn", None) |
| 147 | + |
| 148 | + original_state_dict = load_file(checkpoint_dir / "model.safetensors") |
| 149 | + converted_state_dict = convert_kvae_audio_state_dict(original_state_dict) |
| 150 | + |
| 151 | + model = AutoencoderKLKVAEAudio(**config) |
| 152 | + model.load_state_dict(converted_state_dict, strict=True) |
| 153 | + model = model.to(dtype=torch_dtype) |
| 154 | + |
| 155 | + output_path = Path(output_path) |
| 156 | + output_path.mkdir(parents=True, exist_ok=True) |
| 157 | + model.save_pretrained(output_path) |
| 158 | + |
| 159 | + # round-trip check |
| 160 | + AutoencoderKLKVAEAudio.from_pretrained(output_path, torch_dtype=torch_dtype) |
| 161 | + |
| 162 | + |
| 163 | +def get_args(): |
| 164 | + parser = argparse.ArgumentParser() |
| 165 | + parser.add_argument( |
| 166 | + "--checkpoint_path", |
| 167 | + type=str, |
| 168 | + required=True, |
| 169 | + help="Path to a local directory containing config.json and model.safetensors", |
| 170 | + ) |
| 171 | + parser.add_argument("--output_path", type=str, required=True, help="Output directory") |
| 172 | + parser.add_argument( |
| 173 | + "--dtype", type=str, default="fp32", choices=["fp32", "fp16", "bf16"], help="Data type for converted weights" |
| 174 | + ) |
| 175 | + return parser.parse_args() |
| 176 | + |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + args = get_args() |
| 180 | + convert_kvae_audio( |
| 181 | + checkpoint_path=args.checkpoint_path, |
| 182 | + output_path=args.output_path, |
| 183 | + dtype=args.dtype, |
| 184 | + ) |
0 commit comments