Skip to content

Commit aea7b70

Browse files
authored
[feat] add KVAE-Audio autoencoder (huggingface#14384)
* [feat] add KVAE-Audio autoencoder * [fix] non-contiguous tensor into in_proj in AutoencoderKLKVAEAudio * [chore] sync KVAE-Audio with upstream test and annotation changes * [refactor] dedicated attention class and processor for AutoencoderKLKVAEAudio * [refactor] remove the runtime sample_rate argument from AutoencoderKLKVAEAudio * [refactor] always apply attention in AutoencoderKLKVAEAudio, drop use_attn * [refactor] drop the derived latent_dim default from AutoencoderKLKVAEAudio * [docs] fix encoder_rates docstring in AutoencoderKLKVAEAudio * [refactor] rename Snake1d to KVAEAudioSnake1d in AutoencoderKLKVAEAudio * [tests] skip layerwise casting training for AutoencoderKLKVAEAudio
1 parent 6184688 commit aea7b70

9 files changed

Lines changed: 775 additions & 0 deletions

File tree

‎docs/source/en/_toctree.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,8 @@
481481
title: AutoencoderKLHunyuanVideo15
482482
- local: api/models/autoencoder_kl_kvae
483483
title: AutoencoderKLKVAE
484+
- local: api/models/autoencoder_kl_kvae_audio
485+
title: AutoencoderKLKVAEAudio
484486
- local: api/models/autoencoder_kl_kvae_video
485487
title: AutoencoderKLKVAEVideo
486488
- local: api/models/autoencoderkl_audio_ltx_2
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<!-- Copyright 2026 The Kandinsky Lab Team and The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License. -->
14+
15+
# AutoencoderKLKVAEAudio
16+
17+
A 1D convolutional variational autoencoder (VAE) with KL loss for audio, introduced by the Kandinsky Lab
18+
Team in [KVAE-Audio](https://huggingface.co/kandinskylab/KVAE-Audio). It compresses raw, full-band (48 kHz)
19+
waveforms into compact continuous latents and reconstructs them with high fidelity across speech, music, and
20+
general audio.
21+
22+
The model can be loaded with the following code snippet.
23+
24+
```python
25+
import torch
26+
from diffusers import AutoencoderKLKVAEAudio
27+
28+
vae = AutoencoderKLKVAEAudio.from_pretrained("kandinskylab/KVAE-Audio", subfolder="diffusers", dtype=torch.float32)
29+
```
30+
31+
## AutoencoderKLKVAEAudio
32+
33+
[[autodoc]] AutoencoderKLKVAEAudio
34+
- decode
35+
- encode
36+
- all
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
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+
)

‎src/diffusers/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,7 @@
258258
"AutoencoderKLHunyuanVideo",
259259
"AutoencoderKLHunyuanVideo15",
260260
"AutoencoderKLKVAE",
261+
"AutoencoderKLKVAEAudio",
261262
"AutoencoderKLKVAEVideo",
262263
"AutoencoderKLLTX2Audio",
263264
"AutoencoderKLLTX2Video",
@@ -1173,6 +1174,7 @@
11731174
AutoencoderKLHunyuanVideo,
11741175
AutoencoderKLHunyuanVideo15,
11751176
AutoencoderKLKVAE,
1177+
AutoencoderKLKVAEAudio,
11761178
AutoencoderKLKVAEVideo,
11771179
AutoencoderKLLTX2Audio,
11781180
AutoencoderKLLTX2Video,

‎src/diffusers/models/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
_import_structure["autoencoders.autoencoder_kl_hunyuanimage_refiner"] = ["AutoencoderKLHunyuanImageRefiner"]
4343
_import_structure["autoencoders.autoencoder_kl_hunyuanvideo15"] = ["AutoencoderKLHunyuanVideo15"]
4444
_import_structure["autoencoders.autoencoder_kl_kvae"] = ["AutoencoderKLKVAE"]
45+
_import_structure["autoencoders.autoencoder_kl_kvae_audio"] = ["AutoencoderKLKVAEAudio"]
4546
_import_structure["autoencoders.autoencoder_kl_kvae_video"] = ["AutoencoderKLKVAEVideo"]
4647
_import_structure["autoencoders.autoencoder_kl_ltx"] = ["AutoencoderKLLTXVideo"]
4748
_import_structure["autoencoders.autoencoder_kl_ltx2"] = ["AutoencoderKLLTX2Video"]
@@ -197,6 +198,7 @@
197198
AutoencoderKLHunyuanVideo,
198199
AutoencoderKLHunyuanVideo15,
199200
AutoencoderKLKVAE,
201+
AutoencoderKLKVAEAudio,
200202
AutoencoderKLKVAEVideo,
201203
AutoencoderKLLTX2Audio,
202204
AutoencoderKLLTX2Video,

‎src/diffusers/models/autoencoders/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from .autoencoder_kl_hunyuanimage_refiner import AutoencoderKLHunyuanImageRefiner
1313
from .autoencoder_kl_hunyuanvideo15 import AutoencoderKLHunyuanVideo15
1414
from .autoencoder_kl_kvae import AutoencoderKLKVAE
15+
from .autoencoder_kl_kvae_audio import AutoencoderKLKVAEAudio
1516
from .autoencoder_kl_kvae_video import AutoencoderKLKVAEVideo
1617
from .autoencoder_kl_ltx import AutoencoderKLLTXVideo
1718
from .autoencoder_kl_ltx2 import AutoencoderKLLTX2Video

0 commit comments

Comments
 (0)