Skip to content
Python

added Ace 1.5 support

DeepBeepMeep6465dc704eb2
diff --git a/README.md b/README.md
index 5aa382c..e277310 100644
--- a/README.md
+++ b/README.md
@@ -33,12 +33,16 @@ WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen,
## 🔥 Latest Updates :
-### February 3rd 2026: WanGP v10.70, Get Ready To Rumble
-- **LTX-2 Self Refiner**: WanGP exclusive *Self Refiner* has been added to *Distilled/Non Distilled* models, so hopefully this will improve the quality of our Video Gens.
+### February 4rd 2026: WanGP v10.70, Let's Get Ready To Rumble !
+*The competition between Open Source & Close Source has never been that hot !*
+
+- **Ace Step 1.5 Turbo**: this long waited open source project claims to have overthrown *Suno 5*. It lets you generate high multi minutes quality songs. It comes in four flavours: *Vanilla* (No Language Model Preprocessing, **4s Generation Time!!!**) & *3 levels of LM Preprocessing* for a higher Quality (and increasing VRAM requirements)
- **Kugel Audio 0**: another *TTS* with *Voice Cloning*, this one claims to outperform *ElevenLabs* !!! The nice thing about Kugel Audio is that it can be used to create Dialogues between two cloned voices. Have Fun !
-- **Ace Step 1.5**: this long waited open source project claims to have overthrown *Suno 5*. It lets you generate high multi minutes of quality songs.
+- **LTX-2 Self Refiner**: WanGP exclusive *Self Refiner* has been added to *Distilled/Non Distilled* models, so hopefully this will improve the quality of our Video Gens.
+
+
### February 1st 2026: WanGP v10.61, Upgrade Time !
diff --git a/defaults/ace_step_v1.json b/defaults/ace_step_v1.json
index 786f476..926a1a1 100644
--- a/defaults/ace_step_v1.json
+++ b/defaults/ace_step_v1.json
@@ -1,6 +1,6 @@
{
"model": {
- "name": "TTS ACE-Step v1 3.5B",
+ "name": "TTS ACE-Step v1.0 3.5B",
"architecture": "ace_step_v1",
"description": "ACE-Step, a fast open-source foundation diffusion based model for music generation that overcomes key limitations of existing approaches and achieves state-of-the-art performance.",
"URLs": [
diff --git a/defaults/ace_step_v1_5.json b/defaults/ace_step_v1_5.json
new file mode 100644
index 0000000..af94a07
--- /dev/null
+++ b/defaults/ace_step_v1_5.json
@@ -0,0 +1,23 @@
+{
+ "model": {
+ "name": "TTS ACE-Step v1.5 Turbo 2B",
+ "architecture": "ace_step_v1_5",
+ "description": "ACE-Step 1.5 Turbo (8 steps) without the 5Hz LM stage. Uses the DiT-only path for faster/leaner runs.",
+ "URLs": [
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/ace_step_v1_5_transformer_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/ace_step_v1_5_transformer_quanto_bf16_int8.safetensors"
+ ],
+ "ace_step15_enable_lm": false,
+ "ace_step15_transformer_variant": "turbo",
+ "text_encoder_folder": "acestep-5Hz-lm-1.7B"
+ },
+ "prompt": "[Verse]\nNeon rain on the city line\nYou hum the tune and I fall in time\n[Chorus]\nHold me close and keep the time",
+ "alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
+ "audio_prompt_type": "",
+ "audio_scale": 0.5,
+ "duration_seconds": 20,
+ "num_inference_steps": 8,
+ "shift": 1.0,
+ "guidance_scale": 1.0,
+ "scheduler_type": "euler"
+}
diff --git a/defaults/ace_step_v1_5_turbo_lm_0_6b.json b/defaults/ace_step_v1_5_turbo_lm_0_6b.json
new file mode 100644
index 0000000..6c25d93
--- /dev/null
+++ b/defaults/ace_step_v1_5_turbo_lm_0_6b.json
@@ -0,0 +1,23 @@
+{
+ "model": {
+ "name": "TTS ACE-Step v1.5 Turbo LM_0.6B 2B",
+ "architecture": "ace_step_v1_5",
+ "description": "ACE-Step 1.5 Turbo (8 steps) with 0.6B LM, a diffusion-based music generation model with improved conditioning and timbre control. The LM 0.6B will increase the audio output quality thanks to Medium/Weak Audio Understanding & Composition Capability.",
+ "URLs": "ace_step_v1_5",
+ "text_encoder_URLs": [
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/acestep-5Hz-lm-0.6B/acestep-5Hz-lm-0.6B_bf16.safetensors"
+ ],
+ "ace_step15_enable_lm": true,
+ "ace_step15_transformer_variant": "turbo",
+ "text_encoder_folder": "acestep-5Hz-lm-0.6B"
+ },
+ "prompt": "[Verse]\nNeon rain on the city line\nYou hum the tune and I fall in time\n[Chorus]\nHold me close and keep the time",
+ "alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
+ "audio_prompt_type": "",
+ "audio_scale": 0.5,
+ "duration_seconds": 20,
+ "num_inference_steps": 8,
+ "shift": 1.0,
+ "guidance_scale": 1.0,
+ "scheduler_type": "euler"
+}
diff --git a/defaults/ace_step_v1_5_turbo_lm_1_7b.json b/defaults/ace_step_v1_5_turbo_lm_1_7b.json
new file mode 100644
index 0000000..29bf0da
--- /dev/null
+++ b/defaults/ace_step_v1_5_turbo_lm_1_7b.json
@@ -0,0 +1,24 @@
+{
+ "model": {
+ "name": "TTS ACE-Step v1.5 Turbo LM_1.7B 2B",
+ "architecture": "ace_step_v1_5",
+ "description": "ACE-Step 1.5 Turbo (8 steps) with 1.7B LM, a diffusion-based music generation model with improved conditioning and timbre control. The LM 1.7B will increase the audio output quality thanks to Medium Audio Understanding & Composition Capability.",
+ "URLs": "ace_step_v1_5",
+ "text_encoder_URLs": [
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/acestep-5Hz-lm-1.7B/acestep-5Hz-lm-1.7B_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/acestep-5Hz-lm-1.7B/acestep-5Hz-lm-1.7B_quanto_bf16_int8.safetensors"
+ ],
+ "ace_step15_enable_lm": true,
+ "ace_step15_transformer_variant": "turbo",
+ "text_encoder_folder": "acestep-5Hz-lm-1.7B"
+ },
+ "prompt": "[Verse]\nNeon rain on the city line\nYou hum the tune and I fall in time\n[Chorus]\nHold me close and keep the time",
+ "alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
+ "audio_prompt_type": "",
+ "audio_scale": 0.5,
+ "duration_seconds": 20,
+ "num_inference_steps": 8,
+ "shift": 1.0,
+ "guidance_scale": 1.0,
+ "scheduler_type": "euler"
+}
diff --git a/defaults/ace_step_v1_5_turbo_lm_4b.json b/defaults/ace_step_v1_5_turbo_lm_4b.json
new file mode 100644
index 0000000..67dc401
--- /dev/null
+++ b/defaults/ace_step_v1_5_turbo_lm_4b.json
@@ -0,0 +1,24 @@
+{
+ "model": {
+ "name": "TTS ACE-Step v1.5 Turbo LM_4B 2B",
+ "architecture": "ace_step_v1_5",
+ "description": "ACE-Step 1.5 Turbo (8 steps) with 4B LM, a diffusion-based music generation model with improved conditioning and timbre control. The LM 4B will increase the audio output quality thanks to Strong Audio Understanding & Composition Capability.",
+ "URLs": "ace_step_v1_5",
+ "text_encoder_URLs": [
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/acestep-5Hz-lm-4B/acestep-5Hz-lm-4B_bf16.safetensors",
+ "https://huggingface.co/DeepBeepMeep/TTS/resolve/main/acestep-5Hz-lm-4B/acestep-5Hz-lm-4B_quanto_bf16_int8.safetensors"
+ ],
+ "ace_step15_enable_lm": true,
+ "ace_step15_transformer_variant": "turbo",
+ "text_encoder_folder": "acestep-5Hz-lm-4B"
+ },
+ "prompt": "[Verse]\nNeon rain on the city line\nYou hum the tune and I fall in time\n[Chorus]\nHold me close and keep the time",
+ "alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
+ "audio_prompt_type": "",
+ "audio_scale": 0.5,
+ "duration_seconds": 20,
+ "num_inference_steps": 8,
+ "shift": 1.0,
+ "guidance_scale": 1.0,
+ "scheduler_type": "euler"
+}
diff --git a/models/TTS/ace_step15/__init__.py b/models/TTS/ace_step15/__init__.py
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/models/TTS/ace_step15/__init__.py
@@ -0,0 +1 @@
+
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_audio_vae_config.json b/models/TTS/ace_step15/configs/ace_step_v1_5_audio_vae_config.json
new file mode 100644
index 0000000..f49eb7b
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_audio_vae_config.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "AutoencoderOobleck",
+ "_diffusers_version": "0.34.0",
+ "_name_or_path": "/root/data/repo/gongjunmin/ACE-Step-1.5/checkpoints/vae/",
+ "audio_channels": 2,
+ "channel_multiples": [
+ 1,
+ 2,
+ 4,
+ 8,
+ 16
+ ],
+ "decoder_channels": 128,
+ "decoder_input_channels": 64,
+ "downsampling_ratios": [
+ 2,
+ 4,
+ 4,
+ 6,
+ 10
+ ],
+ "encoder_hidden_size": 128,
+ "sampling_rate": 48000
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config.json
new file mode 100644
index 0000000..43fb144
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config.json
@@ -0,0 +1,75 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "is_turbo": true,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "model_version": "turbo",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_base.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_base.json
new file mode 100644
index 0000000..111f956
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_base.json
@@ -0,0 +1,74 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003,
+ "is_turbo": false
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_sft.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_sft.json
new file mode 100644
index 0000000..111f956
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_sft.json
@@ -0,0 +1,74 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003,
+ "is_turbo": false
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo.json
new file mode 100644
index 0000000..43fb144
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo.json
@@ -0,0 +1,75 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "is_turbo": true,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "model_version": "turbo",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_continuous.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_continuous.json
new file mode 100644
index 0000000..fafc7fd
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_continuous.json
@@ -0,0 +1,74 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003,
+ "is_turbo": true
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift1.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift1.json
new file mode 100644
index 0000000..fafc7fd
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift1.json
@@ -0,0 +1,74 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003,
+ "is_turbo": true
+}
diff --git a/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift3.json b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift3.json
new file mode 100644
index 0000000..fafc7fd
--- /dev/null
+++ b/models/TTS/ace_step15/configs/ace_step_v1_5_transformer_config_turbo_shift3.json
@@ -0,0 +1,74 @@
+{
+ "attention_bias": false,
+ "attention_dropout": 0.0,
+ "audio_acoustic_hidden_dim": 64,
+ "data_proportion": 0.5,
+ "dtype": "bfloat16",
+ "fsq_dim": 2048,
+ "fsq_input_levels": [
+ 8,
+ 8,
+ 8,
+ 5,
+ 5,
+ 5
+ ],
+ "fsq_input_num_quantizers": 1,
+ "head_dim": 128,
+ "hidden_act": "silu",
+ "hidden_size": 2048,
+ "in_channels": 192,
+ "initializer_range": 0.02,
+ "intermediate_size": 6144,
+ "layer_types": [
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention",
+ "sliding_attention",
+ "full_attention"
+ ],
+ "max_position_embeddings": 32768,
+ "model_type": "acestep",
+ "num_attention_heads": 16,
+ "num_attention_pooler_hidden_layers": 2,
+ "num_audio_decoder_hidden_layers": 24,
+ "num_hidden_layers": 24,
+ "num_key_value_heads": 8,
+ "num_lyric_encoder_hidden_layers": 8,
+ "num_timbre_encoder_hidden_layers": 4,
+ "patch_size": 2,
+ "pool_window_size": 5,
+ "rms_norm_eps": 1e-06,
+ "rope_scaling": null,
+ "rope_theta": 1000000,
+ "sliding_window": 128,
+ "text_hidden_dim": 1024,
+ "timbre_fix_frame": 750,
+ "timbre_hidden_dim": 64,
+ "timestep_mu": -0.4,
+ "timestep_sigma": 1.0,
+ "transformers_version": "4.57.0.dev0",
+ "use_cache": true,
+ "use_sliding_window": true,
+ "vocab_size": 64003,
+ "is_turbo": true
+}
diff --git a/models/TTS/ace_step15/models/__init__.py b/models/TTS/ace_step15/models/__init__.py
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/models/TTS/ace_step15/models/__init__.py
@@ -0,0 +1 @@
+
diff --git a/models/TTS/ace_step15/models/ace_step15_hf.py b/models/TTS/ace_step15/models/ace_step15_hf.py
new file mode 100644
index 0000000..b412173
--- /dev/null
+++ b/models/TTS/ace_step15/models/ace_step15_hf.py
@@ -0,0 +1,16 @@
+from __future__ import annotations
+
+from .configuration_acestep_v15 import AceStepConfig
+from .modeling_acestep_v15_turbo import AceStepConditionGenerationModel as _AceStepHFModel
+
+
+class AceStepConditionGenerationModel(_AceStepHFModel):
+ @classmethod
+ def from_config(cls, config):
+ if hasattr(config, "to_dict"):
+ config = config.to_dict()
+ else:
+ config = dict(config)
+ config.pop("_class_name", None)
+ config.pop("_diffusers_version", None)
+ return cls(AceStepConfig(**config))
diff --git a/models/TTS/ace_step15/models/configuration_acestep_v15.py b/models/TTS/ace_step15/models/configuration_acestep_v15.py
new file mode 100644
index 0000000..965a1b7
--- /dev/null
+++ b/models/TTS/ace_step15/models/configuration_acestep_v15.py
@@ -0,0 +1,263 @@
+# coding=utf-8
+# Copyright 2024 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""AceStep model configuration"""
+
+from transformers.configuration_utils import PretrainedConfig, layer_type_validation
+from transformers.modeling_rope_utils import rope_config_validation
+from transformers.utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class AceStepConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`AceStepModel`]. It is used to instantiate an
+ AceStep model according to the specified arguments, defining the model architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 64003):
+ Vocabulary size of the AceStep model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling the model.
+ hidden_size (`int`, *optional*, defaults to 4096):
+ Dimension of the hidden representations.
+ intermediate_size (`int`, *optional*, defaults to 22016):
+ Dimension of the MLP representations.
+ num_hidden_layers (`int`, *optional*, defaults to 32):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 32):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ num_key_value_heads (`int`, *optional*, defaults to 32):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `32`.
+ head_dim (`int`, *optional*, defaults to 128):
+ The attention head dimension.
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the decoder.
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
+ The maximum sequence length that this model might ever be used with.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
+ The epsilon used by the rms normalization layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
+ Whether the model's input and output word embeddings should be tied.
+ rope_theta (`float`, *optional*, defaults to 10000.0):
+ The base period of the RoPE embeddings.
+ rope_scaling (`Dict`, *optional*):
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
+ accordingly.
+ Expected contents:
+ `rope_type` (`str`):
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
+ 'llama3'], with 'default' being the original RoPE implementation.
+ `factor` (`float`, *optional*):
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
+ original maximum pre-trained length.
+ `original_max_position_embeddings` (`int`, *optional*):
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
+ pretraining.
+ `attention_factor` (`float`, *optional*):
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
+ `factor` field to infer the suggested value.
+ `beta_fast` (`float`, *optional*):
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
+ ramp function. If unspecified, it defaults to 32.
+ `beta_slow` (`float`, *optional*):
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
+ ramp function. If unspecified, it defaults to 1.
+ `short_factor` (`list[float]`, *optional*):
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
+ size divided by the number of attention heads divided by 2
+ `long_factor` (`list[float]`, *optional*):
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
+ size divided by the number of attention heads divided by 2
+ `low_freq_factor` (`float`, *optional*):
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
+ `high_freq_factor` (`float`, *optional*):
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
+ use_sliding_window (`bool`, *optional*, defaults to `False`):
+ Whether to use sliding window attention.
+ sliding_window (`int`, *optional*, defaults to 4096):
+ Sliding window attention (SWA) window size. If not specified, will default to `4096`.
+ layer_types (`list`, *optional*):
+ Attention pattern for each layer.
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+
+ ```python
+ >>> from acestep.models import AceStepConfig
+
+ >>> # Initializing an AceStep configuration
+ >>> configuration = AceStepConfig()
+
+ >>> # Initializing a model from the configuration
+ >>> model = AceStepConditionGenerationModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "acestep"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ # Default tensor parallel plan for the base model
+ base_model_tp_plan = {
+ "layers.*.self_attn.q_proj": "colwise",
+ "layers.*.self_attn.k_proj": "colwise",
+ "layers.*.self_attn.v_proj": "colwise",
+ "layers.*.self_attn.o_proj": "rowwise",
+ "layers.*.mlp.gate_proj": "colwise",
+ "layers.*.mlp.up_proj": "colwise",
+ "layers.*.mlp.down_proj": "rowwise",
+ }
+ base_model_pp_plan = {
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
+ "norm": (["hidden_states"], ["hidden_states"]),
+ }
+ def __init__(
+ self,
+ vocab_size=64003,
+ fsq_dim=2048,
+ fsq_input_levels=[8, 8, 8, 5, 5, 5],
+ fsq_input_num_quantizers=1,
+ hidden_size=2048,
+ intermediate_size=6144,
+ num_hidden_layers=24,
+ num_attention_heads=16,
+ num_key_value_heads=8,
+ head_dim=128,
+ hidden_act="silu",
+ max_position_embeddings=32768,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=True,
+ tie_word_embeddings=True,
+ rope_theta=1000000,
+ rope_scaling=None,
+ attention_bias=False,
+ use_sliding_window=True,
+ sliding_window=128,
+ layer_types=None,
+ attention_dropout=0.0,
+ num_lyric_encoder_hidden_layers=8,
+ audio_acoustic_hidden_dim=64,
+ pool_window_size=5,
+ text_hidden_dim=1024,
+ in_channels=192,
+ data_proportion=0.5,
+ timestep_mu=-0.4,
+ timestep_sigma=1.0,
+ timbre_hidden_dim=64,
+ num_timbre_encoder_hidden_layers=4,
+ timbre_fix_frame=750,
+ patch_size=2,
+ num_attention_pooler_hidden_layers=2,
+ num_audio_decoder_hidden_layers=24,
+ model_version="turbo",
+ **kwargs,
+ ):
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.use_sliding_window = use_sliding_window
+ self.sliding_window = sliding_window if self.use_sliding_window else None
+
+ # Text encoder configuration
+ self.text_hidden_dim = text_hidden_dim
+
+ # Lyric encoder configuration
+ self.num_lyric_encoder_hidden_layers = num_lyric_encoder_hidden_layers
+ self.patch_size = patch_size
+
+ # Audio semantic token generation configuration
+ self.audio_acoustic_hidden_dim = audio_acoustic_hidden_dim
+ self.pool_window_size = pool_window_size
+ self.in_channels = in_channels
+ self.data_proportion = data_proportion
+ self.timestep_mu = timestep_mu
+ self.timestep_sigma = timestep_sigma
+
+ # FSQ (Finite Scalar Quantization) configuration
+ self.fsq_dim = fsq_dim
+ self.fsq_input_levels = fsq_input_levels
+ self.fsq_input_num_quantizers = fsq_input_num_quantizers
+
+ # Timbre encoder configuration
+ self.timbre_hidden_dim = timbre_hidden_dim
+ self.num_timbre_encoder_hidden_layers = num_timbre_encoder_hidden_layers
+ self.timbre_fix_frame = timbre_fix_frame
+ self.num_attention_pooler_hidden_layers = num_attention_pooler_hidden_layers
+ self.num_audio_decoder_hidden_layers = num_audio_decoder_hidden_layers
+ self.vocab_size = vocab_size
+
+ # Backward compatibility: ensure num_key_value_heads is set
+ if num_key_value_heads is None:
+ num_key_value_heads = num_attention_heads
+
+ self.num_key_value_heads = num_key_value_heads
+ self.head_dim = head_dim
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.use_cache = use_cache
+ self.rope_theta = rope_theta
+ self.rope_scaling = rope_scaling
+ self.attention_bias = attention_bias
+ self.attention_dropout = attention_dropout
+ self.model_version = model_version
+
+ # Validate rotary position embeddings parameters
+ # Backward compatibility: if there is a 'type' field, move it to 'rope_type'
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
+ rope_config_validation(self)
+
+ self.layer_types = layer_types
+
+ # Set default layer types if not specified
+ if self.layer_types is None:
+ self.layer_types = [
+ "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
+ ]
+ layer_type_validation(self.layer_types)
+
+ super().__init__(
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+
+__all__ = ["AceStepConfig"]
diff --git a/models/TTS/ace_step15/models/modeling_acestep_v15_turbo.py b/models/TTS/ace_step15/models/modeling_acestep_v15_turbo.py
new file mode 100644
index 0000000..8deefdf
--- /dev/null
+++ b/models/TTS/ace_step15/models/modeling_acestep_v15_turbo.py
@@ -0,0 +1,2136 @@
+# Copyright 2025 The ACESTEO Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import time
+from typing import Callable, List, Optional, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from einops import rearrange
+
+# Transformers imports (sorted by submodule, then alphabetically)
+from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
+from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
+from transformers.modeling_layers import GradientCheckpointingLayer
+from transformers.modeling_outputs import BaseModelOutput
+from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from transformers.processing_utils import Unpack
+from transformers.utils import auto_docstring, can_return_tuple, logging
+from transformers.models.qwen3.modeling_qwen3 import (
+ Qwen3MLP,
+ Qwen3RMSNorm,
+ Qwen3RotaryEmbedding,
+ apply_rotary_pos_emb,
+ eager_attention_forward,
+)
+
+from vector_quantize_pytorch import ResidualFSQ
+
+# Local config import with fallback
+try:
+ from .configuration_acestep_v15 import AceStepConfig
+except ImportError:
+ from configuration_acestep_v15 import AceStepConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def create_4d_mask(
+ seq_len: int,
+ dtype: torch.dtype,
+ device: torch.device,
+ attention_mask: Optional[torch.Tensor] = None, # [Batch, Seq_Len]
+ sliding_window: Optional[int] = None,
+ is_sliding_window: bool = False,
+ is_causal: bool = True,
+) -> torch.Tensor:
+ """
+ General 4D Attention Mask generator compatible with CPU/Mac/SDPA and Eager mode.
+ Supports use cases:
+ 1. Causal Full: is_causal=True, is_sliding_window=False (standard GPT)
+ 2. Causal Sliding: is_causal=True, is_sliding_window=True (Mistral/Qwen local window)
+ 3. Bidirectional Full: is_causal=False, is_sliding_window=False (BERT/Encoder)
+ 4. Bidirectional Sliding: is_causal=False, is_sliding_window=True (Longformer local)
+
+ Returns:
+ [Batch, 1, Seq_Len, Seq_Len] additive mask (0.0 for keep, -inf for mask)
+ """
+ # ------------------------------------------------------
+ # 1. Construct basic geometry mask [Seq_Len, Seq_Len]
+ # ------------------------------------------------------
+
+ # Build index matrices
+ # i (Query): [0, 1, ..., L-1]
+ # j (Key): [0, 1, ..., L-1]
+ indices = torch.arange(seq_len, device=device)
+ # diff = i - j
+ diff = indices.unsqueeze(1) - indices.unsqueeze(0)
+
+ # Initialize all True (all positions visible)
+ valid_mask = torch.ones((seq_len, seq_len), device=device, dtype=torch.bool)
+
+ # (A) Handle causality (Causal)
+ if is_causal:
+ # i >= j => diff >= 0
+ valid_mask = valid_mask & (diff >= 0)
+
+ # (B) Handle sliding window
+ if is_sliding_window and sliding_window is not None:
+ if is_causal:
+ # Causal sliding: only attend to past window steps
+ # i - j <= window => diff <= window
+ # (diff >= 0 already handled above)
+ valid_mask = valid_mask & (diff <= sliding_window)
+ else:
+ # Bidirectional sliding: attend past and future window steps
+ # |i - j| <= window => abs(diff) <= sliding_window
+ valid_mask = valid_mask & (torch.abs(diff) <= sliding_window)
+
+ # Expand dimensions to [1, 1, Seq_Len, Seq_Len] for broadcasting
+ valid_mask = valid_mask.unsqueeze(0).unsqueeze(0)
+
+ # ------------------------------------------------------
+ # 2. Apply padding mask (Key Masking)
+ # ------------------------------------------------------
+ if attention_mask is not None:
+ # attention_mask shape: [Batch, Seq_Len] (1=valid, 0=padding)
+ # We want to mask out invalid keys (columns)
+ # Expand shape: [Batch, 1, 1, Seq_Len]
+ padding_mask_4d = attention_mask.view(attention_mask.shape[0], 1, 1, seq_len).to(torch.bool)
+
+ # Broadcasting: Geometry Mask [1, 1, L, L] & Padding Mask [B, 1, 1, L]
+ # Result shape: [B, 1, L, L]
+ valid_mask = valid_mask & padding_mask_4d
+
+ # ------------------------------------------------------
+ # 3. Convert to additive mask
+ # ------------------------------------------------------
+ # Get the minimal value for current dtype
+ min_dtype = torch.finfo(dtype).min
+
+ # Create result tensor filled with -inf by default
+ mask_tensor = torch.full(valid_mask.shape, min_dtype, dtype=dtype, device=device)
+
+ # Set valid positions to 0.0
+ mask_tensor.masked_fill_(valid_mask, 0.0)
+
+ return mask_tensor
+
+
+def pack_sequences(hidden1: torch.Tensor, hidden2: torch.Tensor, mask1: torch.Tensor, mask2: torch.Tensor):
+ """
+ Pack two sequences by concatenating and sorting them based on mask values.
+
+ Args:
+ hidden1: First hidden states tensor of shape [B, L1, D]
+ hidden2: Second hidden states tensor of shape [B, L2, D]
+ mask1: First mask tensor of shape [B, L1]
+ mask2: Second mask tensor of shape [B, L2]
+
+ Returns:
+ Tuple of (packed_hidden_states, new_mask) where:
+ - packed_hidden_states: Packed hidden states with valid tokens (mask=1) first, shape [B, L1+L2, D]
+ - new_mask: New mask tensor indicating valid positions, shape [B, L1+L2]
+ """
+ # Step 1: Concatenate hidden states and masks along sequence dimension
+ hidden_cat = torch.cat([hidden1, hidden2], dim=1) # [B, L, D]
+ mask_cat = torch.cat([mask1, mask2], dim=1) # [B, L]
+
+ B, L, D = hidden_cat.shape
+
+ # Step 2: Sort indices so that mask values of 1 come before 0
+ sort_idx = mask_cat.argsort(dim=1, descending=True, stable=True) # [B, L]
+
+ # Step 3: Reorder hidden states using sorted indices
+ hidden_left = torch.gather(hidden_cat, 1, sort_idx.unsqueeze(-1).expand(B, L, D))
+
+ # Step 4: Create new mask based on valid sequence lengths
+ lengths = mask_cat.sum(dim=1) # [B]
+ new_mask = (torch.arange(L, dtype=torch.long, device=hidden_cat.device).unsqueeze(0) < lengths.unsqueeze(1))
+
+ return hidden_left, new_mask
+
+
+def sample_t_r(batch_size, device, dtype, data_proportion=0.0, timestep_mu=-0.4, timestep_sigma=1.0, use_meanflow=True):
+ """
+ Sample timestep t and r for flow matching training.
+
+ Args:
+ batch_size: Batch size
+ device: Device to create tensors on
+ dtype: Data type for tensors
+ data_proportion: Proportion of data samples (0.0 to 1.0)
+ timestep_mu: Mean for timestep sampling
+ timestep_sigma: Standard deviation for timestep sampling
+ use_meanflow: Whether to use meanflow (if False, data_proportion is set to 1.0)
+
+ Returns:
+ Tuple of (t, r) tensors, each of shape [batch_size]
+ """
+ t = torch.sigmoid(torch.randn((batch_size,), device=device, dtype=dtype) * timestep_sigma + timestep_mu)
+ r = torch.sigmoid(torch.randn((batch_size,), device=device, dtype=dtype) * timestep_sigma + timestep_mu)
+ # Assign t = max, r = min, for each pair
+ t, r = torch.maximum(t, r), torch.minimum(t, r)
+ if not use_meanflow:
+ data_proportion = 1.0
+ data_size = int(batch_size * data_proportion)
+ zero_mask = torch.arange(batch_size, device=device) < data_size
+ r = torch.where(zero_mask, t, r)
+ return t, r
+
+
+class TimestepEmbedding(nn.Module):
+ """
+ Timestep embedding module for diffusion models.
+
+ Converts timestep values into high-dimensional embeddings using sinusoidal
+ positional encoding, followed by MLP layers. Used for conditioning diffusion
+ models on timestep information.
+ """
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ scale: float = 1000,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, bias=True)
+ self.act1 = nn.SiLU()
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim, bias=True)
+ self.in_channels = in_channels
+
+ self.act2 = nn.SiLU()
+ self.time_proj = nn.Linear(time_embed_dim, time_embed_dim * 6)
+ self.scale = scale
+
+ def timestep_embedding(self, t, dim, max_period=10000):
+ """
+ Create sinusoidal timestep embeddings.
+
+ Args:
+ t: A 1-D tensor of N indices, one per batch element. These may be fractional.
+ dim: The dimension of the output embeddings.
+ max_period: Controls the minimum frequency of the embeddings.
+
+ Returns:
+ An (N, D) tensor of positional embeddings.
+ """
+ t = t * self.scale
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
+ ).to(device=t.device)
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+ def forward(self, t):
+ t_freq = self.timestep_embedding(t, self.in_channels)
+ temb = self.linear_1(t_freq.to(t.dtype))
+ temb = self.act1(temb)
+ temb = self.linear_2(temb)
+ timestep_proj = self.time_proj(self.act2(temb)).unflatten(1, (6, -1))
+ return temb, timestep_proj
+
+class AceStepAttention(nn.Module):
+ """
+ Multi-headed attention module for AceStep model.
+
+ Implements the attention mechanism from 'Attention Is All You Need' paper,
+ with support for both self-attention and cross-attention modes. Uses RMSNorm
+ for query and key normalization, and supports sliding window attention for
+ efficient long-sequence processing.
+ """
+
+ def __init__(self, config: AceStepConfig, layer_idx: int, is_cross_attention: bool = False, is_causal: bool = False):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.scaling = self.head_dim**-0.5
+ self.attention_dropout = config.attention_dropout
+ if is_cross_attention:
+ is_causal = False
+ self.is_causal = is_causal
+ self.is_cross_attention = is_cross_attention
+
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias)
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias)
+ # Apply RMS normalization only on the head dimension (unlike OLMo)
+ self.q_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.k_norm = Qwen3RMSNorm(self.head_dim, eps=config.rms_norm_eps)
+ self.attention_type = config.layer_types[layer_idx]
+ self.sliding_window = config.sliding_window if config.layer_types[layer_idx] == "sliding_attention" else None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ past_key_value: Optional[Cache] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor] = None,
+ output_attentions: Optional[bool] = False,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ # Project and normalize query states
+ query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+
+ # Determine if this is cross-attention (requires encoder_hidden_states)
+ is_cross_attention = self.is_cross_attention and encoder_hidden_states is not None
+
+ # Cross-attention path: attend to encoder hidden states
+ if is_cross_attention:
+ encoder_hidden_shape = (*encoder_hidden_states.shape[:-1], -1, self.head_dim)
+ if past_key_value is not None:
+ is_updated = past_key_value.is_updated.get(self.layer_idx)
+ # After the first generated token, we can reuse all key/value states from cache
+ curr_past_key_value = past_key_value.cross_attention_cache
+
+ # Conditions for calculating key and value states
+ if not is_updated:
+ # Compute and cache K/V for the first time
+ key_states = self.k_norm(self.k_proj(encoder_hidden_states).view(encoder_hidden_shape)).transpose(1, 2)
+ value_states = self.v_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
+ # Update cache: save all key/value states to cache for fast auto-regressive generation
+ key_states, value_states = curr_past_key_value.update(key_states, value_states, self.layer_idx)
+ # Set flag that this layer's cross-attention cache is updated
+ past_key_value.is_updated[self.layer_idx] = True
+ else:
+ # Reuse cached key/value states for subsequent tokens
+ key_states = curr_past_key_value.layers[self.layer_idx].keys
+ value_states = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ # No cache used, compute K/V directly
+ key_states = self.k_norm(self.k_proj(encoder_hidden_states).view(encoder_hidden_shape)).transpose(1, 2)
+ value_states = self.v_proj(encoder_hidden_states).view(encoder_hidden_shape).transpose(1, 2)
+
+ # Self-attention path: attend to the same sequence
+ else:
+ # Project and normalize key/value states for self-attention
+ key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ # Apply rotary position embeddings (RoPE) if provided
+ if position_embeddings is not None:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ # Update cache for auto-regressive generation
+ if past_key_value is not None:
+ # Sin and cos are specific to RoPE models; cache_position needed for the static cache
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
+
+ attention_interface: Callable = eager_attention_forward
+ if is_cross_attention and output_attentions:
+ attention_interface: Callable = eager_attention_forward
+ elif self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=self.attention_dropout if self.training else 0.0,
+ scaling=self.scaling,
+ sliding_window=self.sliding_window if not self.is_cross_attention else None,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class AceStepEncoderLayer(GradientCheckpointingLayer):
+ """
+ Encoder layer for AceStep model.
+
+ Consists of self-attention and MLP (feed-forward) sub-layers with residual connections.
+ """
+
+ def __init__(self, config, layer_idx: int):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.config = config
+ self.layer_idx = layer_idx
+
+ # Self-attention sub-layer
+ self.self_attn = AceStepAttention(
+ config=config,
+ layer_idx=layer_idx,
+ is_cross_attention=False,
+ is_causal=False,
+ )
+ self.input_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ # MLP (feed-forward) sub-layer
+ self.mlp = Qwen3MLP(config)
+ self.attention_type = config.layer_types[layer_idx]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = False,
+ **kwargs,
+ ) -> tuple[
+ torch.FloatTensor,
+ Optional[tuple[torch.FloatTensor, torch.FloatTensor]],
+ ]:
+ # Self-attention with residual connection
+ residual = hidden_states
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_attentions=output_attentions,
+ # Encoders don't use cache
+ use_cache=False,
+ past_key_value=None,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ # MLP with residual connection
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ return outputs
+
+
+class AceStepDiTLayer(GradientCheckpointingLayer):
+ """
+ DiT (Diffusion Transformer) layer for AceStep model.
+
+ Implements a transformer layer with three main components:
+ 1. Self-attention with adaptive layer norm (AdaLN)
+ 2. Cross-attention (optional) for conditioning on encoder outputs
+ 3. Feed-forward MLP with adaptive layer norm
+
+ Uses scale-shift modulation from timestep embeddings for adaptive normalization.
+ """
+ def __init__(self, config: AceStepConfig, layer_idx: int, use_cross_attention: bool = True):
+ super().__init__()
+
+ # 1. Self-attention sub-layer with adaptive normalization
+ self.self_attn_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.self_attn = AceStepAttention(config=config, layer_idx=layer_idx)
+
+ # 2. Cross-attention sub-layer (optional, for encoder conditioning)
+ self.use_cross_attention = use_cross_attention
+ if self.use_cross_attention:
+ self.cross_attn_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.cross_attn = AceStepAttention(config=config, layer_idx=layer_idx, is_cross_attention=True)
+
+ # 3. Feed-forward MLP sub-layer with adaptive normalization
+ self.mlp_norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.mlp = Qwen3MLP(config)
+
+ # Scale-shift table for adaptive layer norm modulation (6 values: 3 for self-attn, 3 for MLP)
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, config.hidden_size) / config.hidden_size**0.5)
+ self.attention_type = config.layer_types[layer_idx]
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
+ temb: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_value: Optional[EncoderDecoderCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ cache_position: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> torch.Tensor:
+
+ # Extract scale-shift parameters for adaptive layer norm from timestep embeddings
+ # 6 values: (shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa)
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb
+ ).chunk(6, dim=1)
+
+ # Step 1: Self-attention with adaptive layer norm (AdaLN)
+ # Apply adaptive normalization: norm(x) * (1 + scale) + shift
+ norm_hidden_states = (self.self_attn_norm(hidden_states) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output, self_attn_weights = self.self_attn(
+ hidden_states=norm_hidden_states,
+ position_embeddings=position_embeddings,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_attentions=output_attentions,
+ use_cache=False,
+ past_key_value=None,
+ **kwargs,
+ )
+ # Apply gated residual connection: x = x + attn_output * gate
+ hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)
+
+ # Step 2: Cross-attention (if enabled) for conditioning on encoder outputs
+ if self.use_cross_attention:
+ norm_hidden_states = self.cross_attn_norm(hidden_states).type_as(hidden_states)
+ attn_output, cross_attn_weights = self.cross_attn(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ # Standard residual connection for cross-attention
+ hidden_states = hidden_states + attn_output
+
+ # Step 3: Feed-forward (MLP) with adaptive layer norm
+ # Apply adaptive normalization for MLP: norm(x) * (1 + scale) + shift
+ norm_hidden_states = (self.mlp_norm(hidden_states) * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states)
+ ff_output = self.mlp(norm_hidden_states)
+ # Apply gated residual connection: x = x + mlp_output * gate
+ hidden_states = (hidden_states + ff_output * c_gate_msa).type_as(hidden_states)
+
+ outputs = (hidden_states,)
+ if output_attentions:
+ outputs += (self_attn_weights, cross_attn_weights)
+
+ return outputs
+
+
+@auto_docstring
+class AceStepPreTrainedModel(PreTrainedModel):
+ config_class = AceStepConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["AceStepEncoderLayer", "AceStepDiTLayer"]
+ _skip_keys_device_placement = ["past_key_values"]
+ _supports_flash_attn_3 = True
+ _supports_flash_attn_2 = True
+ _supports_sdpa = True
+ _supports_flex_attn = True
+ _supports_cache_class = True
+ _supports_quantized_cache = True
+ _supports_static_cache = True
+ _supports_attention_backend = True
+
+ def _init_weights(self, module):
+ """
+ Initialize weights for different module types.
+
+ TODO: Support separate initialization for encoders and decoders.
+ """
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, Qwen3RMSNorm):
+ module.weight.data.fill_(1.0)
+
+
+class AceStepLyricEncoder(AceStepPreTrainedModel):
+ """
+ Encoder for processing lyric text embeddings.
+
+ Encodes lyric text hidden states using a transformer encoder architecture
+ with bidirectional attention. Projects text embeddings to model hidden size
+ and processes them through multiple encoder layers.
+ """
+ def __init__(self, config):
+ super().__init__(config)
+
+ # Project text embeddings to model hidden size
+ self.embed_tokens = nn.Linear(config.text_hidden_dim, config.hidden_size)
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+
+ # Stack of encoder layers
+ self.layers = nn.ModuleList(
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_lyric_encoder_hidden_layers)]
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutput:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ assert input_ids is None, "Only `input_ids` is supported for the lyric encoder."
+ assert attention_mask is not None, "Attention mask must be provided for the lyric encoder."
+ assert inputs_embeds is not None, "Inputs embeddings must be provided for the lyric encoder."
+
+ # Project input embeddings: N x T x text_hidden_dim -> N x T x hidden_size
+ inputs_embeds = self.embed_tokens(inputs_embeds)
+ # Cache position: only used for mask construction (not for actual caching)
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
+
+ # Positional IDs
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ # Attention masks
+ seq_len = inputs_embeds.shape[1]
+ dtype = inputs_embeds.dtype
+ device = inputs_embeds.device
+
+ # ?????? Flash Attention 2
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
+
+ # ??? Mask ??
+ full_attn_mask = None
+ sliding_attn_mask = None
+
+ if is_flash_attn:
+ # -------------------------------------------------------
+ # ?? A: Flash Attention ??
+ # -------------------------------------------------------
+ # FA ??? 4D Mask?
+ # ??? padding mask (attention_mask [B, L])?????????
+ # ???? padding mask?? None?
+ # ??????? Layer ???? FA kernel ? sliding_window ?????
+ full_attn_mask = attention_mask
+
+ # ???????????????????FA ????????????? padding mask
+ # Layer ?????????? sliding window ? kernel
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
+
+ else:
+ # -------------------------------------------------------
+ # ?? B: CPU / Mac / SDPA (Eager ??)
+ # -------------------------------------------------------
+ # ?????? 4D Mask [B, 1, L, L]
+
+ # 1. Full Attention (Bidirectional, Global)
+ # ????? create_causal_mask + bidirectional
+ full_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+
+ # 2. Sliding Attention (Bidirectional, Local)
+ # ????? create_sliding_window... + bidirectional
+ if self.config.use_sliding_window:
+ sliding_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=self.config.sliding_window,
+ is_sliding_window=True, # <--- ??????
+ is_causal=False # <--- ????????
+ )
+
+ # ?? Mapping
+ self_attn_mask_mapping = {
+ "full_attention": full_attn_mask,
+ "sliding_attention": sliding_attn_mask,
+ }
+
+ # Initialize hidden states with input embeddings
+ hidden_states = inputs_embeds
+
+ # Create position embeddings to be shared across all layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ # Pass through transformer layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for layer_module in self.layers[: self.config.num_hidden_layers]:
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = layer_module(
+ hidden_states,
+ position_embeddings,
+ self_attn_mask_mapping[layer_module.attention_type],
+ position_ids,
+ output_attentions,
+ **flash_attn_kwargs,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.norm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+
+
+class AttentionPooler(AceStepPreTrainedModel):
+ """
+ Attention-based pooling module.
+
+ Pools sequences of patches using a special token and attention mechanism.
+ The special token attends to all patches and its output is used as the
+ pooled representation. Used for aggregating patch-level features into
+ sequence-level representations.
+ """
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.embed_tokens = nn.Linear(config.hidden_size, config.hidden_size)
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ # Special token used for pooling (CLS-like token)
+ self.special_token = nn.Parameter(torch.randn(1, 1, config.hidden_size) * 0.02)
+ self.layers = nn.ModuleList(
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_attention_pooler_hidden_layers)]
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ def forward(self,
+ x,
+ attention_mask: Optional[torch.Tensor] = None,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutput:
+ B, T, P, D = x.shape
+ x = self.embed_tokens(x)
+ special_tokens = self.special_token.expand(B, T, 1, -1)
+ x = torch.cat([special_tokens, x], dim=2)
+ x = rearrange(x, "b t p c -> (b t) p c")
+
+ # Cache position: only used for mask construction.
+ cache_position = torch.arange(0, x.shape[1], device=x.device)
+ # Postional ids.
+ position_ids = cache_position.unsqueeze(0)
+
+ # embed positions
+ hidden_states = x
+
+ # create position embeddings to be shared across the decoder layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ seq_len = x.shape[1]
+ dtype = x.dtype
+ device = x.device
+
+ # ?????? Flash Attention 2
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
+
+ # ??? Mask ??
+ full_attn_mask = None
+ sliding_attn_mask = None
+
+ if is_flash_attn:
+ # -------------------------------------------------------
+ # ?? A: Flash Attention ??
+ # -------------------------------------------------------
+ # FA ??? 4D Mask?
+ # ??? padding mask (attention_mask [B, L])?????????
+ # ???? padding mask?? None?
+ # ??????? Layer ???? FA kernel ? sliding_window ?????
+ full_attn_mask = attention_mask
+
+ # ???????????????????FA ????????????? padding mask
+ # Layer ?????????? sliding window ? kernel
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
+
+ else:
+ # -------------------------------------------------------
+ # ?? B: CPU / Mac / SDPA (Eager ??)
+ # -------------------------------------------------------
+ # ?????? 4D Mask [B, 1, L, L]
+
+ # 1. Full Attention (Bidirectional, Global)
+ # ????? create_causal_mask + bidirectional
+ full_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+
+ # 2. Sliding Attention (Bidirectional, Local)
+ # ????? create_sliding_window... + bidirectional
+ if self.config.use_sliding_window:
+ sliding_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=self.config.sliding_window,
+ is_sliding_window=True, # <--- ??????
+ is_causal=False # <--- ????????
+ )
+
+ # ?? Mapping
+ self_attn_mask_mapping = {
+ "full_attention": full_attn_mask,
+ "sliding_attention": sliding_attn_mask,
+ }
+
+ for layer_module in self.layers:
+ layer_outputs = layer_module(
+ hidden_states,
+ position_embeddings,
+ attention_mask=self_attn_mask_mapping[layer_module.attention_type],
+ **flash_attn_kwargs,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ hidden_states = self.norm(hidden_states)
+
+ # Extract the special token output (first position) as pooled representation
+ cls_output = hidden_states[:, 0, :]
+ cls_output = rearrange(cls_output, "(b t) c -> b t c", b=B)
+ return cls_output
+
+
+class AudioTokenDetokenizer(AceStepPreTrainedModel):
+ """
+ Audio token detokenizer module.
+
+ Converts quantized audio tokens back to continuous acoustic representations.
+ Expands each token into multiple patches using special tokens, processes them
+ through encoder layers, and projects to acoustic hidden dimension.
+ """
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.embed_tokens = nn.Linear(config.hidden_size, config.hidden_size)
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ # Special tokens for expanding each quantized token into patches
+ self.special_tokens = nn.Parameter(torch.randn(1, config.pool_window_size, config.hidden_size) * 0.02)
+ self.layers = nn.ModuleList(
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_attention_pooler_hidden_layers)]
+ )
+ # Project back to acoustic hidden dimension
+ self.proj_out = nn.Linear(config.hidden_size, config.audio_acoustic_hidden_dim)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ def forward(self,
+ x,
+ attention_mask: Optional[torch.Tensor] = None,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutput:
+ B, T, D = x.shape
+ x = self.embed_tokens(x)
+ # Expand and add special tokens: N x T x D -> N x T x P x D
+ # Each token is expanded into pool_window_size patches
+ x = x.unsqueeze(2) # N x T x 1 x D
+ x = x.repeat(1, 1, self.config.pool_window_size, 1) # N x T x P x D
+ # Add learnable special tokens to each patch
+ special_tokens = self.special_tokens.expand(B, T, -1, -1)
+ x = x + special_tokens
+ # Reshape for processing: (batch * time) x patches x hidden
+ x = rearrange(x, "b t p c -> (b t) p c")
+
+ # Cache position: only used for mask construction
+ cache_position = torch.arange(0, x.shape[1], device=x.device)
+ # Positional IDs
+ position_ids = cache_position.unsqueeze(0)
+
+ # Initialize hidden states
+ hidden_states = x
+
+ # Create position embeddings to be shared across all layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ seq_len = x.shape[1]
+ dtype = x.dtype
+ device = x.device
+
+ # ?????? Flash Attention 2
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
+
+ # ??? Mask ??
+ full_attn_mask = None
+ sliding_attn_mask = None
+
+ if is_flash_attn:
+ # -------------------------------------------------------
+ # ?? A: Flash Attention ??
+ # -------------------------------------------------------
+ # FA ??? 4D Mask?
+ # ??? padding mask (attention_mask [B, L])?????????
+ # ???? padding mask?? None?
+ # ??????? Layer ???? FA kernel ? sliding_window ?????
+ full_attn_mask = attention_mask
+
+ # ???????????????????FA ????????????? padding mask
+ # Layer ?????????? sliding window ? kernel
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
+
+ else:
+ # -------------------------------------------------------
+ # ?? B: CPU / Mac / SDPA (Eager ??)
+ # -------------------------------------------------------
+ # ?????? 4D Mask [B, 1, L, L]
+
+ # 1. Full Attention (Bidirectional, Global)
+ # ????? create_causal_mask + bidirectional
+ full_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+
+ # 2. Sliding Attention (Bidirectional, Local)
+ # ????? create_sliding_window... + bidirectional
+ if self.config.use_sliding_window:
+ sliding_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=self.config.sliding_window,
+ is_sliding_window=True, # <--- ??????
+ is_causal=False # <--- ????????
+ )
+
+ # ?? Mapping
+ self_attn_mask_mapping = {
+ "full_attention": full_attn_mask,
+ "sliding_attention": sliding_attn_mask,
+ }
+
+ for layer_module in self.layers:
+ layer_outputs = layer_module(
+ hidden_states,
+ position_embeddings,
+ attention_mask=self_attn_mask_mapping[layer_module.attention_type],
+ **flash_attn_kwargs,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ hidden_states = self.norm(hidden_states)
+
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = rearrange(hidden_states, "(b t) p c -> b (t p) c", b=B, p=self.config.pool_window_size)
+ return hidden_states
+
+
+class AceStepTimbreEncoder(AceStepPreTrainedModel):
+ """
+ Encoder for extracting timbre embeddings from reference audio.
+
+ Processes packed reference audio acoustic features to extract timbre
+ representations. Uses a special token (CLS-like) to aggregate information
+ from the entire reference audio sequence. Outputs are unpacked back to
+ batch format for use in conditioning.
+ """
+ def __init__(self, config):
+ super().__init__(config)
+
+ # Project acoustic features to model hidden size
+ self.embed_tokens = nn.Linear(config.timbre_hidden_dim, config.hidden_size)
+ self.norm = Qwen3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.rotary_emb = Qwen3RotaryEmbedding(config=config)
+ self.gradient_checkpointing = False
+ # Special token for aggregating timbre information (prepended to sequence)
+ self.special_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+ self.layers = nn.ModuleList(
+ [AceStepEncoderLayer(config, layer_idx) for layer_idx in range(config.num_timbre_encoder_hidden_layers)]
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def unpack_timbre_embeddings(self, timbre_embs_packed, refer_audio_order_mask):
+ """
+ Unpack packed timbre embeddings into batch format.
+
+ Args:
+ timbre_embs_packed: Packed timbre embeddings of shape [N, d]
+ refer_audio_order_mask: Order mask indicating batch assignment for each packed embedding
+
+ Returns:
+ Tuple of (unpacked_embeddings, mask):
+ - unpacked_embeddings: Unpacked embeddings of shape [B, max_count, d]
+ - new_mask: Mask indicating valid positions, shape [B, max_count]
+ """
+ N, d = timbre_embs_packed.shape
+ device = timbre_embs_packed.device
+ dtype = timbre_embs_packed.dtype
+
+ # Get batch size
+ B = int(refer_audio_order_mask.max().item() + 1)
+
+ # Calculate element count and positions for each batch
+ counts = torch.bincount(refer_audio_order_mask, minlength=B)
+ max_count = counts.max().item()
+
+ # Calculate positions within batch
+ sorted_indices = torch.argsort(refer_audio_order_mask * N + torch.arange(N, device=device), stable=True)
+ sorted_batch_ids = refer_audio_order_mask[sorted_indices]
+
+ positions = torch.arange(N, device=device)
+ batch_starts = torch.cat([torch.tensor([0], device=device),
+ torch.cumsum(counts, dim=0)[:-1]])
+ positions_in_sorted = positions - batch_starts[sorted_batch_ids]
+
+ inverse_indices = torch.empty_like(sorted_indices)
+ inverse_indices[sorted_indices] = torch.arange(N, device=device)
+ positions_in_batch = positions_in_sorted[inverse_indices]
+
+ # Use one-hot encoding and matrix multiplication (gradient-friendly approach)
+ # Create one-hot encoding
+ indices_2d = refer_audio_order_mask * max_count + positions_in_batch # (N,)
+ one_hot = F.one_hot(indices_2d, num_classes=B * max_count).to(dtype) # (N, B*max_count)
+
+ # Rearrange using matrix multiplication
+ timbre_embs_flat = one_hot.t() @ timbre_embs_packed # (B*max_count, d)
+ timbre_embs_unpack = timbre_embs_flat.reshape(B, max_count, d)
+
+ # Create mask indicating valid positions
+ mask_flat = (one_hot.sum(dim=0) > 0).long() # (B*max_count,)
+ new_mask = mask_flat.reshape(B, max_count)
+
+ return timbre_embs_unpack, new_mask
+
+ @can_return_tuple
+ def forward(
+ self,
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.FloatTensor] = None,
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutput:
+ inputs_embeds = refer_audio_acoustic_hidden_states_packed
+ # Project embeddings: N x T x timbre_hidden_dim -> N x T x hidden_size
+ inputs_embeds = self.embed_tokens(inputs_embeds)
+ # Prepend special token for timbre aggregation (CLS-like token)
+ # inputs_embeds = torch.cat([self.special_token.expand(inputs_embeds.shape[0], 1, -1), inputs_embeds], dim=1)
+ # Cache position: only used for mask construction (not for actual caching)
+ cache_position = torch.arange(0, inputs_embeds.shape[1], device=inputs_embeds.device)
+ # Positional IDs
+ position_ids = cache_position.unsqueeze(0)
+
+ seq_len = inputs_embeds.shape[1]
+ dtype = inputs_embeds.dtype
+ device = inputs_embeds.device
+
+ # ?????? Flash Attention 2
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
+
+ # ??? Mask ??
+ full_attn_mask = None
+ sliding_attn_mask = None
+
+ if is_flash_attn:
+ # -------------------------------------------------------
+ # ?? A: Flash Attention ??
+ # -------------------------------------------------------
+ # FA ??? 4D Mask?
+ # ??? padding mask (attention_mask [B, L])?????????
+ # ???? padding mask?? None?
+ # ??????? Layer ???? FA kernel ? sliding_window ?????
+ full_attn_mask = attention_mask
+
+ # ???????????????????FA ????????????? padding mask
+ # Layer ?????????? sliding window ? kernel
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
+
+ else:
+ # -------------------------------------------------------
+ # ?? B: CPU / Mac / SDPA (Eager ??)
+ # -------------------------------------------------------
+ # ?????? 4D Mask [B, 1, L, L]
+
+ # 1. Full Attention (Bidirectional, Global)
+ # ????? create_causal_mask + bidirectional
+ full_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+
+ # 2. Sliding Attention (Bidirectional, Local)
+ # ????? create_sliding_window... + bidirectional
+ if self.config.use_sliding_window:
+ sliding_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=self.config.sliding_window,
+ is_sliding_window=True, # <--- ??????
+ is_causal=False # <--- ????????
+ )
+
+ # ?? Mapping
+ self_attn_mask_mapping = {
+ "full_attention": full_attn_mask,
+ "sliding_attention": sliding_attn_mask,
+ }
+
+ # Initialize hidden states
+ hidden_states = inputs_embeds
+
+ # Create position embeddings to be shared across all layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+
+ # Pass through transformer layers
+ for layer_module in self.layers[: self.config.num_hidden_layers]:
+ layer_outputs = layer_module(
+ hidden_states,
+ position_embeddings,
+ self_attn_mask_mapping[layer_module.attention_type],
+ position_ids,
+ **flash_attn_kwargs,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ hidden_states = self.norm(hidden_states)
+ # Extract special token output (first position) as timbre embedding: N x T x D -> N x D
+ hidden_states = hidden_states[:, 0, :]
+ # Unpack packed embeddings back to batch format
+ timbre_embs_unpack, timbre_embs_mask = self.unpack_timbre_embeddings(hidden_states, refer_audio_order_mask)
+ return timbre_embs_unpack, timbre_embs_mask
+
+
+class AceStepAudioTokenizer(AceStepPreTrainedModel):
+ """
+ Audio tokenizer module.
+
+ Converts continuous acoustic features into discrete quantized tokens.
+ Process: project -> pool patches -> quantize. Used for converting audio
+ representations into discrete tokens for processing by the diffusion model.
+ """
+ def __init__(self, config):
+ super().__init__(config)
+ # Project acoustic features to hidden size
+ self.audio_acoustic_proj = nn.Linear(config.audio_acoustic_hidden_dim, config.hidden_size)
+ # Pool patches into sequence-level representations
+ self.attention_pooler = AttentionPooler(config)
+ # Quantize continuous representations into discrete tokens
+ self.quantizer = ResidualFSQ(
+ dim=config.fsq_dim,
+ levels=config.fsq_input_levels,
+ num_quantizers=config.fsq_input_num_quantizers
+ )
+ self.pool_window_size = config.pool_window_size
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ def forward(
+ self,
+ hidden_states: Optional[torch.FloatTensor] = None,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ) -> BaseModelOutput:
+
+ # Project acoustic features to hidden size
+ hidden_states = self.audio_acoustic_proj(hidden_states)
+ # Pool sequences: N x T//pool_window_size x pool_window_size x d -> N x T//pool_window_size x d
+ hidden_states = self.attention_pooler(hidden_states)
+ # Quantize continuous representations into discrete tokens: N x T//pool_window_size x d
+ quantized, indices = self.quantizer(hidden_states)
+ return quantized, indices
+
+ def tokenize(self, x):
+ x = rearrange(x, 'n (t_patch p) d -> n t_patch p d', p=self.pool_window_size)
+ quantized, indices = self.forward(x)
+ return quantized, indices
+
+class Lambda(nn.Module):
+ """
+ Wrapper module for arbitrary lambda functions.
+
+ Allows using lambda functions in nn.Sequential by wrapping them in a Module.
+ Useful for simple transformations like transpose operations.
+ """
+ def __init__(self, func):
+ super().__init__()
+ self.func = func
+
+ def forward(self, x):
+ return self.func(x)
+
+
+class AceStepDiTModel(AceStepPreTrainedModel):
+ """
+ DiT (Diffusion Transformer) model for AceStep.
+
+ Main diffusion model that generates audio latents conditioned on text, lyrics,
+ and timbre. Uses patch-based processing with transformer layers, timestep
+ conditioning, and cross-attention to encoder outputs.
+ """
+ def __init__(self, config: AceStepConfig):
+ super().__init__(config)
+ # Rotary position embeddings for transformer layers
+ self.rotary_emb = Qwen3RotaryEmbedding(config)
+ # Stack of DiT transformer layers
+ self.layers = nn.ModuleList(
+ [AceStepDiTLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
+ )
+
+ in_channels = config.in_channels
+ inner_dim = config.hidden_size
+ patch_size = config.patch_size
+ self.patch_size = patch_size
+
+ # Input projection: patch embedding using 1D convolution
+ # Converts sequence into patches for efficient processing
+ self.proj_in = nn.Sequential(
+ Lambda(lambda x: x.transpose(1, 2)), # [B, T, C] -> [B, C, T]
+ nn.Conv1d(
+ in_channels=in_channels,
+ out_channels=inner_dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ padding=0,
+ ),
+ Lambda(lambda x: x.transpose(1, 2)), # [B, C, T//patch_size] -> [B, T//patch_size, C]
+ )
+
+ # Timestep embeddings for diffusion conditioning
+ # Two embeddings: one for timestep t, one for timestep difference (t - r)
+ self.time_embed = TimestepEmbedding(in_channels=256, time_embed_dim=inner_dim)
+ self.time_embed_r = TimestepEmbedding(in_channels=256, time_embed_dim=inner_dim)
+
+ # Project encoder hidden states to model dimension
+ self.condition_embedder = nn.Linear(inner_dim, inner_dim, bias=True)
+
+ # Output normalization and projection
+ # Adaptive layer norm with scale-shift modulation, then de-patchify
+ self.norm_out = Qwen3RMSNorm(inner_dim, eps=config.rms_norm_eps)
+ self.proj_out = nn.Sequential(
+ Lambda(lambda x: x.transpose(1, 2)), # [B, T//patch_size, inner_dim] -> [B, inner_dim, T//patch_size]
+ nn.ConvTranspose1d(
+ in_channels=inner_dim,
+ out_channels=config.audio_acoustic_hidden_dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ padding=0,
+ ),
+ Lambda(lambda x: x.transpose(1, 2)), # [B, out_channels, T] -> [B, T, out_channels]
+ )
+ # Scale-shift table for adaptive output normalization (2 values: shift, scale)
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.Tensor,
+ timestep_r: torch.Tensor,
+ attention_mask: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_attention_mask: torch.Tensor,
+ context_latents: torch.Tensor,
+ use_cache: Optional[bool] = None,
+ past_key_values: Optional[EncoderDecoderCache] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = False,
+ return_hidden_states: int = None,
+ custom_layers_config: Optional[dict] = None,
+ enable_early_exit: bool = False,
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
+ ):
+
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ # Disable cache during training or when gradient checkpointing is enabled
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ use_cache = False
+ if self.training:
+ use_cache = False
+
+ # Initialize cache if needed (only during inference for auto-regressive generation)
+ if not self.training and use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
+
+ # Compute timestep embeddings for diffusion conditioning
+ # Two embeddings: one for timestep t, one for timestep difference (t - r)
+ temb_t, timestep_proj_t = self.time_embed(timestep)
+ temb_r, timestep_proj_r = self.time_embed_r(timestep - timestep_r)
+ # Combine embeddings
+ temb = temb_t + temb_r
+ timestep_proj = timestep_proj_t + timestep_proj_r
+
+ # Concatenate context latents (source latents + chunk masks) with hidden states
+ hidden_states = torch.cat([context_latents, hidden_states], dim=-1)
+ # Record original sequence length for later restoration after padding
+ original_seq_len = hidden_states.shape[1]
+ # Apply padding if sequence length is not divisible by patch_size
+ # This ensures proper patch extraction
+ pad_length = 0
+ if hidden_states.shape[1] % self.patch_size != 0:
+ pad_length = self.patch_size - (hidden_states.shape[1] % self.patch_size)
+ hidden_states = F.pad(hidden_states, (0, 0, 0, pad_length), mode='constant', value=0)
+
+ # Project input to patches and project encoder states
+ hidden_states = self.proj_in(hidden_states)
+ encoder_hidden_states = self.condition_embedder(encoder_hidden_states)
+
+ # Cache positions
+ if cache_position is None:
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
+ cache_position = torch.arange(
+ past_seen_tokens, past_seen_tokens + hidden_states.shape[1], device=hidden_states.device
+ )
+
+ # Position IDs
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+
+ seq_len = hidden_states.shape[1]
+ encoder_seq_len = encoder_hidden_states.shape[1]
+ dtype = hidden_states.dtype
+ device = hidden_states.device
+
+ # ?????? Flash Attention 2
+ is_flash_attn = (self.config._attn_implementation == "flash_attention_2")
+
+ # ??? Mask ??
+ full_attn_mask = None
+ sliding_attn_mask = None
+ encoder_attention_mask = None
+ attention_mask = None
+ if is_flash_attn:
+ # -------------------------------------------------------
+ # ?? A: Flash Attention ??
+ # -------------------------------------------------------
+ # FA ??? 4D Mask?
+ # ??? padding mask (attention_mask [B, L])?????????
+ # ???? padding mask?? None?
+ # ??????? Layer ???? FA kernel ? sliding_window ?????
+ full_attn_mask = attention_mask
+
+ # ???????????????????FA ????????????? padding mask
+ # Layer ?????????? sliding window ? kernel
+ sliding_attn_mask = attention_mask if self.config.use_sliding_window else None
+
+ else:
+ # -------------------------------------------------------
+ # ?? B: CPU / Mac / SDPA (Eager ??)
+ # -------------------------------------------------------
+ # ?????? 4D Mask [B, 1, L, L]
+
+ # 1. Full Attention (Bidirectional, Global)
+ # ????? create_causal_mask + bidirectional
+ full_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+ max_len = max(seq_len, encoder_seq_len)
+
+ encoder_attention_mask = create_4d_mask(
+ seq_len=max_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=None,
+ is_sliding_window=False,
+ is_causal=False # <--- ????????
+ )
+ encoder_attention_mask = encoder_attention_mask[:, :, :seq_len, :encoder_seq_len]
+ # 2. Sliding Attention (Bidirectional, Local)
+ # ????? create_sliding_window... + bidirectional
+ if self.config.use_sliding_window:
+ sliding_attn_mask = create_4d_mask(
+ seq_len=seq_len,
+ dtype=dtype,
+ device=device,
+ attention_mask=attention_mask, # [B, L]
+ sliding_window=self.config.sliding_window,
+ is_sliding_window=True, # <--- ??????
+ is_causal=False # <--- ????????
+ )
+
+ # ?? Mapping
+ self_attn_mask_mapping = {
+ "full_attention": full_attn_mask,
+ "sliding_attention": sliding_attn_mask,
+ "encoder_attention_mask": encoder_attention_mask,
+ }
+
+ # Create position embeddings to be shared across all decoder layers
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+ all_cross_attentions = () if output_attentions else None
+
+ # Handle early exit for custom layer configurations
+ max_needed_layer = float('inf')
+ if custom_layers_config is not None and enable_early_exit:
+ max_needed_layer = max(custom_layers_config.keys())
+ # Force output_attentions to True when early exit is enabled for attention extraction
+ output_attentions = True
+ if all_cross_attentions is None:
+ all_cross_attentions = ()
+
+ # Process through transformer layers
+ for index_block, layer_module in enumerate(self.layers):
+
+ layer_outputs = layer_module(
+ hidden_states,
+ position_embeddings,
+ timestep_proj,
+ self_attn_mask_mapping[layer_module.attention_type],
+ position_ids,
+ past_key_values,
+ output_attentions,
+ use_cache,
+ cache_position,
+ encoder_hidden_states,
+ self_attn_mask_mapping["encoder_attention_mask"],
+ **flash_attn_kwargs,
+ )
+ hidden_states = layer_outputs[0]
+
+ if output_attentions and self.layers[index_block].use_cross_attention:
+ # layer_outputs structure: (hidden_states, self_attn_weights, cross_attn_weights)
+ # Extract the last element which is cross_attn_weights
+ if len(layer_outputs) >= 3:
+ all_cross_attentions += (layer_outputs[2],)
+
+ if return_hidden_states:
+ return hidden_states
+
+ # Extract scale-shift parameters for adaptive output normalization
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ # Apply adaptive layer norm: norm(x) * (1 + scale) + shift
+ hidden_states = (self.norm_out(hidden_states) * (1 + scale) + shift).type_as(hidden_states)
+ # Project output: de-patchify back to original sequence format
+ hidden_states = self.proj_out(hidden_states)
+
+ # Crop back to original sequence length to ensure exact length match (remove padding)
+ hidden_states = hidden_states[:, :original_seq_len, :]
+
+ outputs = (hidden_states, past_key_values)
+
+ if output_attentions:
+ outputs += (all_cross_attentions,)
+ return outputs
+
+class AceStepConditionEncoder(AceStepPreTrainedModel):
+ """
+ Condition encoder for AceStep model.
+
+ Encodes multiple conditioning inputs (text, lyrics, timbre) and packs them
+ into a single sequence for cross-attention in the diffusion model. Handles
+ projection, encoding, and sequence packing.
+ """
+ def __init__(self, config: AceStepConfig):
+ super().__init__(config)
+ self.config = config
+ # Project text embeddings to model hidden size
+ self.text_projector = nn.Linear(config.text_hidden_dim, config.hidden_size, bias=False)
+ # Encoder for lyric text
+ self.lyric_encoder = AceStepLyricEncoder(config)
+ # Encoder for timbre from reference audio
+ self.timbre_encoder = AceStepTimbreEncoder(config)
+
+ def forward(
+ self,
+ # Text inputs
+ text_hidden_states: Optional[torch.FloatTensor] = None,
+ text_attention_mask: Optional[torch.Tensor] = None,
+ # Lyric inputs
+ lyric_hidden_states: Optional[torch.LongTensor] = None,
+ lyric_attention_mask: Optional[torch.Tensor] = None,
+ # Reference audio for timbre
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.Tensor] = None,
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
+ ):
+ # Project and encode text
+ text_hidden_states = self.text_projector(text_hidden_states)
+ # Encode lyrics
+ lyric_encoder_outputs = self.lyric_encoder(
+ inputs_embeds=lyric_hidden_states,
+ attention_mask=lyric_attention_mask,
+ )
+ lyric_hidden_states = lyric_encoder_outputs.last_hidden_state
+ # Encode timbre from reference audio
+ timbre_embs_unpack, timbre_embs_mask = self.timbre_encoder(refer_audio_acoustic_hidden_states_packed, refer_audio_order_mask)
+
+ # Pack sequences: combine lyrics and timbre, then add text
+ # This creates a single sequence with all conditioning information
+ encoder_hidden_states, encoder_attention_mask = pack_sequences(lyric_hidden_states, timbre_embs_unpack, lyric_attention_mask, timbre_embs_mask)
+ encoder_hidden_states, encoder_attention_mask = pack_sequences(encoder_hidden_states, text_hidden_states, encoder_attention_mask, text_attention_mask)
+ return encoder_hidden_states, encoder_attention_mask
+
+
+class AceStepConditionGenerationModel(AceStepPreTrainedModel):
+ """
+ Main conditional generation model for AceStep.
+
+ End-to-end model for generating audio conditioned on text, lyrics, and timbre.
+ Combines encoder (for conditioning), decoder (diffusion model), tokenizer
+ (for discrete tokenization), and detokenizer (for reconstruction).
+ Supports flow matching training and inference with various sampling methods.
+ """
+ def __init__(self, config: AceStepConfig):
+ super().__init__(config)
+ self.config = config
+ # Diffusion model components
+ self.decoder = AceStepDiTModel(config) # Main diffusion transformer
+ self.encoder = AceStepConditionEncoder(config) # Condition encoder
+ self.tokenizer = AceStepAudioTokenizer(config) # Audio tokenizer
+ self.detokenizer = AudioTokenDetokenizer(config) # Audio detokenizer
+ # Null condition embedding for classifier-free guidance
+ self.null_condition_emb = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def tokenize(self, x, silence_latent, attention_mask):
+ if x.shape[1] % self.config.pool_window_size != 0:
+ pad_len = self.config.pool_window_size - (x.shape[1] % self.config.pool_window_size)
+ x = torch.cat([x, silence_latent[:1,:pad_len].repeat(x.shape[0],1,1)], dim=1)
+ attention_mask = F.pad(attention_mask, (0, pad_len), mode='constant', value=0)
+ x = rearrange(x, 'n (t_patch p) d -> n t_patch p d', p=self.config.pool_window_size)
+ seq_len = x.shape[1]
+ chunk = math.ceil(attention_mask.shape[1] / seq_len)
+ attention_mask = attention_mask.to(x.dtype)
+ attention_mask = F.max_pool1d(attention_mask.unsqueeze(1), kernel_size=chunk, stride=chunk, ceil_mode=True).squeeze(1)
+ quantized, indices = self.tokenizer(x)
+ return quantized, indices, attention_mask
+
+ def detokenize(self, quantized):
+ """
+ Detokenize quantized audio tokens back to continuous representations.
+
+ Args:
+ quantized: Quantized tokens of shape [N, T//pool_window_size, d]
+
+ Returns:
+ Detokenized hidden states of shape [N, T, d]
+ """
+ hidden_states = self.detokenizer(quantized)
+ return hidden_states
+
+ @torch.no_grad()
+ def prepare_condition(
+ self,
+ text_hidden_states: torch.FloatTensor,
+ text_attention_mask: torch.Tensor,
+ lyric_hidden_states: torch.FloatTensor,
+ lyric_attention_mask: torch.Tensor,
+ refer_audio_acoustic_hidden_states_packed: torch.FloatTensor,
+ refer_audio_order_mask: torch.Tensor,
+ hidden_states: torch.FloatTensor,
+ attention_mask: torch.Tensor,
+ silence_latent: torch.FloatTensor,
+ src_latents: torch.FloatTensor,
+ chunk_masks: torch.Tensor,
+ is_covers: torch.Tensor,
+ precomputed_lm_hints_25Hz: Optional[torch.FloatTensor] = None,
+ audio_codes: torch.FloatTensor = None,
+ ):
+
+ dtype = hidden_states.dtype
+ encoder_hidden_states, encoder_attention_mask = self.encoder(
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ )
+
+ # N x T x d -> N x T//pool_window_size x pool_window_size x d
+ # tokenize and detokenize to get LM hints for cover songs (when is_covers=True)
+ # Use precomputed hints if provided (e.g., from audio codes), otherwise tokenize hidden_states
+ if precomputed_lm_hints_25Hz is not None:
+ print("Using precomputed LM hints")
+ lm_hints_25Hz = precomputed_lm_hints_25Hz[:, :src_latents.shape[1], :]
+ else:
+ if audio_codes is not None:
+ lm_hints_5Hz = self.tokenizer.quantizer.get_output_from_indices(audio_codes)
+ else:
+ lm_hints_5Hz, indices, llm_mask = self.tokenize(hidden_states, silence_latent, attention_mask)
+ lm_hints_25Hz = self.detokenize(lm_hints_5Hz)
+ # Crop lm_hints_25Hz to match src_latents length (tokenize may have added padding)
+ lm_hints_25Hz = lm_hints_25Hz[:, :src_latents.shape[1], :]
+ src_latents = torch.where(is_covers.unsqueeze(-1).unsqueeze(-1) > 0, lm_hints_25Hz, src_latents)
+ # Concatenate source latents with chunk masks as context
+ context_latents = torch.cat([src_latents, chunk_masks.to(dtype)], dim=-1)
+ return encoder_hidden_states, encoder_attention_mask, context_latents
+
+ def forward(
+ self,
+ # Diffusion inputs
+ hidden_states: torch.FloatTensor,
+ attention_mask: torch.Tensor,
+ # Encoder inputs
+ # Text
+ text_hidden_states: Optional[torch.FloatTensor] = None,
+ text_attention_mask: Optional[torch.Tensor] = None,
+ # Lyric
+ lyric_hidden_states: Optional[torch.LongTensor] = None,
+ lyric_attention_mask: Optional[torch.Tensor] = None,
+ # Reference audio for timbre
+ refer_audio_acoustic_hidden_states_packed: Optional[torch.Tensor] = None,
+ refer_audio_order_mask: Optional[torch.LongTensor] = None,
+ src_latents: torch.FloatTensor = None,
+ chunk_masks: torch.FloatTensor = None,
+ is_covers: torch.Tensor = None,
+ silence_latent: torch.FloatTensor = None,
+ cfg_ratio: float = 0.15,
+ ):
+ """
+ Forward pass for training (computes training losses).
+ """
+ # Prepare conditioning inputs (encoder states, context latents)
+ encoder_hidden_states, encoder_attention_mask, context_latents = self.prepare_condition(
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ hidden_states=src_latents,
+ attention_mask=attention_mask,
+ silence_latent=silence_latent,
+ src_latents=src_latents,
+ chunk_masks=chunk_masks,
+ is_covers=is_covers,
+ )
+ bsz, device, dtype = hidden_states.shape[0], hidden_states.device, hidden_states.dtype
+ # Classifier-free guidance: randomly drop conditions with probability cfg_ratio
+ # This helps the model learn to work with and without conditions
+ full_cfg_condition_mask = torch.where(
+ (torch.rand(size=(bsz,), device=device, dtype=dtype) < cfg_ratio),
+ torch.zeros(size=(bsz,), device=device, dtype=dtype),
+ torch.ones(size=(bsz,), device=device, dtype=dtype)
+ ).view(-1, 1, 1)
+ # Replace dropped conditions with null condition embedding
+ encoder_hidden_states = torch.where(full_cfg_condition_mask > 0, encoder_hidden_states, self.null_condition_emb.expand_as(encoder_hidden_states))
+
+ # Flow matching setup: sample noise x1 and interpolate with data x0
+ x1 = torch.randn_like(hidden_states) # Noise
+ x0 = hidden_states # Data
+ # Sample timesteps t and r for flow matching
+ t, r = sample_t_r(bsz, device, dtype, self.config.data_proportion, self.config.timestep_mu, self.config.timestep_sigma, use_meanflow=False)
+ t_ = t.unsqueeze(-1).unsqueeze(-1)
+ # Interpolate: x_t = t * x1 + (1 - t) * x0
+ xt = t_ * x1 + (1.0 - t_) * x0
+
+ # Predict flow (velocity) from diffusion model
+ decoder_outputs = self.decoder(
+ hidden_states=xt,
+ timestep=t,
+ timestep_r=t,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ context_latents=context_latents,
+ )
+ # Flow matching loss: predict the flow field v = x1 - x0
+ flow = x1 - x0
+ diffusion_loss = F.mse_loss(decoder_outputs[0], flow)
+ return {
+ "diffusion_loss": diffusion_loss,
+ }
+
+ def training_losses(self, **kwargs):
+ return self.forward(**kwargs)
+
+ def prepare_noise(self, context_latents: torch.FloatTensor, seed: Union[int, List[int], None] = None):
+ """
+ Prepare noise tensor for generation with optional seeding.
+
+ Args:
+ context_latents: Context latents to determine noise shape
+ seed: Can be int, List[int], or None. If None, uses random noise.
+
+ Returns:
+ Noise tensor of appropriate shape
+ """
+ bsz = context_latents.shape[0]
+ device = context_latents.device
+ dtype = context_latents.dtype
+ # Handle seed: can be int, List[int], or None
+ src_latents_shape = (context_latents.shape[0], context_latents.shape[1], context_latents.shape[-1] // 2)
+ if seed is None:
+ # No seed provided - use random
+ noise = torch.randn(src_latents_shape, device=device, dtype=dtype)
+ elif isinstance(seed, list):
+ # List of seeds - generate noise for each sample separately
+ noise_list = []
+ for i, s in enumerate(seed):
+ if s is None or s < 0:
+ # Random seed for this sample
+ noise_i = torch.randn(1, src_latents_shape[1], src_latents_shape[2], device=device, dtype=dtype)
+ else:
+ # Use specific seed for this sample
+ generator = torch.Generator(device=device).manual_seed(int(s))
+ noise_i = torch.randn(1, src_latents_shape[1], src_latents_shape[2], generator=generator, device=device, dtype=dtype)
+ noise_list.append(noise_i)
+ noise = torch.cat(noise_list, dim=0)
+ else:
+ # Single seed for all samples
+ generator = torch.Generator(device=device).manual_seed(int(seed))
+ noise = torch.randn(src_latents_shape, generator=generator, device=device, dtype=dtype)
+
+ return noise
+
+ def get_x0_from_noise(self, zt, vt, t):
+ return zt - vt * t.unsqueeze(-1).unsqueeze(-1)
+
+ def renoise(self, x, t, noise=None):
+ if noise is None:
+ noise = torch.randn_like(x)
+ if isinstance(t, torch.Tensor) and t.ndim != x.ndim:
+ t = t.unsqueeze(-1).unsqueeze(-1)
+ xt = t * noise + (1 - t) * x
+ return xt
+
+ def generate_audio(
+ self,
+ text_hidden_states: torch.FloatTensor,
+ text_attention_mask: torch.FloatTensor,
+ lyric_hidden_states: torch.FloatTensor,
+ lyric_attention_mask: torch.FloatTensor,
+ refer_audio_acoustic_hidden_states_packed: torch.FloatTensor,
+ refer_audio_order_mask: torch.LongTensor,
+ src_latents: torch.FloatTensor,
+ chunk_masks: torch.FloatTensor,
+ is_covers: torch.Tensor,
+ silence_latent: Optional[torch.FloatTensor] = None,
+ attention_mask: torch.Tensor = None,
+ seed: int = None,
+ fix_nfe: int = 8,
+ infer_method: str = "ode",
+ use_cache: bool = True,
+ audio_cover_strength: float = 1.0,
+ non_cover_text_hidden_states: Optional[torch.FloatTensor] = None,
+ non_cover_text_attention_mask: Optional[torch.FloatTensor] = None,
+ precomputed_lm_hints_25Hz: Optional[torch.FloatTensor] = None,
+ audio_codes: Optional[torch.FloatTensor] = None,
+ shift: float = 3.0,
+ timesteps: Optional[torch.Tensor] = None,
+ **kwargs,
+ ):
+ # Valid shifts: only discrete values 1, 2, 3 are supported
+ VALID_SHIFTS = [1.0, 2.0, 3.0]
+
+ # Valid timesteps: all unique timesteps from shift=1,2,3 with fix_nfe=8 (total 20 values)
+ VALID_TIMESTEPS = [
+ 1.0, 0.9545454545454546, 0.9333333333333333, 0.9, 0.875,
+ 0.8571428571428571, 0.8333333333333334, 0.7692307692307693, 0.75,
+ 0.6666666666666666, 0.6428571428571429, 0.625, 0.5454545454545454,
+ 0.5, 0.4, 0.375, 0.3, 0.25, 0.2222222222222222, 0.125
+ ]
+
+ # Pre-defined timestep schedules for each valid shift (fix_nfe=8, excluding final 0)
+ SHIFT_TIMESTEPS = {
+ 1.0: [1.0, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125],
+ 2.0: [1.0, 0.9333333333333333, 0.8571428571428571, 0.7692307692307693, 0.6666666666666666, 0.5454545454545454, 0.4, 0.2222222222222222],
+ 3.0: [1.0, 0.9545454545454546, 0.9, 0.8333333333333334, 0.75, 0.6428571428571429, 0.5, 0.3],
+ }
+
+ # Determine the timestep schedule to use
+ t_schedule_list = None
+
+ if timesteps is not None:
+ # Process custom timesteps: map each value to nearest valid timestep
+ timesteps_list = timesteps.tolist() if isinstance(timesteps, torch.Tensor) else list(timesteps)
+
+ # Remove trailing zeros
+ while len(timesteps_list) > 0 and timesteps_list[-1] == 0:
+ timesteps_list.pop()
+
+ # Validate length: 1-20
+ if len(timesteps_list) < 1:
+ logger.warning(f"timesteps length is too short after removing trailing zeros, using default shift={shift}")
+ elif len(timesteps_list) > 20:
+ logger.warning(f"timesteps length={len(timesteps_list)} exceeds maximum 20, truncating to 20")
+ timesteps_list = timesteps_list[:20]
+ t_schedule_list = timesteps_list
+ else:
+ t_schedule_list = timesteps_list
+
+ if t_schedule_list is not None:
+ # Map each timestep to nearest valid timestep
+ original_timesteps = t_schedule_list.copy()
+ mapped_timesteps = []
+ for t in t_schedule_list:
+ nearest = min(VALID_TIMESTEPS, key=lambda x: abs(x - t))
+ mapped_timesteps.append(nearest)
+
+ if original_timesteps != mapped_timesteps:
+ logger.warning(f"timesteps mapped to nearest valid values: {original_timesteps} -> {mapped_timesteps}")
+
+ t_schedule_list = mapped_timesteps
+
+ if t_schedule_list is None:
+ # Use shift-based schedule: round to nearest valid shift
+ original_shift = shift
+ shift = min(VALID_SHIFTS, key=lambda x: abs(x - shift))
+ if original_shift != shift:
+ logger.warning(f"shift={original_shift} not supported, rounded to nearest valid shift={shift}")
+ t_schedule_list = SHIFT_TIMESTEPS[shift]
+
+ if attention_mask is None:
+ latent_length = src_latents.shape[1]
+ attention_mask = torch.ones(src_latents.shape[0], latent_length, device=src_latents.device, dtype=src_latents.dtype)
+
+ time_costs = {}
+ start_time = time.time()
+ total_start_time = start_time
+ encoder_hidden_states, encoder_attention_mask, context_latents = self.prepare_condition(
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ hidden_states=src_latents,
+ attention_mask=attention_mask,
+ silence_latent=silence_latent,
+ src_latents=src_latents,
+ chunk_masks=chunk_masks,
+ is_covers=is_covers,
+ precomputed_lm_hints_25Hz=precomputed_lm_hints_25Hz,
+ audio_codes=audio_codes,
+ )
+
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = None, None, None
+ if audio_cover_strength < 1.0:
+ non_is_covers = torch.zeros_like(is_covers, device=is_covers.device, dtype=is_covers.dtype)
+ # Use silence_latent for non-cover condition to simulate text2music mode (no reference audio)
+ silence_latent_expanded = silence_latent[:, :src_latents.shape[1], :].expand(src_latents.shape[0], -1, -1)
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = self.prepare_condition(
+ text_hidden_states=non_cover_text_hidden_states,
+ text_attention_mask=non_cover_text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ hidden_states=silence_latent_expanded,
+ attention_mask=attention_mask,
+ silence_latent=silence_latent,
+ src_latents=silence_latent_expanded,
+ chunk_masks=chunk_masks,
+ is_covers=non_is_covers,
+ precomputed_lm_hints_25Hz=None,
+ audio_codes=None,
+ )
+
+ end_time = time.time()
+ time_costs["encoder_time_cost"] = end_time - start_time
+ start_time = end_time
+
+ noise = self.prepare_noise(context_latents, seed)
+ bsz, device, dtype = context_latents.shape[0], context_latents.device, context_latents.dtype
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
+
+ # Use pre-computed t_schedule_list (already validated and mapped to valid timesteps)
+ t_schedule = torch.tensor(t_schedule_list, device=device, dtype=dtype)
+ num_steps = len(t_schedule)
+
+ # Recalculate cover_steps based on actual num_steps
+ cover_steps = int(num_steps * audio_cover_strength)
+
+ xt = noise
+ for step_idx in range(num_steps):
+ current_timestep = t_schedule[step_idx].item()
+ t_curr_tensor = current_timestep * torch.ones((bsz,), device=device, dtype=dtype)
+
+ if step_idx >= cover_steps:
+ encoder_hidden_states = encoder_hidden_states_non_cover
+ encoder_attention_mask = encoder_attention_mask_non_cover
+ context_latents = context_latents_non_cover
+ past_key_values = EncoderDecoderCache(DynamicCache(), DynamicCache())
+
+ with torch.no_grad():
+ decoder_outputs = self.decoder(
+ hidden_states=xt,
+ timestep=t_curr_tensor,
+ timestep_r=t_curr_tensor,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ context_latents=context_latents,
+ use_cache=True,
+ past_key_values=past_key_values,
+ )
+
+ vt = decoder_outputs[0]
+ past_key_values = decoder_outputs[1]
+
+ # On final step, directly compute x0 from noise
+ if step_idx == num_steps - 1:
+ xt = self.get_x0_from_noise(xt, vt, t_curr_tensor)
+ break
+
+ # Update x_t based on inference method
+ if infer_method == "sde":
+ # Stochastic Differential Equation: predict clean, then re-add noise
+ pred_clean = self.get_x0_from_noise(xt, vt, t_curr_tensor)
+ next_timestep = t_schedule[step_idx + 1].item()
+ xt = self.renoise(pred_clean, next_timestep)
+ elif infer_method == "ode":
+ # Ordinary Differential Equation: Euler method
+ # dx/dt = -v, so x_{t+1} = x_t - v_t * dt
+ next_timestep = t_schedule[step_idx + 1].item()
+ dt = current_timestep - next_timestep
+ dt_tensor = dt * torch.ones((bsz,), device=device, dtype=dtype).unsqueeze(-1).unsqueeze(-1)
+ xt = xt - vt * dt_tensor
+
+ x_gen = xt
+ end_time = time.time()
+ time_costs["diffusion_time_cost"] = end_time - start_time
+ time_costs["diffusion_per_step_time_cost"] = time_costs["diffusion_time_cost"] / num_steps
+ time_costs["total_time_cost"] = end_time - total_start_time
+ return {
+ "target_latents": x_gen,
+ "time_costs": time_costs,
+ }
+
+
+def test_forward(model, seed=42):
+ # Fix random seed for reproducibility
+ import random
+ import numpy as np
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ if torch.cuda.is_available():
+ torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+
+ # Get model dtype and device
+ model_dtype = next(model.parameters()).dtype
+ device = next(model.parameters()).device
+
+ print(f"Testing with dtype: {model_dtype}, device: {device}, seed: {seed}")
+
+ # Test data preparation with matching dtype
+ text_hidden_states = torch.randn(2, 77, 1024, dtype=model_dtype, device=device)
+ text_attention_mask = torch.ones(2, 77, dtype=model_dtype, device=device)
+ lyric_hidden_states = torch.randn(2, 123, 1024, dtype=model_dtype, device=device)
+ lyric_attention_mask = torch.ones(2, 123, dtype=model_dtype, device=device)
+ refer_audio_acoustic_hidden_states_packed = torch.randn(3, 750, 64, dtype=model_dtype, device=device)
+ refer_audio_order_mask = torch.LongTensor([0, 0, 1]).to(device)
+
+ # Base config: 25 Hz hidden states ? 10 s = 250 frames (round to int)
+ base_seconds = 10
+ frames_per_second = 25
+ base_seq_len = base_seconds * frames_per_second
+
+ hidden_states = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device)
+ attention_mask = torch.ones(2, base_seq_len, dtype=model_dtype, device=device)
+ # Add some padding to test mask behavior
+ pad_start = max(base_seq_len // 2, 1)
+ attention_mask[0, pad_start:] = 0
+ chunk_mask = torch.ones(2, base_seq_len, 64, dtype=model_dtype, device=device)
+ chunk_mask[0, pad_start:] = 0
+
+ silence_latent = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device)
+ # New required parameters for updated training logic
+ src_latents = torch.randn(2, base_seq_len, 64, dtype=model_dtype, device=device) # Source latents for context
+ is_covers = torch.tensor([0, 1], dtype=torch.long, device=device) # Cover song indicators (0=original, 1=cover)
+
+ # Test 1: Flow matching training (using 10s sequence for sanity check by default)
+ print(f"Testing flow matching training with {base_seconds}s sequence ({base_seq_len} frames @ {frames_per_second}Hz)...")
+ outputs = model.training_losses(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ chunk_masks=chunk_mask,
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ silence_latent=silence_latent,
+ src_latents=src_latents,
+ is_covers=is_covers,
+ cfg_ratio=0.15,
+ )
+ loss = outputs['diffusion_loss']
+ print(f"Flow matching loss: {loss.item():.6f}")
+ print(f" Loss stats - min: {loss.min().item():.6f}, max: {loss.max().item():.6f}, mean: {loss.mean().item():.6f}, std: {loss.std().item() if loss.numel() > 1 else 0:.6f}")
+
+ # Test 2: Generation with flow matching, testing throughput for different sequence lengths
+ lengths_seconds = [10, 30, 60, 120, 180, 240]
+ infer_steps = 2 # Can be increased as needed (e.g., 50/100) to better approximate real inference
+
+ print("\n===== Throughput benchmark (25Hz hidden states) =====")
+ for seconds in lengths_seconds:
+ seq_len = seconds * frames_per_second
+
+ # Reconstruct inputs for current sequence length
+ cur_hidden_states = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
+ cur_attention_mask = torch.ones(2, seq_len, dtype=model_dtype, device=device)
+ cur_chunk_mask = torch.ones(2, seq_len, 64, dtype=model_dtype, device=device)
+ cur_silence_latent = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
+ cur_src_latents = torch.randn(2, seq_len, 64, dtype=model_dtype, device=device)
+
+ print(f"\n--- {seconds}s input ({seq_len} frames @ {frames_per_second}Hz) ---")
+ outputs = model.generate_audio(
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_acoustic_hidden_states_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ src_latents=cur_src_latents,
+ chunk_masks=cur_chunk_mask,
+ silence_latent=cur_silence_latent,
+ infer_steps=infer_steps,
+ is_covers=is_covers,
+ seed=1234,
+ )
+
+ target_latents = outputs["target_latents"]
+ time_costs = outputs.get("time_costs", {})
+
+ total_time = time_costs.get("total_time_cost", None)
+ diffusion_time = time_costs.get("diffusion_time_cost", None)
+
+ # Output shape and statistics
+ print(f"Generated latents shape: {target_latents.shape}")
+ print(
+ f"Stats - min: {target_latents.min().item():.4f}, "
+ f"max: {target_latents.max().item():.4f}, "
+ f"mean: {target_latents.mean().item():.4f}, "
+ f"std: {target_latents.std().item():.4f}"
+ )
+
+ # Calculate throughput: statistics by frame count and audio seconds
+ bsz, t_len = target_latents.shape[0], target_latents.shape[1]
+ audio_seconds = t_len / frames_per_second
+
+ if total_time is not None:
+ frames_throughput = (bsz * t_len) / total_time
+ seconds_throughput = (bsz * audio_seconds) / total_time
+ print(
+ f"Time costs: total={total_time:.4f}s, diffusion={diffusion_time:.4f}s "
+ f"({infer_steps} steps)"
+ if diffusion_time is not None
+ else f"Time costs: total={total_time:.4f}s"
+ )
+ print(
+ f"Throughput (based on total_time): "
+ f"{frames_throughput:.2f} frames/s, "
+ f"{seconds_throughput:.2f} audio-seconds/s (batch={bsz})"
+ )
+ else:
+ print("Time costs not available in outputs['time_costs']; only basic stats printed.")
+
+
+if __name__ == "__main__":
+ from torch.profiler import profile, record_function, ProfilerActivity
+ import os, torch
+ import time
+ from transformers import AutoModel
+ config = AceStepConfig()
+ start = time.time()
+ import os
+ model_dir = os.path.dirname(os.path.abspath(__file__))
+ model = AceStepConditionGenerationModel.from_pretrained(model_dir)
+ end = time.time()
+ # model.config._attn_implementation = "sdpa"
+ model.config._attn_implementation = "flash_attention_2"
+ model.eval()
+ # model = model.to("cpu")
+ # model = model.float()
+ model = model.to("cuda")
+ model = model.bfloat16()
+ test_forward(model)
diff --git a/models/TTS/ace_step15/pipeline_ace_step15.py b/models/TTS/ace_step15/pipeline_ace_step15.py
new file mode 100644
index 0000000..a563b7c
--- /dev/null
+++ b/models/TTS/ace_step15/pipeline_ace_step15.py
@@ -0,0 +1,1334 @@
+"""
+ACE-Step 1.5 pipeline for WanGP.
+"""
+
+import copy
+import math
+import os
+import random
+import re
+
+import torch
+import torchaudio
+import yaml
+from tqdm import tqdm
+from transformers import AutoTokenizer, Qwen3ForCausalLM, Qwen3Model
+from diffusers import AutoencoderOobleck
+
+from mmgp import offload
+
+from .models.ace_step15_hf import AceStepConditionGenerationModel
+
+_DEFAULT_TIMBRE = [
+ -1.3672e-01, -1.5820e-01, 5.8594e-01, -5.7422e-01, 3.0273e-02,
+ 2.7930e-01, -2.5940e-03, -2.0703e-01, -1.6113e-01, -1.4746e-01,
+ -2.7710e-02, -1.8066e-01, -2.9688e-01, 1.6016e+00, -2.6719e+00,
+ 7.7734e-01, -1.3516e+00, -1.9434e-01, -7.1289e-02, -5.0938e+00,
+ 2.4316e-01, 4.7266e-01, 4.6387e-02, -6.6406e-01, -2.1973e-01,
+ -6.7578e-01, -1.5723e-01, 9.5312e-01, -2.0020e-01, -1.7109e+00,
+ 5.8984e-01, -5.7422e-01, 5.1562e-01, 2.8320e-01, 1.4551e-01,
+ -1.8750e-01, -5.9814e-02, 3.6719e-01, -1.0059e-01, -1.5723e-01,
+ 2.0605e-01, -4.3359e-01, -8.2812e-01, 4.5654e-02, -6.6016e-01,
+ 1.4844e-01, 9.4727e-02, 3.8477e-01, -1.2578e+00, -3.3203e-01,
+ -8.5547e-01, 4.3359e-01, 4.2383e-01, -8.9453e-01, -5.0391e-01,
+ -5.6152e-02, -2.9219e+00, -2.4658e-02, 5.0391e-01, 9.8438e-01,
+ 7.2754e-02, -2.1582e-01, 6.3672e-01, 1.0000e+00,
+]
+
+_AUDIO_CODE_RE = re.compile(r"<\|audio_code_(\d+)\|>")
+_AUDIO_CODE_TOKEN_RE = re.compile(r"^<\|audio_code_(\d+)\|>$")
+_DEFAULT_DIT_INSTRUCTION = "Fill the audio semantic mask based on the given conditions:"
+_DEFAULT_LM_INSTRUCTION = "Generate audio semantic tokens based on the given conditions:"
+_SFT_GEN_PROMPT = """# Instruction
+{}
+
+# Caption
+{}
+
+# Metas
+{}<|endoftext|>
+"""
+
+
+def _ace_step15_get_vae_tile_size(vae_config, device_mem_capacity, mixed_precision):
+ if vae_config == 0:
+ if mixed_precision:
+ device_mem_capacity = device_mem_capacity / 2
+ if device_mem_capacity >= 24000:
+ use_vae_config = 1
+ elif device_mem_capacity >= 12000:
+ use_vae_config = 2
+ else:
+ use_vae_config = 3
+ else:
+ use_vae_config = vae_config
+
+ if use_vae_config == 1:
+ return 0
+ if use_vae_config == 2:
+ return 256
+ return 128
+
+
+class ACEStep15Pipeline:
+ def __init__(
+ self,
+ transformer_weights_path: str,
+ transformer_config_path: str,
+ vae_weights_path: str,
+ vae_config_path: str,
+ text_encoder_2_weights_path: str,
+ text_encoder_2_tokenizer_dir: str,
+ lm_weights_path: str,
+ lm_tokenizer_dir: str,
+ silence_latent_path: str | None = None,
+ enable_lm: bool = True,
+ device=None,
+ dtype=torch.bfloat16,
+ ):
+ if device is None:
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ self.device = device
+
+ if isinstance(dtype, str):
+ dtype = getattr(torch, dtype, torch.bfloat16)
+ self.dtype = dtype
+
+ if not text_encoder_2_weights_path:
+ raise ValueError("Ace Step 1.5 requires a pre-text encoder weights path.")
+
+ self.enable_lm = bool(enable_lm)
+ if self.enable_lm and not lm_weights_path:
+ raise ValueError("Ace Step 1.5 requires a 5Hz LM weights path.")
+
+ self.text_encoder_2_weights_path = text_encoder_2_weights_path
+ self.text_encoder_2_tokenizer_dir = text_encoder_2_tokenizer_dir
+ self.lm_weights_path = lm_weights_path
+ self.lm_tokenizer_dir = lm_tokenizer_dir
+ self.silence_latent_path = silence_latent_path
+
+ self._interrupt = False
+ self._early_stop = False
+ self.loaded = False
+
+ self._latent_hop_length = 1920
+
+ self._load_models(transformer_weights_path, transformer_config_path, vae_weights_path, vae_config_path)
+ self._init_lm_hint_modules()
+ self._load_tokenizers()
+ self._load_text_encoder_2()
+ if self.enable_lm:
+ self._load_lm()
+ else:
+ self.lm_model = None
+ self._load_silence_latent()
+
+ self.loaded = True
+
+ def _load_models(self, transformer_weights_path, transformer_config_path, vae_weights_path, vae_config_path):
+ self.ace_step_transformer = offload.fast_load_transformers_model(
+ transformer_weights_path,
+ modelClass=AceStepConditionGenerationModel,
+ defaultConfigPath=transformer_config_path,
+ default_dtype=self.dtype,
+ ignore_unused_weights=True,
+ )
+ self.ace_step_transformer.eval()
+ self.model = self.ace_step_transformer
+
+ self._patch_oobleck_weight_norm()
+ self.audio_vae = offload.fast_load_transformers_model(
+ vae_weights_path,
+ modelClass=AutoencoderOobleck,
+ defaultConfigPath=vae_config_path,
+ default_dtype=self.dtype,
+ ignore_unused_weights=True,
+ )
+ self.audio_vae.eval()
+ self.audio_vae._offload_hooks = ["encode", "decode"]
+ self.audio_vae.get_VAE_tile_size = _ace_step15_get_vae_tile_size
+ self.vae = self.audio_vae
+
+ @staticmethod
+ def _patch_oobleck_weight_norm():
+ try:
+ from torch.nn.utils import parametrizations
+ from diffusers.models.autoencoders import autoencoder_oobleck
+ autoencoder_oobleck.weight_norm = parametrizations.weight_norm
+ except Exception:
+ return
+
+ def _init_lm_hint_modules(self):
+ self._lm_hint_quantizer = None
+ self._lm_hint_detokenizer = None
+ try:
+ quantizer = self.ace_step_transformer.tokenizer.quantizer
+ detokenizer = self.ace_step_transformer.detokenizer
+ except AttributeError:
+ return
+
+ try:
+ self._lm_hint_quantizer = copy.deepcopy(quantizer).to(device="cpu", dtype=torch.float32).eval()
+ self._lm_hint_detokenizer = copy.deepcopy(detokenizer).to(device="cpu").eval()
+ for p in self._lm_hint_quantizer.parameters():
+ p.requires_grad_(False)
+ for p in self._lm_hint_detokenizer.parameters():
+ p.requires_grad_(False)
+ except Exception:
+ self._lm_hint_quantizer = None
+ self._lm_hint_detokenizer = None
+
+ self.audio_sample_rate = 48000
+ for attr in ("sampling_rate", "sample_rate"):
+ if hasattr(self.audio_vae, "config") and hasattr(self.audio_vae.config, attr):
+ self.audio_sample_rate = int(getattr(self.audio_vae.config, attr))
+ break
+
+ def _load_tokenizers(self):
+ self.pre_text_tokenizer = AutoTokenizer.from_pretrained(
+ self.text_encoder_2_tokenizer_dir,
+ local_files_only=True,
+ trust_remote_code=True,
+ )
+ if self.pre_text_tokenizer.pad_token_id is None:
+ self.pre_text_tokenizer.pad_token = self.pre_text_tokenizer.eos_token or self.pre_text_tokenizer.unk_token
+ self.pre_text_tokenizer.padding_side = "right"
+ self.lm_tokenizer = None
+ if not self.enable_lm:
+ return
+ try:
+ from shared.utils.transformers_fast_tokenizer_patch import load_cached_lm_tokenizer
+ self.lm_tokenizer = load_cached_lm_tokenizer(
+ self.lm_tokenizer_dir,
+ lambda: AutoTokenizer.from_pretrained(
+ self.lm_tokenizer_dir,
+ local_files_only=True,
+ trust_remote_code=True,
+ ),
+ )
+ except Exception:
+ self.lm_tokenizer = AutoTokenizer.from_pretrained(
+ self.lm_tokenizer_dir,
+ local_files_only=True,
+ trust_remote_code=True,
+ )
+ if self.lm_tokenizer.pad_token_id is None:
+ self.lm_tokenizer.pad_token = self.lm_tokenizer.eos_token or self.lm_tokenizer.unk_token
+ self.lm_tokenizer.padding_side = "left"
+ self._build_audio_code_vocab()
+
+ def _load_text_encoder_2(self):
+ config_path = os.path.join(os.path.dirname(self.text_encoder_2_weights_path), "config.json")
+ self.text_encoder_2 = offload.fast_load_transformers_model(
+ self.text_encoder_2_weights_path,
+ modelClass=Qwen3Model,
+ defaultConfigPath=config_path,
+ default_dtype=self.dtype,
+ ignore_unused_weights=True,
+ )
+ self.text_encoder_2.eval()
+
+ def _load_lm(self):
+ config_path = os.path.join(os.path.dirname(self.lm_weights_path), "config.json")
+ def _remap_lm_state_dict(state_dict, quantization_map=None, tied_weights_map=None):
+ # AceStep 5Hz LM weights are stored without a `model.` prefix.
+ if any(key.startswith("model.") for key in state_dict.keys()):
+ if "lm_head.weight" not in state_dict and "model.embed_tokens.weight" in state_dict:
+ state_dict["lm_head.weight"] = state_dict["model.embed_tokens.weight"]
+ return state_dict, quantization_map, tied_weights_map
+ remapped = {f"model.{key}": value for key, value in state_dict.items()}
+ if "model.embed_tokens.weight" in remapped and "lm_head.weight" not in remapped:
+ remapped["lm_head.weight"] = remapped["model.embed_tokens.weight"]
+ return remapped, quantization_map, tied_weights_map
+
+ self.lm_model = offload.fast_load_transformers_model(
+ self.lm_weights_path,
+ modelClass=Qwen3ForCausalLM,
+ defaultConfigPath=config_path,
+ default_dtype=self.dtype,
+ preprocess_sd=_remap_lm_state_dict,
+ ignore_unused_weights=True,
+ )
+ self.lm_model.eval()
+
+ def _load_silence_latent(self):
+ if not self.silence_latent_path or not os.path.isfile(self.silence_latent_path):
+ self.silence_latent = None
+ return
+ self.silence_latent = torch.load(self.silence_latent_path, map_location="cpu")
+
+ def _abort_requested(self) -> bool:
+ return bool(self._interrupt)
+
+ def _early_stop_requested(self) -> bool:
+ return bool(self._early_stop)
+
+ def request_early_stop(self) -> None:
+ self._early_stop = True
+
+ def _should_abort(self) -> bool:
+ return self._abort_requested() or self._early_stop_requested()
+
+ def _encode_prompt(self, prompt: str, max_length: int = 256, use_embed_tokens: bool = False):
+ tokens = self.pre_text_tokenizer(
+ prompt,
+ return_tensors="pt",
+ padding=True,
+ truncation=True,
+ max_length=max_length,
+ )
+ input_ids = tokens["input_ids"].to(self.device)
+ attention_mask = tokens.get("attention_mask")
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(self.device).bool()
+ with torch.no_grad():
+ if use_embed_tokens:
+ hidden_states = self.text_encoder_2.embed_tokens(input_ids)
+ else:
+ outputs = self.text_encoder_2(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ output_hidden_states=False,
+ use_cache=False,
+ )
+ hidden_states = outputs.last_hidden_state
+ return hidden_states, attention_mask
+
+ def _build_audio_code_vocab(self):
+ vocab = self.lm_tokenizer.get_vocab()
+ vocab_size = len(vocab)
+ audio_code_ids = []
+ audio_code_map = {}
+ max_code = self._get_audio_code_max()
+ self._audio_code_max = max_code
+ for token_text, token_id in vocab.items():
+ match = _AUDIO_CODE_TOKEN_RE.match(token_text)
+ if match:
+ code_val = int(match.group(1))
+ if max_code is not None and code_val > max_code:
+ continue
+ audio_code_ids.append(token_id)
+ audio_code_map[token_id] = code_val
+ self._audio_code_token_ids = audio_code_ids
+ self._audio_code_token_map = audio_code_map
+ mask = torch.full((vocab_size,), float("-inf"))
+ if audio_code_ids:
+ mask[audio_code_ids] = 0
+ self._audio_code_mask = mask
+
+ def _get_audio_code_max(self):
+ config = getattr(self, "ace_step_transformer", None)
+ if config is None:
+ return None
+ config = getattr(self.ace_step_transformer, "config", None)
+ if config is None:
+ return None
+ levels = getattr(config, "fsq_input_levels", None)
+ if not levels:
+ return None
+ total = 1
+ for level in levels:
+ try:
+ level_int = int(level)
+ except (TypeError, ValueError):
+ return None
+ if level_int <= 0:
+ return None
+ total *= level_int
+ if total <= 0:
+ return None
+ return total - 1
+
+ def _parse_audio_code_string(self, code_str):
+ if not code_str:
+ return []
+ try:
+ vals = [int(x) for x in _AUDIO_CODE_RE.findall(str(code_str))]
+ max_code = getattr(self, "_audio_code_max", None)
+ if max_code is not None:
+ vals = [v for v in vals if 0 <= v <= max_code]
+ return vals
+ except Exception:
+ return []
+
+ def _has_meaningful_negative_prompt(self, negative_prompt: str) -> bool:
+ return bool(negative_prompt and negative_prompt.strip() and negative_prompt.strip() != "NO USER INPUT")
+
+ def _format_lm_metadata_as_cot(self, metadata: dict) -> str:
+ cot_items = {}
+ for key in ("bpm", "caption", "duration", "keyscale", "language", "timesignature"):
+ if key in metadata and metadata[key] is not None:
+ value = metadata[key]
+ if key == "timesignature" and isinstance(value, str) and value.endswith("/4"):
+ value = value.split("/")[0]
+ if isinstance(value, str) and value.isdigit():
+ value = int(value)
+ cot_items[key] = value
+ if cot_items:
+ cot_yaml = yaml.dump(cot_items, allow_unicode=True, sort_keys=True).strip()
+ else:
+ cot_yaml = ""
+ return f"<think>\n{cot_yaml}\n</think>"
+
+ def _build_lm_prompt_with_cot(
+ self,
+ caption: str,
+ lyrics: str,
+ cot_text: str,
+ is_negative_prompt: bool = False,
+ negative_prompt: str = "NO USER INPUT",
+ ) -> str:
+ if is_negative_prompt:
+ has_negative = self._has_meaningful_negative_prompt(negative_prompt)
+ cot_for_prompt = "<think>\n</think>"
+ caption_for_prompt = negative_prompt if has_negative else caption
+ else:
+ cot_for_prompt = cot_text
+ caption_for_prompt = caption
+
+ user_prompt = f"# Caption\n{caption_for_prompt}\n\n# Lyric\n{lyrics}\n"
+ formatted = self.lm_tokenizer.apply_chat_template(
+ [
+ {"role": "system", "content": f"# Instruction\n{_DEFAULT_LM_INSTRUCTION}\n\n"},
+ {"role": "user", "content": user_prompt},
+ {"role": "assistant", "content": cot_for_prompt},
+ ],
+ tokenize=False,
+ add_generation_prompt=False,
+ )
+ if not formatted.endswith("\n"):
+ formatted += "\n"
+ return formatted
+
+ def _format_meta(self, bpm, duration, keyscale, timesignature):
+ duration_str = f"{duration} seconds" if isinstance(duration, (int, float)) else str(duration)
+ return (
+ f"- bpm: {bpm}\n"
+ f"- timesignature: {timesignature}\n"
+ f"- keyscale: {keyscale}\n"
+ f"- duration: {duration_str}\n"
+ )
+
+ def _build_text_prompt(self, caption, meta, instruction=None):
+ if instruction is None:
+ instruction = _DEFAULT_DIT_INSTRUCTION
+ return _SFT_GEN_PROMPT.format(instruction, caption, meta)
+
+ def _build_lyrics_prompt(self, lyrics, language):
+ return "# Languages\n{}\n\n# Lyric\n{}<|endoftext|>".format(language, lyrics)
+
+ def _generate_audio_codes(
+ self,
+ tags,
+ lyrics,
+ bpm,
+ duration,
+ keyscale,
+ timesignature,
+ seed,
+ min_tokens,
+ max_tokens,
+ temperature,
+ top_p,
+ top_k,
+ language="",
+ negative_prompt="NO USER INPUT",
+ cfg_scale=None,
+ callback=None,
+ ):
+ if cfg_scale is None:
+ cfg_scale = 2.5
+
+ metadata = {
+ "bpm": bpm,
+ "duration": duration,
+ "keyscale": keyscale,
+ "timesignature": timesignature,
+ }
+ if tags:
+ metadata["caption"] = tags
+ if language:
+ metadata["language"] = language
+ cot_text = self._format_lm_metadata_as_cot(metadata)
+
+ prompt = self._build_lm_prompt_with_cot(tags, lyrics, cot_text, is_negative_prompt=False, negative_prompt=negative_prompt)
+ prompt_negative = self._build_lm_prompt_with_cot(tags, lyrics, cot_text, is_negative_prompt=True, negative_prompt=negative_prompt)
+
+ pos_ids = self.lm_tokenizer(prompt, add_special_tokens=False)["input_ids"]
+ neg_ids = self.lm_tokenizer(prompt_negative, add_special_tokens=False)["input_ids"]
+
+ pad_id = self.lm_tokenizer.pad_token_id or self.lm_tokenizer.eos_token_id or 0
+ eos_token_id = self.lm_tokenizer.eos_token_id or pad_id
+
+ max_len = max(len(pos_ids), len(neg_ids))
+ pos_ids = ([pad_id] * (max_len - len(pos_ids))) + pos_ids
+ neg_ids = ([pad_id] * (max_len - len(neg_ids))) + neg_ids
+
+ input_ids = torch.tensor([pos_ids, neg_ids], device=self.device)
+ attention_mask = (input_ids != pad_id).to(torch.long)
+
+ generator = torch.Generator(device=self.device)
+ if seed is not None and seed >= 0:
+ generator.manual_seed(seed)
+
+ with torch.no_grad():
+ outputs = self.lm_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ use_cache=True,
+ )
+ past_key_values = outputs.past_key_values
+ next_logits = outputs.logits[:, -1]
+
+ audio_codes = []
+ max_new_tokens = max_tokens
+ audio_code_mask = None
+ if hasattr(self, "_audio_code_mask"):
+ audio_code_mask = self._audio_code_mask.to(device=self.device, dtype=next_logits.dtype)
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=max_new_tokens,
+ denoising_extra=f"LM codes 0/{max_new_tokens}",
+ progress_unit="tokens",
+ )
+
+ for step in tqdm(range(max_new_tokens), total=max_new_tokens, desc="LM codes", leave=False):
+ if self._should_abort():
+ return None
+
+ cond_logits = next_logits[0:1]
+ uncond_logits = next_logits[1:2]
+ cfg_logits = uncond_logits + cfg_scale * (cond_logits - uncond_logits)
+
+ if audio_code_mask is not None:
+ cfg_logits = cfg_logits + audio_code_mask
+
+ if top_k is not None and top_k > 0:
+ top_k_vals, _ = torch.topk(cfg_logits, top_k)
+ min_val = top_k_vals[..., -1, None]
+ cfg_logits[cfg_logits < min_val] = float("-inf")
+
+ if top_p is not None and 0 < top_p < 1.0:
+ sorted_logits, sorted_indices = torch.sort(cfg_logits, descending=True)
+ cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
+ sorted_indices_to_remove = cumulative_probs > top_p
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
+ sorted_indices_to_remove[..., 0] = 0
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
+ cfg_logits[indices_to_remove] = float("-inf")
+
+ if temperature is not None and temperature > 0:
+ cfg_logits = cfg_logits / float(temperature)
+ next_token = torch.multinomial(torch.softmax(cfg_logits, dim=-1), num_samples=1, generator=generator).squeeze(1)
+ else:
+ next_token = torch.argmax(cfg_logits, dim=-1)
+
+ token = int(next_token.item())
+ code_val = None
+ if hasattr(self, "_audio_code_token_map"):
+ code_val = self._audio_code_token_map.get(token)
+ if code_val is None:
+ token_text = self.lm_tokenizer.decode([token], skip_special_tokens=False)
+ match = _AUDIO_CODE_RE.search(token_text)
+ if match:
+ code_val = int(match.group(1))
+ if code_val is not None:
+ audio_codes.append(code_val)
+ if len(audio_codes) >= max_tokens:
+ break
+
+ next_input = torch.tensor([[token], [token]], device=self.device)
+ attention_mask = torch.cat(
+ [attention_mask, torch.ones((2, 1), device=self.device, dtype=attention_mask.dtype)],
+ dim=1,
+ )
+ with torch.no_grad():
+ outputs = self.lm_model(
+ input_ids=next_input,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ use_cache=True,
+ )
+ past_key_values = outputs.past_key_values
+ next_logits = outputs.logits[:, -1]
+
+ if callback is not None:
+ callback(
+ step_idx=int(step),
+ override_num_inference_steps=max_new_tokens,
+ denoising_extra=f"LM codes {step+1}/{max_new_tokens}",
+ progress_unit="tokens",
+ )
+
+ if len(audio_codes) == 0:
+ return []
+ if len(audio_codes) < min_tokens:
+ pad_val = audio_codes[-1]
+ audio_codes.extend([pad_val] * (min_tokens - len(audio_codes)))
+ return audio_codes[:max_tokens]
+
+ def _default_timbre_latents(self, length):
+ if self.silence_latent is not None:
+ return self._get_silence_latent(length, 1, self.device, self.dtype)
+ base = torch.tensor(_DEFAULT_TIMBRE, device=self.device, dtype=self.dtype)
+ base = base.view(1, 1, -1).repeat(1, max(1, length), 1)
+ if base.shape[1] > length:
+ base = base[:, :length, :]
+ elif base.shape[1] < length:
+ pad = length - base.shape[1]
+ base = torch.nn.functional.pad(base, (0, 0, 0, pad))
+ return base
+
+ def _get_silence_latent(self, length, batch_size, device, dtype):
+ if self.silence_latent is None:
+ return torch.zeros((batch_size, length, 64), device=device, dtype=dtype)
+ lat = self.silence_latent
+ if lat.dim() == 2:
+ lat = lat.unsqueeze(0)
+ if lat.dim() == 3 and lat.shape[1] != length:
+ if lat.shape[1] == 64:
+ lat = lat.permute(0, 2, 1)
+ if lat.shape[1] < length:
+ pad = length - lat.shape[1]
+ lat = torch.nn.functional.pad(lat, (0, 0, 0, pad))
+ elif lat.shape[1] > length:
+ lat = lat[:, :length, :]
+ if lat.shape[0] != batch_size:
+ lat = lat.repeat(batch_size, 1, 1)
+ return lat.to(device=device, dtype=dtype)
+
+ def _decode_audio_codes_to_latents(self, audio_codes, target_length, dtype):
+ if audio_codes is None:
+ return None
+ if not torch.is_tensor(audio_codes):
+ audio_codes = torch.tensor(audio_codes, device=self.device, dtype=torch.long)
+ if audio_codes.dim() == 1:
+ audio_codes = audio_codes.unsqueeze(0)
+ if audio_codes.dim() == 2:
+ audio_codes = audio_codes.unsqueeze(-1)
+
+ quantizer = self._lm_hint_quantizer or self.ace_step_transformer.tokenizer.quantizer
+ detokenizer = self._lm_hint_detokenizer or self.ace_step_transformer.detokenizer
+
+ def _resolve_module_device(module, fallback_device):
+ for tensor in module.parameters():
+ if torch.is_tensor(tensor) and tensor.device.type != "cpu":
+ return tensor.device
+ data = getattr(tensor, "_data", None)
+ if torch.is_tensor(data) and data.device.type != "cpu":
+ return data.device
+ for tensor in module.buffers():
+ if torch.is_tensor(tensor) and tensor.device.type != "cpu":
+ return tensor.device
+ proj = getattr(module, "project_out", None)
+ if proj is not None:
+ for attr in ("qweight", "weight"):
+ t = getattr(proj, attr, None)
+ if torch.is_tensor(t) and t.device.type != "cpu":
+ return t.device
+ data = getattr(t, "_data", None) if t is not None else None
+ if torch.is_tensor(data) and data.device.type != "cpu":
+ return data.device
+ return fallback_device
+
+ if quantizer is self._lm_hint_quantizer:
+ quantizer_device = _resolve_module_device(quantizer, next(quantizer.parameters(), torch.empty(0)).device)
+ else:
+ quantizer_device = self.device
+ if detokenizer is self._lm_hint_detokenizer:
+ detokenizer_device = _resolve_module_device(detokenizer, next(detokenizer.parameters(), torch.empty(0)).device)
+ else:
+ detokenizer_device = self.device
+ if quantizer_device is None:
+ quantizer_device = self.device
+ if detokenizer_device is None:
+ detokenizer_device = quantizer_device
+
+ audio_codes = audio_codes.to(device=quantizer_device)
+ quantized = quantizer.get_output_from_indices(audio_codes)
+ if detokenizer_device != quantizer_device:
+ quantized = quantized.to(device=detokenizer_device)
+ if quantized.dtype != dtype:
+ quantized = quantized.to(dtype)
+ lm_hints_25hz = detokenizer(quantized)
+ lm_hints_25hz = lm_hints_25hz[:, :target_length, :]
+ lm_hints_25hz = lm_hints_25hz.to(device=self.device, dtype=dtype)
+ return lm_hints_25hz
+
+ def _is_silence(self, audio):
+ return torch.all(audio.abs() < 1e-6)
+
+ def _normalize_audio_to_stereo_48k(self, audio, sr):
+ if audio.dim() == 1:
+ audio = audio.unsqueeze(0)
+ if audio.shape[0] == 1:
+ audio = torch.cat([audio, audio], dim=0)
+ audio = audio[:2]
+ if sr != self.audio_sample_rate:
+ audio = torchaudio.transforms.Resample(sr, self.audio_sample_rate)(audio)
+ audio = torch.clamp(audio, -1.0, 1.0)
+ return audio
+
+ def _process_reference_audio(self, audio_path):
+ if audio_path is None:
+ return None
+ audio, sr = torchaudio.load(audio_path)
+ audio = self._normalize_audio_to_stereo_48k(audio, sr)
+ if self._is_silence(audio):
+ return None
+
+ target_frames = int(30 * self.audio_sample_rate)
+ segment_frames = int(10 * self.audio_sample_rate)
+ if audio.shape[-1] < target_frames:
+ repeat_times = int(math.ceil(target_frames / max(1, audio.shape[-1])))
+ audio = audio.repeat(1, repeat_times)
+
+ total_frames = audio.shape[-1]
+ segment_size = total_frames // 3
+
+ def _rand_start(base, avail):
+ if avail <= 0:
+ return base
+ return base + random.randint(0, avail)
+
+ front_start = _rand_start(0, max(0, segment_size - segment_frames))
+ middle_start = _rand_start(segment_size, max(0, segment_size - segment_frames))
+ back_start = _rand_start(2 * segment_size, max(0, (total_frames - 2 * segment_size) - segment_frames))
+
+ front_audio = audio[:, front_start:front_start + segment_frames]
+ middle_audio = audio[:, middle_start:middle_start + segment_frames]
+ back_audio = audio[:, back_start:back_start + segment_frames]
+
+ return torch.cat([front_audio, middle_audio, back_audio], dim=-1)
+
+ def _process_src_audio(self, audio_path):
+ if audio_path is None:
+ return None
+ audio, sr = torchaudio.load(audio_path)
+ return self._normalize_audio_to_stereo_48k(audio, sr)
+
+ @torch.no_grad()
+ def _encode_waveform_to_latents(self, waveform, target_length, kwargs=None, pad_to_length=True):
+ if waveform is None:
+ return None
+ if waveform.dim() == 2:
+ waveform = waveform.unsqueeze(0)
+ if waveform.dim() != 3:
+ raise ValueError(f"Expected waveform shape [1, 2, T], got {tuple(waveform.shape)}")
+
+ def _normalize_latents(latents):
+ if latents.dim() == 2:
+ latents = latents.unsqueeze(0)
+ if latents.dim() == 3:
+ if latents.shape[-1] == 64:
+ pass
+ elif latents.shape[1] == 64:
+ latents = latents.permute(0, 2, 1)
+ return latents
+
+ total_samples = waveform.shape[-1]
+ duration_seconds = total_samples / float(self.audio_sample_rate) if self.audio_sample_rate else None
+ tile_seconds = self._get_vae_temporal_tile_seconds(kwargs, duration_seconds)
+
+ latents = None
+ if tile_seconds is not None and tile_seconds > 0:
+ tile_samples = int(round(tile_seconds * self.audio_sample_rate))
+ if tile_samples > 0 and total_samples > tile_samples:
+ overlap_samples = int(round(tile_samples * 0.25))
+ if overlap_samples >= tile_samples:
+ overlap_samples = max(0, tile_samples // 4)
+ step = max(1, tile_samples - overlap_samples)
+ hop = int(self._latent_hop_length)
+ overlap_frames = int(round(overlap_samples / max(1, hop)))
+
+ for start in range(0, total_samples, step):
+ end = min(start + tile_samples, total_samples)
+ chunk = waveform[..., start:end].to(self.device)
+ encoded = self.audio_vae.encode(chunk)
+ chunk_latents = _normalize_latents(encoded.latent_dist.mode())
+ if latents is None:
+ latents = chunk_latents
+ else:
+ if overlap_frames > 0 and latents.shape[1] >= overlap_frames and chunk_latents.shape[1] >= overlap_frames:
+ fade = torch.linspace(
+ 0.0,
+ 1.0,
+ overlap_frames,
+ device=chunk_latents.device,
+ dtype=chunk_latents.dtype,
+ ).view(1, -1, 1)
+ latents[:, -overlap_frames:, :] = (
+ latents[:, -overlap_frames:, :] * (1.0 - fade)
+ + chunk_latents[:, :overlap_frames, :] * fade
+ )
+ latents = torch.cat([latents, chunk_latents[:, overlap_frames:, :]], dim=1)
+ else:
+ latents = torch.cat([latents, chunk_latents], dim=1)
+ del chunk
+ if latents is None:
+ latents = torch.zeros((1, 1, 64), device=self.device, dtype=self.dtype)
+ else:
+ tile_seconds = None
+
+ if tile_seconds is None:
+ encoded = self.audio_vae.encode(waveform.to(self.device))
+ latents = _normalize_latents(encoded.latent_dist.mode())
+
+ if pad_to_length and target_length is not None:
+ if latents.shape[1] > target_length:
+ latents = latents[:, :target_length, :]
+ elif latents.shape[1] < target_length:
+ pad = target_length - latents.shape[1]
+ latents = torch.nn.functional.pad(latents, (0, 0, 0, pad))
+ return latents.to(device=self.device, dtype=self.dtype)
+
+ @torch.no_grad()
+ def _encode_reference_audio(self, audio_path, target_length, kwargs=None, pad_to_length=True, use_reference_processing=True):
+ if audio_path is None:
+ return None
+ if use_reference_processing:
+ waveform = self._process_reference_audio(audio_path)
+ else:
+ waveform = self._process_src_audio(audio_path)
+ return self._encode_waveform_to_latents(waveform, target_length, kwargs, pad_to_length=pad_to_length)
+
+ def _get_vae_temporal_tile_seconds(self, kwargs, duration_seconds):
+ if kwargs is None:
+ kwargs = {}
+ if kwargs.get("vae_temporal_tiling", True) is False:
+ return None
+ tile_seconds = kwargs.get("vae_temporal_tile_seconds", None)
+ if tile_seconds is not None:
+ try:
+ tile_seconds = float(tile_seconds)
+ except (TypeError, ValueError):
+ tile_seconds = None
+ if tile_seconds is not None and tile_seconds <= 0:
+ return None
+ if tile_seconds is None:
+ tile_choice = kwargs.get("VAE_tile_size")
+ tile_size = None
+ if isinstance(tile_choice, dict):
+ tile_size = tile_choice.get("tile_sample_min_size")
+ if tile_size is None:
+ tile_size = tile_choice.get("tile_latent_min_size")
+ elif isinstance(tile_choice, (list, tuple)):
+ if len(tile_choice) >= 2:
+ if isinstance(tile_choice[0], bool) and not tile_choice[0]:
+ tile_size = 0
+ else:
+ try:
+ tile_size = int(tile_choice[1])
+ except (TypeError, ValueError):
+ tile_size = None
+ elif len(tile_choice) == 1:
+ try:
+ tile_size = int(tile_choice[0])
+ except (TypeError, ValueError):
+ tile_size = None
+ elif isinstance(tile_choice, (int, float, bool)):
+ tile_size = int(tile_choice)
+
+ if tile_size is None:
+ if not torch.cuda.is_available():
+ return None
+ try:
+ device_index = self.device.index if getattr(self.device, "type", None) == "cuda" else 0
+ total_gb = torch.cuda.get_device_properties(device_index).total_memory / (1024 ** 3)
+ except Exception:
+ total_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
+ if total_gb >= 24:
+ tile_seconds = 80.0
+ elif total_gb >= 12:
+ tile_seconds = 40.0
+ else:
+ tile_seconds = 20.0
+ else:
+ if tile_size <= 0:
+ tile_seconds = 80.0
+ elif tile_size >= 256:
+ tile_seconds = 40.0
+ else:
+ tile_seconds = 20.0
+ if duration_seconds is not None and tile_seconds is not None and duration_seconds <= tile_seconds:
+ return None
+ return tile_seconds
+
+ def _decode_latents_tiled(self, latents, tile_seconds, overlap_factor=0.25):
+ if tile_seconds is None or tile_seconds <= 0:
+ return None
+ frames_per_sec = self.audio_sample_rate / float(self._latent_hop_length)
+ tile_frames = int(round(tile_seconds * frames_per_sec))
+ if tile_frames <= 0:
+ return None
+ overlap_frames = int(round(tile_frames * float(overlap_factor)))
+ if overlap_frames < 0:
+ overlap_frames = 0
+ if overlap_frames >= tile_frames:
+ overlap_frames = max(0, tile_frames // 4)
+
+ batch_size, channels, total_frames = latents.shape
+ if total_frames <= tile_frames:
+ return None
+
+ hop = int(self._latent_hop_length)
+ total_samples = total_frames * hop
+ step = max(1, tile_frames - overlap_frames)
+
+ output = None
+ for start in range(0, total_frames, step):
+ end = min(start + tile_frames, total_frames)
+ chunk = latents[:, :, start:end]
+ with torch.no_grad():
+ decoded = self.audio_vae.decode(chunk)
+ chunk_audio = decoded.sample
+ expected = (end - start) * hop
+ if chunk_audio.shape[-1] > expected:
+ chunk_audio = chunk_audio[..., :expected]
+ elif chunk_audio.shape[-1] < expected:
+ pad = expected - chunk_audio.shape[-1]
+ chunk_audio = torch.nn.functional.pad(chunk_audio, (0, pad))
+ if output is None:
+ output = chunk_audio.new_zeros((batch_size, chunk_audio.shape[1], total_samples))
+ start_sample = start * hop
+ end_sample = start_sample + expected
+ if start == 0 or overlap_frames == 0:
+ output[..., start_sample:end_sample] = chunk_audio
+ else:
+ ov = min(overlap_frames * hop, start_sample, expected)
+ if ov > 0:
+ fade = torch.linspace(0.0, 1.0, ov, device=chunk_audio.device, dtype=chunk_audio.dtype).view(1, 1, -1)
+ output[..., start_sample:start_sample + ov] = (
+ output[..., start_sample:start_sample + ov] * (1.0 - fade)
+ + chunk_audio[..., :ov] * fade
+ )
+ output[..., start_sample + ov:end_sample] = chunk_audio[..., ov:]
+ else:
+ output[..., start_sample:end_sample] = chunk_audio
+ return output
+
+ def _build_t_schedule(self, shift, timesteps):
+ valid_shifts = [1.0, 2.0, 3.0]
+ valid_timesteps = [
+ 1.0, 0.9545454545454546, 0.9333333333333333, 0.9, 0.875,
+ 0.8571428571428571, 0.8333333333333334, 0.7692307692307693, 0.75,
+ 0.6666666666666666, 0.6428571428571429, 0.625, 0.5454545454545454,
+ 0.5, 0.4, 0.375, 0.3, 0.25, 0.2222222222222222, 0.125,
+ ]
+ shift_timesteps = {
+ 1.0: [1.0, 0.875, 0.75, 0.625, 0.5, 0.375, 0.25, 0.125],
+ 2.0: [1.0, 0.9333333333333333, 0.8571428571428571, 0.7692307692307693, 0.6666666666666666, 0.5454545454545454, 0.4, 0.2222222222222222],
+ 3.0: [1.0, 0.9545454545454546, 0.9, 0.8333333333333334, 0.75, 0.6428571428571429, 0.5, 0.3],
+ }
+
+ if timesteps is not None:
+ t_list = timesteps.tolist() if isinstance(timesteps, torch.Tensor) else list(timesteps)
+ while len(t_list) > 0 and t_list[-1] == 0:
+ t_list.pop()
+ if len(t_list) > 20:
+ t_list = t_list[:20]
+ if len(t_list) >= 1:
+ mapped = [min(valid_timesteps, key=lambda x: abs(x - t)) for t in t_list]
+ return mapped
+
+ shift_val = min(valid_shifts, key=lambda x: abs(x - float(shift)))
+ return shift_timesteps[shift_val]
+
+ def _sample_latents(
+ self,
+ noise,
+ text_hidden_states,
+ text_attention_mask,
+ lyric_hidden_states,
+ lyric_attention_mask,
+ refer_audio,
+ refer_audio_order_mask,
+ audio_codes,
+ src_latents,
+ use_cover,
+ non_cover_text_hidden_states,
+ non_cover_text_attention_mask,
+ audio_cover_strength,
+ shift,
+ timesteps,
+ infer_method,
+ callback=None,
+ ):
+ t_schedule_list = self._build_t_schedule(shift, timesteps)
+ t_schedule = torch.tensor(t_schedule_list, device=self.device, dtype=noise.dtype)
+ num_steps = len(t_schedule)
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=num_steps,
+ denoising_extra=f"0/{num_steps} steps",
+ progress_unit="steps",
+ )
+
+ batch_size = noise.shape[0]
+ latent_length = noise.shape[1]
+ silence_latent = self._get_silence_latent(latent_length, batch_size, noise.device, noise.dtype)
+ src_latents_for_condition = src_latents if src_latents is not None else silence_latent
+ if src_latents_for_condition.device != noise.device:
+ src_latents_for_condition = src_latents_for_condition.to(noise.device)
+ if src_latents_for_condition.dtype != noise.dtype:
+ src_latents_for_condition = src_latents_for_condition.to(noise.dtype)
+ if src_latents_for_condition.shape[1] > latent_length:
+ src_latents_for_condition = src_latents_for_condition[:, :latent_length, :]
+ elif src_latents_for_condition.shape[1] < latent_length:
+ pad = latent_length - src_latents_for_condition.shape[1]
+ src_latents_for_condition = torch.nn.functional.pad(src_latents_for_condition, (0, 0, 0, pad))
+
+ chunk_masks = torch.ones_like(src_latents_for_condition)
+ precomputed_lm_hints = None
+ audio_codes_for_condition = audio_codes
+ is_covers = torch.ones((batch_size,), device=noise.device, dtype=torch.long) if use_cover else torch.zeros((batch_size,), device=noise.device, dtype=torch.long)
+
+ latent_attention_mask = torch.ones((batch_size, latent_length), device=noise.device, dtype=torch.bool)
+
+ refer_audio_packed = refer_audio
+ if refer_audio_packed.dim() == 3 and refer_audio_packed.shape[-1] != 64:
+ refer_audio_packed = refer_audio_packed.permute(0, 2, 1)
+
+ if refer_audio_order_mask is None:
+ refer_audio_order_mask = torch.arange(batch_size, device=noise.device, dtype=torch.long)
+
+ encoder_hidden_states, encoder_attention_mask, context_latents = self.ace_step_transformer.prepare_condition(
+ text_hidden_states=text_hidden_states,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ hidden_states=src_latents_for_condition,
+ attention_mask=latent_attention_mask,
+ silence_latent=silence_latent,
+ src_latents=src_latents_for_condition,
+ chunk_masks=chunk_masks,
+ is_covers=is_covers,
+ precomputed_lm_hints_25Hz=precomputed_lm_hints,
+ audio_codes=audio_codes_for_condition,
+ )
+
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = None, None, None
+ if audio_cover_strength < 1.0:
+ non_is_covers = torch.zeros_like(is_covers, device=noise.device, dtype=is_covers.dtype)
+ silence_latent_expanded = silence_latent[:, :latent_length, :].expand(batch_size, -1, -1)
+ text_hidden_states_non_cover = text_hidden_states if non_cover_text_hidden_states is None else non_cover_text_hidden_states
+ text_attention_mask_non_cover = text_attention_mask if non_cover_text_attention_mask is None else non_cover_text_attention_mask
+ encoder_hidden_states_non_cover, encoder_attention_mask_non_cover, context_latents_non_cover = self.ace_step_transformer.prepare_condition(
+ text_hidden_states=text_hidden_states_non_cover,
+ text_attention_mask=text_attention_mask_non_cover,
+ lyric_hidden_states=lyric_hidden_states,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio_acoustic_hidden_states_packed=refer_audio_packed,
+ refer_audio_order_mask=refer_audio_order_mask,
+ hidden_states=silence_latent_expanded,
+ attention_mask=latent_attention_mask,
+ silence_latent=silence_latent,
+ src_latents=silence_latent_expanded,
+ chunk_masks=chunk_masks,
+ is_covers=non_is_covers,
+ precomputed_lm_hints_25Hz=None,
+ audio_codes=None,
+ )
+
+ cover_steps = int(num_steps * audio_cover_strength)
+
+ xt = noise
+ for i, t in tqdm(enumerate(t_schedule), total=num_steps):
+ if self._should_abort():
+ return None
+ t_tensor = t * torch.ones((batch_size,), device=xt.device, dtype=xt.dtype)
+ if (encoder_hidden_states_non_cover is not None) and (i >= cover_steps):
+ encoder_hidden_states = encoder_hidden_states_non_cover
+ encoder_attention_mask = encoder_attention_mask_non_cover
+ context_latents = context_latents_non_cover
+ with torch.no_grad():
+ vt = self.ace_step_transformer.decoder(
+ hidden_states=xt,
+ timestep=t_tensor,
+ timestep_r=t_tensor,
+ attention_mask=latent_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ context_latents=context_latents,
+ )[0]
+
+ if i == num_steps - 1:
+ xt = xt - vt * t_tensor.view(-1, 1, 1)
+ break
+
+ next_t = t_schedule[i + 1]
+ if infer_method == "sde":
+ pred_clean = xt - vt * t_tensor.view(-1, 1, 1)
+ xt = next_t * torch.randn_like(pred_clean) + (1 - next_t) * pred_clean
+ else:
+ dt = t - next_t
+ xt = xt - vt * dt
+
+ if callback is not None:
+ callback(
+ step_idx=int(i),
+ override_num_inference_steps=num_steps,
+ denoising_extra=f"{i+1}/{num_steps} steps",
+ progress_unit="steps",
+ )
+
+ return xt
+
+ def generate(
+ self,
+ input_prompt: str,
+ model_mode,
+ audio_guide,
+ *,
+ alt_prompt=None,
+ audio_guide2=None,
+ audio_prompt_type="",
+ temperature: float = 1.0,
+ **kwargs,
+ ):
+ self._interrupt = False
+ self._early_stop = False
+
+ if not self.loaded:
+ raise RuntimeError("ACE-Step 1.5 weights are not loaded.")
+
+ lyrics = (input_prompt or "").strip()
+ if not lyrics:
+ raise ValueError("Lyrics prompt cannot be empty for ACE-Step 1.5.")
+
+ tags = "" if alt_prompt is None else str(alt_prompt)
+
+ duration_seconds = kwargs.get("duration_seconds")
+ if duration_seconds is None:
+ duration_seconds = kwargs.get("audio_duration")
+ try:
+ duration_seconds = float(duration_seconds) if duration_seconds is not None else 20.0
+ except (TypeError, ValueError):
+ duration_seconds = 20.0
+
+ num_inference_steps = kwargs.get("num_inference_steps") or kwargs.get("sampling_steps") or 60
+ try:
+ num_inference_steps = int(num_inference_steps)
+ except (TypeError, ValueError):
+ num_inference_steps = 60
+
+ guidance_scale = kwargs.get("guidance_scale", 7.0)
+ try:
+ guidance_scale = float(guidance_scale)
+ except (TypeError, ValueError):
+ guidance_scale = 7.0
+
+ scheduler_type = model_mode or kwargs.get("scheduler_type", "euler")
+ seed = kwargs.get("seed")
+ try:
+ seed = int(seed) if seed is not None else None
+ except (TypeError, ValueError):
+ seed = None
+
+ batch_size = kwargs.get("batch_size", 1)
+ try:
+ batch_size = int(batch_size)
+ except (TypeError, ValueError):
+ batch_size = 1
+
+ bpm = int(kwargs.get("bpm", 120))
+ timesignature = int(kwargs.get("timesignature", 2))
+ keyscale = kwargs.get("keyscale", "C major")
+ language = kwargs.get("language", "en")
+
+ duration_int = int(math.ceil(duration_seconds))
+ min_tokens = duration_int * 5
+
+ top_p = kwargs.get("top_p", 0.9)
+ top_k = kwargs.get("top_k", None)
+
+ callback = kwargs.get("callback")
+
+ meta_cap = self._format_meta(bpm, duration_int, keyscale, timesignature)
+ use_ref = "A" in (audio_prompt_type or "")
+ use_timbre = "B" in (audio_prompt_type or "")
+ has_src_audio = bool(use_ref and audio_guide)
+
+ user_audio_codes = kwargs.get("audio_codes")
+ if user_audio_codes is None:
+ user_audio_codes = kwargs.get("audio_code_hints")
+ if isinstance(user_audio_codes, str):
+ parsed = self._parse_audio_code_string(user_audio_codes)
+ user_audio_codes = parsed if parsed else None
+ elif isinstance(user_audio_codes, (list, tuple)) and user_audio_codes:
+ if isinstance(user_audio_codes[0], str):
+ parsed = self._parse_audio_code_string(user_audio_codes[0])
+ user_audio_codes = parsed if parsed else None
+
+ audio_codes = None
+ if user_audio_codes:
+ max_code = getattr(self, "_audio_code_max", None)
+ if max_code is not None:
+ bad_codes = [v for v in user_audio_codes if v < 0 or v > max_code]
+ if bad_codes:
+ raise ValueError(f"Audio codes out of range 0..{max_code}; example={bad_codes[0]}")
+ audio_codes = user_audio_codes
+ elif self.enable_lm and not has_src_audio:
+ audio_codes = self._generate_audio_codes(
+ tags=tags,
+ lyrics=lyrics,
+ bpm=bpm,
+ duration=duration_int,
+ keyscale=keyscale,
+ timesignature=timesignature,
+ seed=seed if seed is not None else 0,
+ min_tokens=min_tokens,
+ max_tokens=min_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ language=language,
+ negative_prompt=kwargs.get("lm_negative_prompt", "NO USER INPUT"),
+ cfg_scale=kwargs.get("lm_cfg_scale"),
+ callback=callback,
+ )
+ if audio_codes is None:
+ return None
+ if len(audio_codes) == 0:
+ raise RuntimeError("Audio code generation aborted or failed.")
+ max_code = getattr(self, "_audio_code_max", None)
+ if max_code is not None:
+ bad_codes = [v for v in audio_codes if v < 0 or v > max_code]
+ if bad_codes:
+ raise RuntimeError(f"LM generated out-of-range audio codes; example={bad_codes[0]}")
+
+ if audio_codes is not None:
+ audio_codes = torch.tensor(audio_codes, device=self.device, dtype=torch.long).unsqueeze(0).unsqueeze(-1)
+
+ use_cover = (audio_codes is not None) or has_src_audio
+
+ instruction = _DEFAULT_LM_INSTRUCTION if use_cover else _DEFAULT_DIT_INSTRUCTION
+ text_prompt = self._build_text_prompt(tags, meta_cap, instruction=instruction)
+ lyrics_prompt = self._build_lyrics_prompt(lyrics, language)
+
+ context, text_attention_mask = self._encode_prompt(text_prompt, max_length=256, use_embed_tokens=False)
+ lyric_hidden, lyric_attention_mask = self._encode_prompt(lyrics_prompt, max_length=2048, use_embed_tokens=True)
+ lyric_embed = lyric_hidden
+ if batch_size > 1:
+ context = context.repeat(batch_size, 1, 1)
+ lyric_embed = lyric_embed.repeat(batch_size, 1, 1)
+ if audio_codes is not None:
+ audio_codes = audio_codes.repeat(batch_size, 1, 1)
+
+ latent_length = int(round(duration_seconds * self.audio_sample_rate / self._latent_hop_length))
+ latent_length = max(latent_length, 1)
+
+ timbre_length = int(getattr(self.ace_step_transformer.config, "timbre_fix_frame", 750))
+ default_ref = self._default_timbre_latents(timbre_length)
+
+ src_latents = None
+ if use_ref and audio_guide:
+ src_latents = self._encode_reference_audio(audio_guide, latent_length, kwargs, pad_to_length=True, use_reference_processing=False)
+ timbre_latents = None
+ if use_timbre and audio_guide2:
+ timbre_latents = self._encode_reference_audio(audio_guide2, timbre_length, kwargs, pad_to_length=True, use_reference_processing=True)
+
+ refer_audio_latents = []
+ refer_audio_order_mask = []
+ if timbre_latents is not None:
+ refer_audio_latents.append(timbre_latents)
+ refer_audio_order_mask.append(0)
+ if not refer_audio_latents:
+ refer_audio_latents.append(default_ref)
+ refer_audio_order_mask.append(0)
+
+ refer_audio = torch.cat(refer_audio_latents, dim=0)
+ refer_audio_order_mask = torch.tensor(refer_audio_order_mask, device=self.device, dtype=torch.long)
+
+ if batch_size > 1:
+ refer_audio = refer_audio.repeat(batch_size, 1, 1)
+ refer_audio_order_mask = refer_audio_order_mask.repeat(batch_size) + torch.arange(batch_size, device=self.device).repeat_interleave(len(refer_audio_latents))
+
+ audio_cover_strength = kwargs.get("audio_scale", 1.0)
+ try:
+ audio_cover_strength = float(audio_cover_strength)
+ except (TypeError, ValueError):
+ audio_cover_strength = 1.0
+ audio_cover_strength = max(0.0, min(1.0, audio_cover_strength))
+ if not use_cover:
+ audio_cover_strength = 1.0
+
+ shift = kwargs.get("shift", 1.0)
+ timesteps = kwargs.get("timesteps")
+ infer_method = kwargs.get("infer_method", "ode")
+
+ silence_latent = self._get_silence_latent(latent_length, batch_size, self.device, self.dtype)
+
+ rng = None
+ if seed is not None and seed >= 0:
+ rng = torch.Generator(device=self.device).manual_seed(seed)
+ if rng is None:
+ noise = torch.randn_like(silence_latent)
+ else:
+ noise = torch.randn(
+ silence_latent.shape,
+ device=silence_latent.device,
+ dtype=silence_latent.dtype,
+ generator=rng,
+ )
+
+ non_cover_text_hidden_states = None
+ non_cover_text_attention_mask = None
+ if use_cover and audio_cover_strength < 1.0:
+ non_cover_text_prompt = self._build_text_prompt(tags, meta_cap, instruction=_DEFAULT_DIT_INSTRUCTION)
+ non_cover_text_hidden_states, non_cover_text_attention_mask = self._encode_prompt(
+ non_cover_text_prompt,
+ max_length=256,
+ use_embed_tokens=False,
+ )
+ if batch_size > 1:
+ non_cover_text_hidden_states = non_cover_text_hidden_states.repeat(batch_size, 1, 1)
+ non_cover_text_attention_mask = non_cover_text_attention_mask.repeat(batch_size, 1)
+
+ sampled_latents = self._sample_latents(
+ noise=noise,
+ text_hidden_states=context,
+ text_attention_mask=text_attention_mask,
+ lyric_hidden_states=lyric_embed,
+ lyric_attention_mask=lyric_attention_mask,
+ refer_audio=refer_audio,
+ refer_audio_order_mask=refer_audio_order_mask,
+ audio_codes=audio_codes,
+ src_latents=src_latents,
+ use_cover=use_cover,
+ non_cover_text_hidden_states=non_cover_text_hidden_states,
+ non_cover_text_attention_mask=non_cover_text_attention_mask,
+ audio_cover_strength=audio_cover_strength,
+ shift=shift,
+ timesteps=timesteps,
+ infer_method=infer_method,
+ callback=callback,
+ )
+
+ if sampled_latents is None:
+ return None
+
+ sampled_latents = sampled_latents.permute(0, 2, 1)
+ tile_seconds = self._get_vae_temporal_tile_seconds(kwargs, duration_seconds)
+ tiled_audio = self._decode_latents_tiled(sampled_latents, tile_seconds)
+ if tiled_audio is None:
+ with torch.no_grad():
+ decoded = self.audio_vae.decode(sampled_latents)
+ audio = decoded.sample
+ else:
+ audio = tiled_audio
+
+ target_samples = int(round(duration_seconds * self.audio_sample_rate))
+ if audio.shape[-1] > target_samples:
+ audio = audio[..., :target_samples]
+
+ return {
+ "x": audio,
+ "audio_sampling_rate": int(self.audio_sample_rate),
+ }
diff --git a/models/TTS/ace_step_handler.py b/models/TTS/ace_step_handler.py
index 21e527f..7ac5c06 100644
--- a/models/TTS/ace_step_handler.py
+++ b/models/TTS/ace_step_handler.py
@@ -23,6 +23,31 @@ ACE_STEP_TEXT_ENCODER_URL = (
f"{ACE_STEP_TEXT_ENCODER_FOLDER}/{ACE_STEP_TEXT_ENCODER_NAME}"
)
+ACE_STEP15_REPO_ID = "DeepBeepMeep/TTS"
+ACE_STEP15_REPO_FOLDER = "ace_step15"
+ACE_STEP15_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "ace_step15", "configs")
+
+ACE_STEP15_TRANSFORMER_CONFIG_NAME = "ace_step_v1_5_transformer_config.json"
+ACE_STEP15_VAE_WEIGHTS_NAME = "ace_step_v1_5_audio_vae_bf16.safetensors"
+ACE_STEP15_VAE_CONFIG_NAME = "ace_step_v1_5_audio_vae_config.json"
+ACE_STEP15_TEXT_ENCODER_2_FOLDER = "Qwen3-Embedding-0.6B"
+ACE_STEP15_TEXT_ENCODER_2_NAME = "model.safetensors"
+ACE_STEP15_LM_FOLDER = "acestep-5Hz-lm-1.7B"
+ACE_STEP15_SILENCE_LATENT_NAME = "silence_latent.pt"
+
+ACE_STEP15_TRANSFORMER_VARIANTS = {
+ "base": "ace_step_v1_5_transformer_config_base.json",
+ "sft": "ace_step_v1_5_transformer_config_sft.json",
+ "turbo": "ace_step_v1_5_transformer_config_turbo.json",
+ "turbo_shift1": "ace_step_v1_5_transformer_config_turbo_shift1.json",
+ "turbo_shift3": "ace_step_v1_5_transformer_config_turbo_shift3.json",
+ "turbo_continuous": "ace_step_v1_5_transformer_config_turbo_continuous.json",
+}
+
+def _ace_step15_lm_weights_name(lm_folder):
+ folder_name = os.path.basename(os.path.normpath(str(lm_folder)))
+ return f"{folder_name}_bf16.safetensors"
+
ACE_STEP_DURATION_SLIDER = {
"label": "Duration (seconds)",
"min": 5,
@@ -31,10 +56,14 @@ ACE_STEP_DURATION_SLIDER = {
"default": 20,
}
+
def _get_model_path(model_def, key, default):
if not model_def:
return default
- value = model_def.get(key, default)
+ value = model_def.get(key, None)
+ if value is None or value == "":
+ model_block = model_def.get("model", {}) if isinstance(model_def, dict) else {}
+ value = model_block.get(key, None)
return value or default
def _ace_step_ckpt_file(filename):
@@ -51,10 +80,36 @@ def _ckpt_dir(dirname):
return fl.locate_folder(dirname, error_if_none=False) or dirname
+def _ace_step15_ckpt_file(filename):
+ rel_path = os.path.join(ACE_STEP15_REPO_FOLDER, filename)
+ return fl.locate_file(rel_path, error_if_none=False) or rel_path
+
+
+def _ace_step15_ckpt_dir(dirname):
+ rel_path = os.path.join(ACE_STEP15_REPO_FOLDER, dirname)
+ return fl.locate_folder(rel_path, error_if_none=False) or rel_path
+
+
+def _ace_step15_lm_ckpt_file(filename):
+ return fl.locate_file(filename, error_if_none=False) or filename
+
+
+def _ace_step15_lm_ckpt_dir(dirname):
+ return fl.locate_folder(dirname, error_if_none=False) or dirname
+
+
+def _ace_step15_config_path(filename):
+ return os.path.join(ACE_STEP15_CONFIG_DIR, filename)
+
+
+def _is_ace_step15(base_model_type):
+ return base_model_type == "ace_step_v1_5"
+
+
class family_handler:
@staticmethod
def query_supported_types():
- return ["ace_step_v1"]
+ return ["ace_step_v1", "ace_step_v1_5"]
@staticmethod
def query_family_maps():
@@ -76,13 +131,60 @@ class family_handler:
default=None,
help=f"Path to a directory that contains Ace Step settings (default: {os.path.join(lora_root, 'ace_step')})",
)
+ parser.add_argument(
+ "--lora-dir-ace-step15",
+ dest="lora_ace_step15",
+ type=str,
+ default=None,
+ help=f"Path to a directory that contains Ace Step 1.5 settings (default: {os.path.join(lora_root, 'ace_step_v1_5')})",
+ )
@staticmethod
def get_lora_dir(base_model_type, args, lora_root):
+ if _is_ace_step15(base_model_type):
+ return getattr(args, "lora_ace_step15", None) or os.path.join(lora_root, "ace_step_v1_5")
return getattr(args, "lora_ace_step", None) or os.path.join(lora_root, "ace_step")
@staticmethod
def query_model_def(base_model_type, model_def):
+ if _is_ace_step15(base_model_type):
+ return {
+ "audio_only": True,
+ "image_outputs": False,
+ "sliding_window": False,
+ "guidance_max_phases": 1,
+ "no_negative_prompt": True,
+ "image_prompt_types_allowed": "",
+ "profiles_dir": ["ace_step_v1_5"],
+ "text_encoder_folder": _get_model_path(model_def, "text_encoder_folder", ACE_STEP15_LM_FOLDER),
+ "inference_steps": True,
+ "temperature": True,
+ "any_audio_prompt": True,
+ "audio_guide_label": "Reference Audio",
+ "audio_guide2_label": "Reference Timbre",
+ "audio_scale_name": "Reference Audio Strength",
+ "audio_prompt_choices": True,
+ "enabled_audio_lora": False,
+ "audio_prompt_type_sources": {
+ "selection": ["", "A", "B", "AB"],
+ "labels": {
+ "": "No Reference Audio / No Reference Timbre",
+ "A": "Reference Audio (need to provide original lyrics and set a Reference Audio Strength)",
+ "B": "Reference Timbre",
+ "AB": "Reference Audio + Timbre",
+ },
+ "default": "",
+ "label": "Reference Sources",
+ "letters_filter": "AB",
+ },
+ "alt_prompt": {
+ "label": "Genres / Tags",
+ "placeholder": "disco",
+ "lines": 2,
+ },
+ "duration_slider": dict(ACE_STEP_DURATION_SLIDER),
+ "text_prompt_enhancer_instructions": HEARTMULA_LYRIC_PROMPT,
+ }
return {
"audio_only": True,
"image_outputs": False,
@@ -121,6 +223,51 @@ class family_handler:
@staticmethod
def query_model_files(computeList, base_model_type, model_def=None):
+ if _is_ace_step15(base_model_type):
+ enable_lm = bool(_get_model_path(model_def, "ace_step15_enable_lm", False))
+ text_encoder_2_folder = _get_model_path(model_def, "ACE_STEP15_TEXT_ENCODER_2_FOLDER", ACE_STEP15_TEXT_ENCODER_2_FOLDER)
+ base_files = [
+ ACE_STEP15_VAE_WEIGHTS_NAME,
+ ACE_STEP15_SILENCE_LATENT_NAME,
+ ]
+ text_encoder_2_files = [
+ ACE_STEP15_TEXT_ENCODER_2_NAME,
+ "config.json",
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "special_tokens_map.json",
+ ]
+ source_folders = [
+ ACE_STEP15_REPO_FOLDER,
+ text_encoder_2_folder,
+ ]
+ file_lists = [
+ base_files,
+ text_encoder_2_files,
+ ]
+ target_folders = [None, None]
+ if enable_lm:
+ lm_folder = _get_model_path(model_def, "text_encoder_folder", ACE_STEP15_LM_FOLDER)
+ lm_files = [
+ "config.json",
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "special_tokens_map.json",
+ "added_tokens.json",
+ "merges.txt",
+ "vocab.json",
+ "chat_template.jinja",
+ ]
+ source_folders.append(lm_folder)
+ file_lists.append(lm_files)
+ target_folders.append(None)
+ return {
+ "repoId": ACE_STEP15_REPO_ID,
+ "sourceFolderList": source_folders,
+ "targetFolderList": target_folders,
+ "fileList": file_lists,
+ }
+ text_encoder_folder = _get_model_path(model_def, "text_encoder_folder", ACE_STEP_TEXT_ENCODER_FOLDER)
base_files = [
ACE_STEP_TRANSFORMER_CONFIG_NAME,
ACE_STEP_DCAE_WEIGHTS_NAME,
@@ -138,7 +285,7 @@ class family_handler:
"repoId": ACE_STEP_REPO_ID,
"sourceFolderList": [
ACE_STEP_REPO_FOLDER,
- ACE_STEP_TEXT_ENCODER_FOLDER,
+ text_encoder_folder,
],
"targetFolderList": [None, None],
"fileList": [base_files, tokenizer_files],
@@ -161,63 +308,140 @@ class family_handler:
profile=0,
**kwargs,
):
- from .ace_step.pipeline_ace_step import ACEStepPipeline
-
transformer_weights = None
if isinstance(model_filename, (list, tuple)):
transformer_weights = model_filename[0] if model_filename else None
else:
transformer_weights = model_filename
- transformer_config = _get_model_path(model_def, "ace_step_transformer_config", _ace_step_ckpt_file(ACE_STEP_TRANSFORMER_CONFIG_NAME))
- dcae_weights = _get_model_path(model_def, "ace_step_dcae_weights", _ace_step_ckpt_file(ACE_STEP_DCAE_WEIGHTS_NAME))
- dcae_config = _get_model_path(model_def, "ace_step_dcae_config", _ace_step_ckpt_file(ACE_STEP_DCAE_CONFIG_NAME))
- vocoder_weights = _get_model_path(model_def, "ace_step_vocoder_weights", _ace_step_ckpt_file(ACE_STEP_VOCODER_WEIGHTS_NAME))
- vocoder_config = _get_model_path(model_def, "ace_step_vocoder_config", _ace_step_ckpt_file(ACE_STEP_VOCODER_CONFIG_NAME))
- text_encoder_folder = _get_model_path(model_def, "text_encoder_folder", ACE_STEP_TEXT_ENCODER_FOLDER)
- text_encoder_weights = text_encoder_filename or _get_model_path(
- model_def,
- "ace_step_text_encoder_weights",
- os.path.join(text_encoder_folder, ACE_STEP_TEXT_ENCODER_NAME),
- )
- tokenizer_dir = _get_model_path(
- model_def,
- "ace_step_tokenizer_dir",
- _ckpt_dir(text_encoder_folder),
- )
+ if _is_ace_step15(base_model_type):
+ from .ace_step15.pipeline_ace_step15 import ACEStep15Pipeline
- pipeline = ACEStepPipeline(
- transformer_weights_path=transformer_weights,
- transformer_config_path=transformer_config,
- dcae_weights_path=dcae_weights,
- dcae_config_path=dcae_config,
- vocoder_weights_path=vocoder_weights,
- vocoder_config_path=vocoder_config,
- text_encoder_weights_path=text_encoder_weights,
- text_encoder_tokenizer_dir=tokenizer_dir,
- dtype=dtype or torch.bfloat16,
- )
+ transformer_variant = _get_model_path(model_def, "ace_step15_transformer_variant", "")
+ transformer_config_name = ACE_STEP15_TRANSFORMER_CONFIG_NAME
+ if transformer_variant:
+ transformer_config_name = ACE_STEP15_TRANSFORMER_VARIANTS.get(
+ str(transformer_variant).lower(),
+ transformer_config_name,
+ )
+ transformer_config = _get_model_path(model_def, "ace_step15_transformer_config", _ace_step15_config_path(transformer_config_name))
+ vae_weights = _get_model_path(model_def, "ace_step15_vae_weights", _ace_step15_ckpt_file(ACE_STEP15_VAE_WEIGHTS_NAME))
+ vae_config = _get_model_path(model_def, "ace_step15_vae_config", _ace_step15_config_path(ACE_STEP15_VAE_CONFIG_NAME))
- pipe = {
- "transformer": pipeline.ace_step_transformer,
- "text_encoder": pipeline.text_encoder_model,
- "codec": pipeline.music_dcae,
- }
- if save_quantized and transformer_weights:
- from wgp import get_model_def, save_quantized_model
-
- save_quantized_model(
- pipeline.ace_step_transformer,
- model_type,
- transformer_weights,
- dtype or torch.bfloat16,
- transformer_config,
+ text_encoder_2_folder = _get_model_path(model_def, "ACE_STEP15_TEXT_ENCODER_2_FOLDER", ACE_STEP15_TEXT_ENCODER_2_FOLDER)
+ text_encoder_2_weights = _get_model_path(
+ model_def,
+ "ace_step15_text_encoder_2_weights",
+ fl.locate_file(os.path.join(text_encoder_2_folder, ACE_STEP15_TEXT_ENCODER_2_NAME), error_if_none=False)
+ or os.path.join(text_encoder_2_folder, ACE_STEP15_TEXT_ENCODER_2_NAME),
+ )
+ pre_text_tokenizer_dir = _get_model_path(model_def, "ace_step15_pre_text_tokenizer_dir", _ckpt_dir(text_encoder_2_folder))
+
+ enable_lm = bool(_get_model_path(model_def, "ace_step15_enable_lm", False))
+ lm_folder = _get_model_path(model_def, "text_encoder_folder", ACE_STEP15_LM_FOLDER)
+ lm_weights = text_encoder_filename
+ lm_tokenizer_dir = _get_model_path(model_def, "ace_step15_lm_tokenizer_dir", _ace_step15_lm_ckpt_dir(lm_folder))
+ silence_latent = _get_model_path(model_def, "ace_step15_silence_latent", _ace_step15_ckpt_file(ACE_STEP15_SILENCE_LATENT_NAME))
+
+ pipeline = ACEStep15Pipeline(
+ transformer_weights_path=transformer_weights,
+ transformer_config_path=transformer_config,
+ vae_weights_path=vae_weights,
+ vae_config_path=vae_config,
+ text_encoder_2_weights_path=text_encoder_2_weights,
+ text_encoder_2_tokenizer_dir=pre_text_tokenizer_dir,
+ lm_weights_path=lm_weights,
+ lm_tokenizer_dir=lm_tokenizer_dir,
+ silence_latent_path=silence_latent,
+ enable_lm=enable_lm,
+ dtype=dtype or torch.bfloat16,
)
- return pipeline, pipe
+
+ pipe = {
+ "transformer": pipeline.ace_step_transformer,
+ "text_encoder_2": pipeline.text_encoder_2,
+ "codec": pipeline.audio_vae,
+ }
+ if text_encoder_filename and pipeline.lm_model is not None:
+ pipe["text_encoder"] = pipeline.lm_model
+
+ if save_quantized and transformer_weights:
+ from wgp import save_quantized_model
+
+ save_quantized_model(
+ pipeline.ace_step_transformer,
+ model_type,
+ transformer_weights,
+ dtype or torch.bfloat16,
+ transformer_config,
+ )
+
+ return pipeline, pipe
+ else:
+ from .ace_step.pipeline_ace_step import ACEStepPipeline
+
+ transformer_config = _get_model_path(model_def, "ace_step_transformer_config", _ace_step_ckpt_file(ACE_STEP_TRANSFORMER_CONFIG_NAME))
+ dcae_weights = _get_model_path(model_def, "ace_step_dcae_weights", _ace_step_ckpt_file(ACE_STEP_DCAE_WEIGHTS_NAME))
+ dcae_config = _get_model_path(model_def, "ace_step_dcae_config", _ace_step_ckpt_file(ACE_STEP_DCAE_CONFIG_NAME))
+ vocoder_weights = _get_model_path(model_def, "ace_step_vocoder_weights", _ace_step_ckpt_file(ACE_STEP_VOCODER_WEIGHTS_NAME))
+ vocoder_config = _get_model_path(model_def, "ace_step_vocoder_config", _ace_step_ckpt_file(ACE_STEP_VOCODER_CONFIG_NAME))
+ text_encoder_folder = _get_model_path(model_def, "text_encoder_folder", ACE_STEP_TEXT_ENCODER_FOLDER)
+ text_encoder_weights = text_encoder_filename or _get_model_path(model_def, "ace_step_text_encoder_weights", os.path.join(text_encoder_folder, ACE_STEP_TEXT_ENCODER_NAME))
+ tokenizer_dir = _get_model_path(model_def, "ace_step_tokenizer_dir", _ckpt_dir(text_encoder_folder))
+
+ pipeline = ACEStepPipeline(
+ transformer_weights_path=transformer_weights,
+ transformer_config_path=transformer_config,
+ dcae_weights_path=dcae_weights,
+ dcae_config_path=dcae_config,
+ vocoder_weights_path=vocoder_weights,
+ vocoder_config_path=vocoder_config,
+ text_encoder_weights_path=text_encoder_weights,
+ text_encoder_tokenizer_dir=tokenizer_dir,
+ dtype=dtype or torch.bfloat16,
+ )
+
+ pipe = {
+ "transformer": pipeline.ace_step_transformer,
+ "text_encoder": pipeline.text_encoder_model,
+ "codec": pipeline.music_dcae,
+ }
+ if save_quantized and transformer_weights:
+ from wgp import get_model_def, save_quantized_model
+
+ save_quantized_model(
+ pipeline.ace_step_transformer,
+ model_type,
+ transformer_weights,
+ dtype or torch.bfloat16,
+ transformer_config,
+ )
+ return pipeline, pipe
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
duration_def = model_def.get("duration_slider", {})
+ if _is_ace_step15(base_model_type):
+ ui_defaults.update(
+ {
+ "audio_prompt_type": "",
+ "prompt": "[Verse]\\nNeon rain on the city line\\n"
+ "You hum the tune and I fall in time\\n"
+ "[Chorus]\\nHold me close and keep the time",
+ "alt_prompt": "dreamy synth-pop, shimmering pads, soft vocals",
+ "scheduler_type": "euler",
+ "duration_seconds": duration_def.get("default", 60),
+ "repeat_generation": 1,
+ "video_length": 0,
+ "num_inference_steps": 8,
+ "negative_prompt": "",
+ "temperature": 1.0,
+ "guidance_scale": 1.0,
+ "multi_prompts_gen_type": 2,
+ "audio_scale": 1.0,
+ }
+ )
+ return
ui_defaults.update(
{
"audio_prompt_type": "",
diff --git a/shared/utils/transformers_fast_tokenizer_patch.py b/shared/utils/transformers_fast_tokenizer_patch.py
new file mode 100644
index 0000000..c1f0b8a
--- /dev/null
+++ b/shared/utils/transformers_fast_tokenizer_patch.py
@@ -0,0 +1,318 @@
+import json
+import os
+import pickle
+import sys
+
+
+_PATCH_ALLOWED_PATHS = None
+_ORIG_FAST_INIT = None
+
+
+def _normalize_path(path):
+ if not path:
+ return None
+ try:
+ return os.path.normcase(os.path.abspath(path))
+ except Exception:
+ return None
+
+
+def _path_allowed(path):
+ if not _PATCH_ALLOWED_PATHS:
+ return False
+ norm = _normalize_path(path)
+ if norm is None:
+ return False
+ for allowed in _PATCH_ALLOWED_PATHS:
+ if allowed is None:
+ continue
+ try:
+ if os.path.commonpath([norm, allowed]) == allowed:
+ return True
+ except Exception:
+ if norm.startswith(allowed):
+ return True
+ return False
+
+
+def _load_cached_tokenizer(tokenizer_file, TokenizerFast):
+ if not tokenizer_file:
+ return None
+ return TokenizerFast.from_file(tokenizer_file)
+
+
+def patch_pretrained_tokenizer_fast(allow_paths=None):
+ global _PATCH_ALLOWED_PATHS
+ global _ORIG_FAST_INIT
+ if allow_paths is not None:
+ _PATCH_ALLOWED_PATHS = [_normalize_path(p) for p in allow_paths if p]
+
+ try:
+ import transformers.tokenization_utils_fast as tuf
+ except Exception:
+ return
+
+ cls = tuf.PreTrainedTokenizerFast
+ if getattr(cls, "_wan2gp_fast_init_patched", False):
+ return
+
+ if _ORIG_FAST_INIT is None:
+ _ORIG_FAST_INIT = cls.__init__
+
+ def _patched_init(self, *args, **kwargs):
+ fast_tokenizer_file = kwargs.get("tokenizer_file")
+ from_slow = kwargs.get("from_slow", False)
+ if not fast_tokenizer_file or from_slow or not _path_allowed(fast_tokenizer_file):
+ return _ORIG_FAST_INIT(self, *args, **kwargs)
+
+ try:
+ fast_tokenizer = _load_cached_tokenizer(fast_tokenizer_file, tuf.TokenizerFast)
+ if fast_tokenizer is None:
+ return _ORIG_FAST_INIT(self, *args, **kwargs)
+ kwargs["tokenizer_object"] = fast_tokenizer
+ except Exception:
+ return _ORIG_FAST_INIT(self, *args, **kwargs)
+
+ tokenizer_object = kwargs.pop("tokenizer_object", None)
+ slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
+ fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
+ from_slow = kwargs.pop("from_slow", False)
+ added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})
+ self.add_prefix_space = kwargs.get("add_prefix_space", False)
+
+ if from_slow and slow_tokenizer is None and self.slow_tokenizer_class is None:
+ raise ValueError(
+ "Cannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you "
+ "have sentencepiece installed."
+ )
+
+ if tokenizer_object is not None:
+ fast_tokenizer = tokenizer_object
+ else:
+ fast_tokenizer = tuf.TokenizerFast.from_file(fast_tokenizer_file)
+
+ self._tokenizer = fast_tokenizer
+
+ if slow_tokenizer is not None:
+ kwargs.update(slow_tokenizer.init_kwargs)
+
+ self._decode_use_source_tokenizer = False
+
+ _truncation = self._tokenizer.truncation
+
+ if _truncation is not None:
+ self._tokenizer.enable_truncation(**_truncation)
+ kwargs.setdefault("max_length", _truncation["max_length"])
+ kwargs.setdefault("truncation_side", _truncation["direction"])
+ kwargs.setdefault("stride", _truncation["stride"])
+ kwargs.setdefault("truncation_strategy", _truncation["strategy"])
+ else:
+ self._tokenizer.no_truncation()
+
+ _padding = self._tokenizer.padding
+ if _padding is not None:
+ self._tokenizer.enable_padding(**_padding)
+ kwargs.setdefault("pad_token", _padding["pad_token"])
+ kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
+ kwargs.setdefault("padding_side", _padding["direction"])
+ kwargs.setdefault("max_length", _padding["length"])
+ kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"])
+
+ tuf.PreTrainedTokenizerBase.__init__(self, **kwargs)
+ self._tokenizer.encode_special_tokens = self.split_special_tokens
+
+ added_tokens_decoder_hash = {hash(repr(token)) for token in self.added_tokens_decoder}
+ tokens_to_add = [
+ token
+ for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
+ if hash(repr(token)) not in added_tokens_decoder_hash
+ ]
+ encoder_set = set(self.added_tokens_encoder.keys())
+ for token in tokens_to_add:
+ if isinstance(token, tuf.AddedToken):
+ encoder_set.add(token.content)
+ else:
+ encoder_set.add(str(token))
+ tokens_to_add_set = set(tokens_to_add)
+ tokens_to_add += [
+ token
+ for token in self.all_special_tokens_extended
+ if token not in encoder_set and token not in tokens_to_add_set
+ ]
+
+ if len(tokens_to_add) > 0:
+ special_tokens = set(self.all_special_tokens)
+ tokens = []
+ append = tokens.append
+ for token in tokens_to_add:
+ if isinstance(token, tuf.AddedToken):
+ content = token.content
+ if (not token.special) and (content in special_tokens):
+ token.special = True
+ append(token)
+ else:
+ append(tuf.AddedToken(token, special=(token in special_tokens)))
+ if tokens:
+ self.add_tokens(tokens)
+
+ try:
+ pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
+ if pre_tok_state.get("add_prefix_space", self.add_prefix_space) != self.add_prefix_space:
+ pre_tok_class = getattr(tuf.pre_tokenizers_fast, pre_tok_state.pop("type"))
+ pre_tok_state["add_prefix_space"] = self.add_prefix_space
+ self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
+ except Exception:
+ pass
+
+ cls.__init__ = _patched_init
+ cls._wan2gp_fast_init_patched = True
+
+
+def unpatch_pretrained_tokenizer_fast():
+ global _ORIG_FAST_INIT
+ if _ORIG_FAST_INIT is None:
+ return
+ try:
+ import transformers.tokenization_utils_fast as tuf
+ except Exception:
+ return
+ cls = tuf.PreTrainedTokenizerFast
+ if not getattr(cls, "_wan2gp_fast_init_patched", False):
+ return
+ cls.__init__ = _ORIG_FAST_INIT
+ cls._wan2gp_fast_init_patched = False
+
+
+def _get_transformers_version():
+ try:
+ import transformers as _transformers
+ return getattr(_transformers, "__version__", None)
+ except Exception:
+ return None
+
+
+def _get_tokenizers_version():
+ try:
+ import tokenizers as _tokenizers
+ return getattr(_tokenizers, "__version__", None)
+ except Exception:
+ return None
+
+
+def _collect_tokenizer_files(tokenizer_dir):
+ candidates = [
+ "tokenizer.json",
+ "tokenizer_config.json",
+ "special_tokens_map.json",
+ "added_tokens.json",
+ "vocab.json",
+ "merges.txt",
+ "config.json",
+ "sentencepiece.bpe.model",
+ "tokenizer.model",
+ ]
+ files = []
+ for name in candidates:
+ path = os.path.join(tokenizer_dir, name)
+ if os.path.isfile(path):
+ try:
+ stat = os.stat(path)
+ files.append({"path": name, "mtime": stat.st_mtime, "size": stat.st_size})
+ except OSError:
+ files.append({"path": name, "mtime": None, "size": None})
+ return files
+
+
+def _sanitize_cache_tag(tag):
+ if not tag:
+ return ""
+ safe = "".join(ch if ch.isalnum() or ch in ("-", "_", ".") else "_" for ch in str(tag))
+ return safe.strip("._-")
+
+
+def _cache_paths(tokenizer_dir, cache_tag=None):
+ suffix = _sanitize_cache_tag(cache_tag)
+ if suffix:
+ cache_file = os.path.join(tokenizer_dir, f"tokenizer.wgp.full.{suffix}.pkl")
+ meta_file = os.path.join(tokenizer_dir, f"tokenizer.wgp.full.{suffix}.meta.json")
+ else:
+ cache_file = os.path.join(tokenizer_dir, "tokenizer.wgp.full.pkl")
+ meta_file = os.path.join(tokenizer_dir, "tokenizer.wgp.full.meta.json")
+ return cache_file, meta_file
+
+
+def _read_cache_meta(meta_file):
+ try:
+ with open(meta_file, "r", encoding="utf-8") as handle:
+ return json.load(handle)
+ except Exception:
+ return None
+
+
+def _meta_matches(meta, tokenizer_dir):
+ if not meta:
+ return False
+ if tuple(meta.get("py_version", [])) != tuple(sys.version_info[:3]):
+ return False
+ if meta.get("transformers_version") != _get_transformers_version():
+ return False
+ if meta.get("tokenizers_version") != _get_tokenizers_version():
+ return False
+ expected_files = meta.get("files", [])
+ current_files = _collect_tokenizer_files(tokenizer_dir)
+ if len(expected_files) != len(current_files):
+ return False
+ current_map = {f.get("path"): f for f in current_files}
+ for entry in expected_files:
+ cur = current_map.get(entry.get("path"))
+ if cur is None:
+ return False
+ if entry.get("mtime") != cur.get("mtime") or entry.get("size") != cur.get("size"):
+ return False
+ return True
+
+
+def _load_full_tokenizer_cache(tokenizer_dir, cache_tag=None):
+ cache_file, meta_file = _cache_paths(tokenizer_dir, cache_tag=cache_tag)
+ if not os.path.isfile(cache_file) or not os.path.isfile(meta_file):
+ return None
+ meta = _read_cache_meta(meta_file)
+ if not _meta_matches(meta, tokenizer_dir):
+ return None
+ try:
+ with open(cache_file, "rb") as handle:
+ return pickle.load(handle)
+ except Exception:
+ return None
+
+
+def _save_full_tokenizer_cache(tokenizer_dir, tokenizer, cache_tag=None):
+ cache_file, meta_file = _cache_paths(tokenizer_dir, cache_tag=cache_tag)
+ meta = {
+ "py_version": list(sys.version_info[:3]),
+ "transformers_version": _get_transformers_version(),
+ "tokenizers_version": _get_tokenizers_version(),
+ "files": _collect_tokenizer_files(tokenizer_dir),
+ }
+ try:
+ with open(cache_file, "wb") as handle:
+ pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
+ with open(meta_file, "w", encoding="utf-8") as handle:
+ json.dump(meta, handle)
+ except Exception:
+ pass
+
+
+def load_cached_lm_tokenizer(tokenizer_dir, loader_fn, cache_tag=None):
+ if not tokenizer_dir:
+ return loader_fn()
+ cached = _load_full_tokenizer_cache(tokenizer_dir, cache_tag=cache_tag)
+ if cached is not None:
+ return cached
+ patch_pretrained_tokenizer_fast(allow_paths=[tokenizer_dir])
+ try:
+ tokenizer = loader_fn()
+ finally:
+ unpatch_pretrained_tokenizer_fast()
+ _save_full_tokenizer_cache(tokenizer_dir, tokenizer, cache_tag=cache_tag)
+ return tokenizer
diff --git a/wgp.py b/wgp.py
index cceda56..7ae0430 100644
--- a/wgp.py
+++ b/wgp.py
@@ -720,16 +720,17 @@ def validate_settings(state, model_type, single_prompt, inputs):
if audio_guide == None:
gr.Info("You must provide an Audio Source")
return ret()
- if "B" in audio_prompt_type:
- if audio_guide2 == None:
- gr.Info("You must provide a second Audio Source")
- return ret()
- else:
- audio_guide2 = None
else:
audio_guide = None
+
+
+ if "B" in audio_prompt_type:
+ if audio_guide2 == None:
+ gr.Info("You must provide a second Audio Source")
+ return ret()
+ else:
audio_guide2 = None
-
+
if model_type in ["vace_multitalk_14B"] and ("B" in audio_prompt_type or "X" in audio_prompt_type):
if not "I" in video_prompt_type and not not "V" in video_prompt_type:
gr.Info("To get good results with Multitalk and two people speaking, it is recommended to set a Reference Frame or a Control Video (potentially truncated) that contains the two people one on each side")
@@ -4322,7 +4323,7 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
labels += ["Control Net Weights"]
audio_scale_name = model_def.get("audio_scale_name", "")
- if len(audio_scale_name) > 0:
+ if len(audio_scale_name) > 0 and any_letters(video_audio_prompt_type,"AB"):
values += [configs.get("audio_scale", 1)]
labels += [audio_scale_name]
@@ -9600,6 +9601,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
audio_prompt_type_sources_def = model_def.get("audio_prompt_type_sources", None)
audio_prompt_type_value = ui_get("audio_prompt_type", "A" if any_audio_prompt and audio_prompt_type_sources_def is None else "")
any_multi_speakers = False
+ any_audio_guide2 = False
if any_audio_prompt:
any_single_speaker = not model_def.get("multi_speakers_only", False)
any_multi_speakers = not model_def.get("one_speaker_only", False) and not audio_only
@@ -9628,6 +9630,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
audio_prompt_type_sources_labels = audio_prompt_type_sources_def.get("labels", {})
audio_prompt_type_sources_choices = []
for choice in selection:
+ if "B" in choice: any_audio_guide2 = True
label = audio_prompt_type_sources_labels.get(choice, audio_prompt_type_sources_labels_all.get(choice, choice))
audio_prompt_type_sources_choices.append((label, choice))
if len(audio_prompt_type_sources_choices) == 0:
@@ -9654,7 +9657,6 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
with gr.Row(visible = any_audio_prompt and any_letters(audio_prompt_type_value,"AB") and not image_outputs) as audio_guide_row:
any_audio_guide = any_audio_prompt and not image_outputs
- any_audio_guide2 = any_multi_speakers
audio_guide = gr.Audio(value= ui_defaults.get("audio_guide", None), type="filepath", label= model_def.get("audio_guide_label","Voice to follow"), show_download_button= True, visible= any_audio_prompt and "A" in audio_prompt_type_value )
audio_guide2 = gr.Audio(value= ui_defaults.get("audio_guide2", None), type="filepath", label=model_def.get("audio_guide2_label","Voice to follow #2"), show_download_button= True, visible= any_audio_prompt and "B" in audio_prompt_type_value )
custom_guide_def = model_def.get("custom_guide", None)
@@ -9896,7 +9898,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
control_net_weight = gr.Slider(0.0, 2.0, value=ui_get("control_net_weight"), step=0.01, label=f"{control_net_weight_name} Weight" + ("" if control_net_weight_size<=1 else " #1"), visible=control_net_weight_size >= 1, show_reset_button= False)
control_net_weight2 = gr.Slider(0.0, 2.0, value=ui_get("control_net_weight2"), step=0.01, label=f"{control_net_weight_name} Weight" + ("" if control_net_weight_size<=1 else " #2"), visible=control_net_weight_size >=2, show_reset_button= False)
control_net_weight_alt = gr.Slider(0.0, 2.0, value=ui_get("control_net_weight_alt"), step=0.01, label=control_net_weight_alt_name + " Weight", visible=len(control_net_weight_alt_name) >0, show_reset_button= False)
- audio_scale = gr.Slider(0.0, 2.0, value=ui_get("audio_scale", 1), step=0.01, label=audio_scale_name, visible=audio_scale_visible, show_reset_button= False)
+ audio_scale = gr.Slider(0.0, 1.0, value=ui_get("audio_scale", 1), step=0.01, label=audio_scale_name, visible=audio_scale_visible, show_reset_button= False)
with gr.Row(visible = not (hunyuan_t2v or hunyuan_i2v or no_negative_prompt)) as negative_prompt_row:
negative_prompt = gr.Textbox(label="Negative Prompt (ignored if no Guidance that is if CFG = 1)", value=ui_get("negative_prompt") )
with gr.Column(visible = model_def.get("NAG", False)) as NAG_col: