Skip to content
Python

add cuda graph toolkit & accelerated heartmula

DeepBeepMeepff570ae73d0f
diff --git a/models/TTS/HeartMula/heartcodec/models/flow_matching.py b/models/TTS/HeartMula/heartcodec/models/flow_matching.py
index 72e5551..57d7721 100644
--- a/models/TTS/HeartMula/heartcodec/models/flow_matching.py
+++ b/models/TTS/HeartMula/heartcodec/models/flow_matching.py
@@ -150,7 +150,7 @@ class FlowMatching(nn.Module):
dt = t_span[1] - t_span[0]
noise = x.clone()
sol = []
- for step in tqdm(range(1, len(t_span)), disable=disable_progress):
+ for step in tqdm(range(1, len(t_span)), disable=disable_progress, mininterval=0.33):
if abort_signal and abort_signal():
return None
x[:, 0:incontext_length, :] = (1 - (1 - 1e-6) * t) * noise[
diff --git a/models/TTS/HeartMula/heartmula/cudagraph_hooks.py b/models/TTS/HeartMula/heartmula/cudagraph_hooks.py
new file mode 100644
index 0000000..dbb6498
--- /dev/null
+++ b/models/TTS/HeartMula/heartmula/cudagraph_hooks.py
@@ -0,0 +1,142 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import torch
+
+from shared.llm_engines.cudagraph_kit import AutoRegressiveCudaGraphKit
+
+if TYPE_CHECKING:
+ from .llama_blocks import TransformerDecoder
+ from .modeling_heartmula import HeartMuLa
+
+
+class HeartMuLaCudaGraphHooks:
+ def __init__(self, model: "HeartMuLa") -> None:
+ self.model = model
+ self._enabled = False
+ self._kit: AutoRegressiveCudaGraphKit | None = None
+ self._backbone_tokens = 0
+ self._decoder_tokens = 0
+ self._backbone_flash_graph = False
+
+ def set_lm_decoder_engine(self, lm_decoder_engine: str | None) -> None:
+ engine = str(lm_decoder_engine or "legacy").strip().lower()
+ self._enabled = engine == "cg"
+ if not self._enabled:
+ self.release()
+
+ @staticmethod
+ def _collect_attention_modules(transformer: "TransformerDecoder"):
+ return [layer.attn for layer in transformer.layers if hasattr(layer, "attn")]
+
+ @staticmethod
+ def _can_use_flash_graph(attn_modules: list[object]) -> bool:
+ if not attn_modules:
+ return False
+ for attn in attn_modules:
+ if not bool(getattr(attn, "allow_flash2_kvcache", False)):
+ return False
+ if not bool(getattr(attn, "_flash_kv_ready", False)):
+ return False
+ return True
+
+ def prepare(self, *, max_backbone_tokens: int, max_decoder_tokens: int) -> None:
+ self.release()
+ if not self._enabled:
+ return
+ model_device = next(self.model.parameters()).device
+ if model_device.type != "cuda":
+ return
+ if not self.model.backbone.caches_are_enabled() or not self.model.decoder[0].caches_are_enabled():
+ raise RuntimeError("HeartMuLa caches must be setup before CUDA graph preparation.")
+ if max_backbone_tokens <= 0 or max_decoder_tokens <= 0:
+ raise ValueError("CUDA graph token limits must be > 0.")
+ kit = AutoRegressiveCudaGraphKit("heartmula")
+ backbone_attn = self._collect_attention_modules(self.model.backbone)
+ decoder_attn = self._collect_attention_modules(self.model.decoder[0])
+ self._backbone_flash_graph = self._can_use_flash_graph(backbone_attn)
+ backbone_graph_mode = "flash_kvcache" if self._backbone_flash_graph else "index"
+ self._backbone_tokens = int(
+ kit.attach_attention_modules(backbone_attn, max_backbone_tokens, graph_mode=backbone_graph_mode)
+ )
+ self._decoder_tokens = int(
+ kit.attach_attention_modules(decoder_attn, max_decoder_tokens, graph_mode="index")
+ )
+ self._kit = kit
+ self._prime_decode_kernels()
+
+ def release(self) -> None:
+ if self._kit is not None:
+ self._kit.release()
+ self._kit = None
+ self._backbone_tokens = 0
+ self._decoder_tokens = 0
+ self._backbone_flash_graph = False
+
+ def _active(self) -> bool:
+ return self._kit is not None and self._backbone_tokens > 0 and self._decoder_tokens > 0
+
+ def is_active(self) -> bool:
+ return self._active()
+
+ def _backbone_decode_step(self, hidden_states: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
+ if self._backbone_flash_graph:
+ return self.model.backbone(hidden_states, input_pos=input_pos, mask=None)
+ mask = self.model.backbone_causal_mask[input_pos, : self._backbone_tokens]
+ return self.model.backbone(hidden_states, input_pos=input_pos, mask=mask)
+
+ def _decoder_decode_step(self, hidden_states: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
+ mask = self.model.decoder_causal_mask[input_pos, : self._decoder_tokens]
+ return self.model.decoder[0](self.model.projection(hidden_states), input_pos=input_pos, mask=mask)
+
+ def _prime_decode_kernels(self) -> None:
+ if not self._active():
+ return
+ kv_cache = self.model.backbone.layers[0].attn.kv_cache
+ if kv_cache is None:
+ return
+ batch_size = int(kv_cache.k_cache.shape[0])
+ hidden_dim = int(self.model.projection.in_features)
+ model_device = kv_cache.k_cache.device
+ model_dtype = next(self.model.parameters()).dtype
+ hidden = torch.zeros((batch_size, 1, hidden_dim), device=model_device, dtype=model_dtype)
+ pos = torch.zeros((batch_size, 1), device=model_device, dtype=torch.long)
+ with torch.no_grad():
+ _ = self._backbone_decode_step(hidden, pos)
+ self.model.backbone.reset_caches()
+ _ = self._decoder_decode_step(hidden, pos)
+ self.model.decoder[0].reset_caches()
+
+ def run_backbone_decode(self, hidden_states: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
+ if not self._active():
+ raise RuntimeError("Backbone CUDA graph decode called while CUDA graph is inactive.")
+ token_pos = int(input_pos.reshape(-1)[0].item())
+ if token_pos < 0 or token_pos >= self._backbone_tokens:
+ raise RuntimeError(
+ f"Backbone decode position {token_pos} exceeds CUDA graph cache capacity {self._backbone_tokens}."
+ )
+ try:
+ return self._kit.run("backbone_decode", self._backbone_decode_step, hidden_states, input_pos)
+ except Exception as exc:
+ self.release()
+ raise RuntimeError(f"HeartMuLa backbone CUDA graph decode failed: {exc}") from exc
+
+ def run_decoder(self, hidden_states: torch.Tensor, input_pos: torch.Tensor) -> torch.Tensor:
+ if not self._active():
+ raise RuntimeError("Decoder CUDA graph decode called while CUDA graph is inactive.")
+ last_output = None
+ try:
+ for token_idx in range(hidden_states.shape[1]):
+ token_pos = input_pos[:, token_idx : token_idx + 1]
+ absolute_pos = int(token_pos.reshape(-1)[0].item())
+ if absolute_pos < 0 or absolute_pos >= self._decoder_tokens:
+ raise RuntimeError(
+ f"Decoder decode position {absolute_pos} exceeds CUDA graph cache capacity {self._decoder_tokens}."
+ )
+ token_hidden = hidden_states[:, token_idx : token_idx + 1]
+ last_output = self._kit.run("decoder_decode", self._decoder_decode_step, token_hidden, token_pos)
+ except Exception as exc:
+ self.release()
+ raise RuntimeError(f"HeartMuLa decoder CUDA graph decode failed: {exc}") from exc
+ return last_output
diff --git a/models/TTS/HeartMula/heartmula/llama_blocks.py b/models/TTS/HeartMula/heartmula/llama_blocks.py
index 1a06da5..afe567d 100644
--- a/models/TTS/HeartMula/heartmula/llama_blocks.py
+++ b/models/TTS/HeartMula/heartmula/llama_blocks.py
@@ -358,6 +358,7 @@ class MultiHeadAttention(nn.Module):
is_causal: bool = True,
attn_dropout: float = 0.0,
cache_expand_step: int = 200,
+ allow_flash2_kvcache: bool = False,
) -> None:
super().__init__()
if num_heads % num_kv_heads != 0:
@@ -378,6 +379,7 @@ class MultiHeadAttention(nn.Module):
self.head_dim = head_dim
self.max_seq_len = max_seq_len
self.is_causal = is_causal
+ self.allow_flash2_kvcache = allow_flash2_kvcache
self.kv_cache: Optional[ExpandableKVCache] = None
self.q_proj = q_proj
@@ -503,15 +505,15 @@ class MultiHeadAttention(nn.Module):
self._flash_device = device
self._flash_dtype = dtype
flash_ok = (
- device.type == "cuda"
+ self.allow_flash2_kvcache
+ and device.type == "cuda"
and dtype in (torch.float16, torch.bfloat16)
and self.head_dim <= 256
- ) and False #disabled flash
- kv_ready = self.kv_cache is not None and self.cache_enabled
- self._flash_kv_ready = (
- flash_ok and self._flash_attn is not None and kv_ready
+ and self._flash_attn is not None
)
- self._flash_full_ready = flash_ok and self._flash_attn_func is not None
+ kv_ready = self.kv_cache is not None and self.cache_enabled
+ self._flash_kv_ready = flash_ok and kv_ready
+ self._flash_full_ready = False
def reset_flash(self) -> None:
self._flash_kv_ready = False
@@ -529,9 +531,13 @@ class MultiHeadAttention(nn.Module):
) -> torch.Tensor:
bsz, s_x, _ = x.shape
q = self.q_proj(x).view(bsz, s_x, self.num_heads, self.head_dim)
+ graph_state = None
+ graph_flash_kvcache = False
if self.kv_cache is not None and self.cache_enabled:
self.kv_cache.ensure_device(q.device, q.dtype)
- if mask is not None and s_x == 1:
+ graph_state = getattr(self.kv_cache, "graph_state", None)
+ graph_flash_kvcache = bool(getattr(graph_state, "flash_kvcache", False))
+ if mask is not None and s_x == 1 and graph_state is None:
mask = None
y = x if y is None else y
s_y = y.shape[1]
@@ -544,36 +550,46 @@ class MultiHeadAttention(nn.Module):
k= v = None
k, v = self._expand_kv(kv_list, self.num_heads // self.num_kv_heads)
- if s_x == 1:
- use_flash_kv = self._flash_kv_ready and mask is None
- if use_flash_kv:
- global _FLASH_ATTN_NOTICE_SHOWN
- if not _FLASH_ATTN_NOTICE_SHOWN:
- print("\nHeartMuLa attention: using flash_attn_with_kvcache.")
- _FLASH_ATTN_NOTICE_SHOWN = True
- self.kv_cache.ensure_capacity(self.kv_cache.size + s_y)
+ use_flash_kv = self._flash_kv_ready and mask is None and (graph_state is None or graph_flash_kvcache)
+ if graph_flash_kvcache and (input_pos is None or input_pos.numel() != bsz):
+ use_flash_kv = False
+ if use_flash_kv:
+ self.kv_cache.ensure_capacity(self.kv_cache.size + s_y)
+ if graph_flash_kvcache:
+ cache_seqlens = input_pos.reshape(-1).to(device=q.device, dtype=torch.int32)
+ else:
cache_seqlens = torch.full(
(bsz,),
self.kv_cache.size,
device=q.device,
dtype=torch.int32,
)
- attn_out = self._flash_attn(
- q=q,
- k_cache=self.kv_cache.k_cache,
- v_cache=self.kv_cache.v_cache,
- k=k,
- v=v,
- cache_seqlens=cache_seqlens,
- cache_leftpad=None,
- causal=True,
- )
+ attn_out = self._flash_attn(
+ q=q,
+ k_cache=self.kv_cache.k_cache,
+ v_cache=self.kv_cache.v_cache,
+ k=k,
+ v=v,
+ cache_seqlens=cache_seqlens,
+ cache_leftpad=None,
+ causal=self.is_causal,
+ )
+ if not graph_flash_kvcache:
self.kv_cache.advance(s_y)
- else:
- if self.kv_cache is not None and self.cache_enabled:
- k_cache, v_cache = self.kv_cache.update(k, v)
- k = k_cache[:, : self.kv_cache.size]
- v = v_cache[:, : self.kv_cache.size]
+ elif s_x == 1:
+ if (
+ graph_state is not None
+ and not graph_flash_kvcache
+ and self.kv_cache is not None
+ and self.cache_enabled
+ and input_pos is not None
+ and mask is not None
+ ):
+ k_cache = self.kv_cache.k_cache[:bsz]
+ v_cache = self.kv_cache.v_cache[:bsz]
+ graph_state.write(k_cache, v_cache, k, v, input_pos)
+ k = k_cache
+ v = v_cache
attn_out = self._sdpa(
q,
k,
@@ -581,17 +597,6 @@ class MultiHeadAttention(nn.Module):
mask=mask,
is_causal=False,
)
- else:
- use_flash_full = self._flash_full_ready and mask is None
- if use_flash_full:
- if self.kv_cache is not None and self.cache_enabled:
- self.kv_cache.update(k, v)
- attn_out = self._flash_full(
- q,
- k,
- v,
- is_causal=self.is_causal,
- )
else:
if self.kv_cache is not None and self.cache_enabled:
k_cache, v_cache = self.kv_cache.update(k, v)
@@ -602,8 +607,20 @@ class MultiHeadAttention(nn.Module):
k,
v,
mask=mask,
- is_causal=self.is_causal if mask is None else False,
+ is_causal=False,
)
+ else:
+ if self.kv_cache is not None and self.cache_enabled:
+ k_cache, v_cache = self.kv_cache.update(k, v)
+ k = k_cache[:, : self.kv_cache.size]
+ v = v_cache[:, : self.kv_cache.size]
+ attn_out = self._sdpa(
+ q,
+ k,
+ v,
+ mask=mask,
+ is_causal=self.is_causal if mask is None else False,
+ )
q = None
k = None
@@ -752,6 +769,7 @@ def build_llama_decoder(
intermediate_dim: Optional[int] = None,
norm_eps: float = 1e-5,
scale_factor: int = 32,
+ allow_flash2_kvcache: bool = False,
) -> TransformerDecoder:
head_dim = embed_dim // num_heads
num_kv_heads = num_kv_heads if num_kv_heads else num_heads
@@ -775,6 +793,7 @@ def build_llama_decoder(
pos_embeddings=rope,
max_seq_len=max_seq_len,
attn_dropout=attn_dropout,
+ allow_flash2_kvcache=allow_flash2_kvcache,
)
hidden_dim = (
intermediate_dim
diff --git a/models/TTS/HeartMula/heartmula/modeling_heartmula.py b/models/TTS/HeartMula/heartmula/modeling_heartmula.py
index 0764206..091656f 100644
--- a/models/TTS/HeartMula/heartmula/modeling_heartmula.py
+++ b/models/TTS/HeartMula/heartmula/modeling_heartmula.py
@@ -3,6 +3,7 @@ import torch.nn as nn
from transformers.modeling_utils import PreTrainedModel
from .configuration_heartmula import HeartMuLaConfig
+from .cudagraph_hooks import HeartMuLaCudaGraphHooks
from .llama_blocks import Llama3ScaledRoPE, TransformerDecoder, build_llama_decoder
@@ -123,6 +124,7 @@ class HeartMuLa(PreTrainedModel):
self.config = config
self._interrupt_check = None
+ self._cuda_graph_hooks = HeartMuLaCudaGraphHooks(self)
self.backbone, backbone_dim = _prepare_transformer(
FLAVORS[config.backbone_flavor]()
@@ -130,6 +132,9 @@ class HeartMuLa(PreTrainedModel):
self.decoder, decoder_dim = _prepare_transformer(
FLAVORS[config.decoder_flavor]()
)
+ for layer in self.backbone.layers:
+ if hasattr(layer, "attn"):
+ layer.attn.allow_flash2_kvcache = True
self.text_embeddings = nn.Embedding(config.text_vocab_size, backbone_dim)
self.audio_embeddings = nn.Embedding(
config.audio_vocab_size * config.audio_num_codebooks, backbone_dim
@@ -148,6 +153,20 @@ class HeartMuLa(PreTrainedModel):
self.muq_linear = nn.Linear(config.muq_dim, backbone_dim)
self.post_init()
+ def set_lm_decoder_engine(self, lm_decoder_engine: str | None) -> None:
+ self._cuda_graph_hooks.set_lm_decoder_engine(lm_decoder_engine)
+
+ def prepare_decode_cuda_graph(
+ self, *, max_backbone_tokens: int, max_decoder_tokens: int
+ ) -> None:
+ self._cuda_graph_hooks.prepare(
+ max_backbone_tokens=max_backbone_tokens,
+ max_decoder_tokens=max_decoder_tokens,
+ )
+
+ def release_decode_cuda_graph(self) -> None:
+ self._cuda_graph_hooks.release()
+
def setup_caches(self, max_batch_size: int):
dtype = next(self.parameters()).dtype
device = next(self.parameters()).device
@@ -210,10 +229,10 @@ class HeartMuLa(PreTrainedModel):
) -> torch.Tensor:
if self._check_interrupt():
return None
- b, _, _ = tokens.size()
+ b, seq_len, _ = tokens.size()
+ graph_active = self._cuda_graph_hooks.is_active()
assert self.backbone.caches_are_enabled(), "backbone caches are not enabled"
- curr_backbone_mask = None
uncond_mask = None
if cfg_scale > 1.0 and b > 1:
@@ -241,7 +260,8 @@ class HeartMuLa(PreTrainedModel):
)
batch_indices = torch.arange(h.shape[0], device=h.device)
h[batch_indices, starts] = continuous_segments
- h = self.backbone(h, input_pos=input_pos, mask=curr_backbone_mask)
+ use_backbone_graph = graph_active and seq_len == 1 and continuous_segments is None
+ h = self._cuda_graph_hooks.run_backbone_decode(h, input_pos) if use_backbone_graph else self.backbone(h, input_pos=input_pos, mask=None)
if self._check_interrupt():
return None
last_h = h[:, -1, :]
@@ -271,10 +291,7 @@ class HeartMuLa(PreTrainedModel):
for i in range(1, self.config.audio_num_codebooks):
if self._check_interrupt():
return None
- curr_decoder_mask = None
- decoder_h = self.decoder[0](
- self.projection(curr_h), input_pos=curr_pos, mask=curr_decoder_mask
- )
+ decoder_h = self._cuda_graph_hooks.run_decoder(curr_h, curr_pos) if graph_active else self.decoder[0](self.projection(curr_h), input_pos=curr_pos, mask=None)
if self._check_interrupt():
return None
head_weight = self.audio_head[i - 1]
@@ -304,6 +321,7 @@ class HeartMuLa(PreTrainedModel):
def release_caches(self):
# Drop KV cache tensors to free memory between generations.
+ self.release_decode_cuda_graph()
for module in self.backbone.modules():
if hasattr(module, "kv_cache"):
module.kv_cache = None
diff --git a/models/TTS/HeartMula/pipeline.py b/models/TTS/HeartMula/pipeline.py
index 6113d67..8782184 100644
--- a/models/TTS/HeartMula/pipeline.py
+++ b/models/TTS/HeartMula/pipeline.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
import json
import random
+import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
@@ -101,6 +102,8 @@ class HeartMuLaPipeline:
codec_guidance_scale: float = 1.25,
codec_version: str = "",
VAE_dtype = torch.float32,
+ lm_decoder_engine=None,
+
):
self.device = torch.device("cpu")
self.mula_device = self.device
@@ -116,6 +119,7 @@ class HeartMuLaPipeline:
self.codec_version = codec_version
self.heartmula_weights_path = heartmula_weights_path
self.VAE_dtype = VAE_dtype
+ self.lm_decoder_engine = str(lm_decoder_engine or "legacy").strip().lower()
self.ckpt_root = Path(ckpt_root) if ckpt_root is not None else Path(
fl.get_download_location()
@@ -128,6 +132,8 @@ class HeartMuLaPipeline:
self._muq_dim = 512
self._load_models()
+ engine = "cg" if self.lm_decoder_engine == "cg" else "legacy"
+ print(f"[HeartMuLa] Decoder Engine={engine} flash2={'on' if getattr(self.mula.backbone.layers[0].attn, '_flash_attn', None) is not None else 'off'}")
def _load_models(self):
(
@@ -162,8 +168,8 @@ class HeartMuLaPipeline:
delattr(self.mula, "decoder")
self.mula.decoder = [decoder]
- if hasattr(self.mula, "_interrupt_check"):
- self.mula._interrupt_check = self._abort_requested
+ self.mula._interrupt_check = self._abort_requested
+ self.mula.set_lm_decoder_engine(self.lm_decoder_engine)
self.model = self.mula
self.mula.eval()
first_param = next(self.mula.parameters(), None)
@@ -338,6 +344,13 @@ class HeartMuLaPipeline:
self.mula.prepare_flash(mula_device, flash_dtype)
if self._abort_requested():
return None
+ frame_duration_ms = 80 # 80 ms per audio token frame.
+ max_audio_frames = max_audio_length_ms // frame_duration_ms
+ prompt_len = int(prompt_tokens.shape[1])
+ self.mula.prepare_decode_cuda_graph(
+ max_backbone_tokens=prompt_len + max_audio_frames,
+ max_decoder_tokens=int(getattr(self.mula.config, "audio_num_codebooks", 8)),
+ )
try:
curr_token = self.mula.generate_frame(
tokens=prompt_tokens,
@@ -371,9 +384,9 @@ class HeartMuLaPipeline:
padded_token_mask[..., -1] = False
return padded_token, padded_token_mask
- frame_duration_ms = 80 # 80 ms per audio token frame.
- max_audio_frames = max_audio_length_ms // frame_duration_ms
progress_total_seconds = max(1, max_audio_length_ms // 1000)
+ progress_refresh_interval_s = 0.33
+ last_progress_callback_ts = 0.0
if callback is not None:
callback(
step_idx=-1,
@@ -381,9 +394,10 @@ class HeartMuLaPipeline:
denoising_extra=f"0s/{progress_total_seconds}s",
progress_unit="seconds",
)
+ last_progress_callback_ts = time.monotonic()
if not early_stop_now:
- for i in tqdm(range(max_audio_frames)):
+ for i in tqdm(range(max_audio_frames), mininterval=progress_refresh_interval_s):
if self._abort_requested():
return None
curr_token, curr_token_mask = _pad_audio_token(curr_token)
@@ -404,7 +418,7 @@ class HeartMuLaPipeline:
frames.append(curr_token[0:1,])
if self._early_stop_requested():
break
- if i % 10 == 0 and callback is not None:
+ if callback is not None and (time.monotonic() - last_progress_callback_ts) >= progress_refresh_interval_s:
generated_ms = len(frames) * frame_duration_ms
generated_seconds_int = min(
progress_total_seconds,
@@ -418,11 +432,13 @@ class HeartMuLaPipeline:
),
progress_unit="seconds",
)
+ last_progress_callback_ts = time.monotonic()
frames = torch.stack(frames).permute(1, 2, 0).squeeze(0)
return {"frames": frames}
finally:
# Drop KV cache tensors as soon as we're done with generation.
try:
+ self.mula.release_decode_cuda_graph()
self.mula.move_causal_masks(torch.device("cpu"))
self.mula.release_caches()
torch.cuda.empty_cache()
@@ -538,6 +554,7 @@ class HeartMuLaPipeline:
def release(self) -> None:
if hasattr(self, "mula") and self.mula is not None:
+ self.mula.release_decode_cuda_graph()
self.mula = None
if hasattr(self, "model"):
self.model = None
diff --git a/models/TTS/ace_step_handler.py b/models/TTS/ace_step_handler.py
index 7557469..e43f4ab 100644
--- a/models/TTS/ace_step_handler.py
+++ b/models/TTS/ace_step_handler.py
@@ -300,6 +300,7 @@ class family_handler:
"audio_scale_name": "Source Audio Strength",
"audio_prompt_choices": True,
"enabled_audio_lora": True,
+ "lm_engines": ["vllm"],
"prompt_class": "Lyrics",
"prompt_description": "Lyrics / Prompt (Write [Instrumental] for Instrumental Generation only)",
"audio_prompt_type_sources": {
diff --git a/models/TTS/heartmula_handler.py b/models/TTS/heartmula_handler.py
index 2961ffc..e39215b 100644
--- a/models/TTS/heartmula_handler.py
+++ b/models/TTS/heartmula_handler.py
@@ -26,6 +26,7 @@ def _get_heartmula_model_def():
"placeholder": "piano,happy,wedding",
"lines": 2,
},
+ "lm_engines": ["cg"],
"text_prompt_enhancer_instructions": HEARTMULA_LYRIC_PROMPT,
"prompt_enhancer_button_label": "Compose Lyrics",
"duration_slider": {
@@ -118,6 +119,7 @@ class family_handler:
submodel_no_list=None,
text_encoder_filename=None,
profile=0,
+ lm_decoder_engine="legacy",
**kwargs,
):
from .HeartMula.pipeline import HeartMuLaPipeline
@@ -148,7 +150,10 @@ class family_handler:
codec_steps=model_def.get("heartmula_codec_steps", 10),
codec_guidance_scale=model_def.get("heartmula_codec_guidance_scale", 1.25),
codec_version=model_def.get("heartmula_codec_version", ""),
+ lm_decoder_engine=lm_decoder_engine,
)
+ if lm_decoder_engine=="cg":
+ pipeline.mula._budget = 0
pipeline.mula.decoder[0].layers._compile_me = False
pipeline.mula.backbone.layers._compile_me = False
diff --git a/plugins/wan2gp-configuration/plugin.py b/plugins/wan2gp-configuration/plugin.py
index d071e76..0f962df 100644
--- a/plugins/wan2gp-configuration/plugin.py
+++ b/plugins/wan2gp-configuration/plugin.py
@@ -44,7 +44,6 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.request_global("generate_dropdown_model_list")
self.request_global("get_unique_id")
self.request_global("reset_prompt_enhancer")
- self.request_global("resolve_lm_decoder_engine")
self.request_global("apply_int8_kernel_setting")
self.request_component("header")
@@ -156,11 +155,12 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.lm_decoder_engine_choice = gr.Dropdown(
choices=[
("Auto", ""),
- ("PyTorch (slow, compatible)", "legacy"),
- ("vllm (up to x10 faster, requires Triton & Flash Attention 2 and must be implemented in corresponding model)", "vllm"),
+ ("PyTorch: slow, compatible", "legacy"),
+ ("Cuda Graph: up to x6 faster, whole LM will be loaded in VRAM", "cg"),
+ ("vllm: up to x10 faster, whole LM will be loaded in VRAM, requires Triton & Flash Attention 2", "vllm"),
],
value=self.server_config.get("lm_decoder_engine", ""),
- label="Language Models Decoder Engine",
+ label="Language Models Decoder Engine (when available for a model)",
)
self.VAE_precision_choice = gr.Dropdown(choices=[("16-bit (faster, less VRAM)", "16"), ("32-bit (slower, better for sliding window)", "32")], value=self.server_config.get("vae_precision", "16"), label="VAE Encoding/Decoding Precision")
self.compile_choice = gr.Dropdown(choices=[("On (up to 20% faster, requires Triton)", "transformer"), ("Off", "")], value=self.compile, label="Compile Transformer Model (slight speed again, but first generation is slower and potential compatibility issues with some GPUs/Models)", interactive=not self.args.lock_config)
@@ -443,7 +443,6 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.set_global("compile", new_server_config["compile"])
self.set_global("text_encoder_quantization", new_server_config["text_encoder_quantization"])
self.set_global("lm_decoder_engine", new_server_config["lm_decoder_engine"])
- self.set_global("lm_decoder_engine_obtained", self.resolve_lm_decoder_engine(new_server_config["lm_decoder_engine"]))
self.set_global("vae_config", new_server_config["vae_config"])
self.set_global("boost", new_server_config["boost"])
self.set_global("enable_int8_kernels", new_server_config["enable_int8_kernels"])
diff --git a/shared/llm_engines/cudagraph_kit.py b/shared/llm_engines/cudagraph_kit.py
new file mode 100644
index 0000000..f7127f0
--- /dev/null
+++ b/shared/llm_engines/cudagraph_kit.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Callable, Iterable
+
+import torch
+
+
+@dataclass
+class GraphKVIndexWriter:
+ """Writes decode K/V values at the absolute token position provided by input_pos."""
+
+ def write(self, k_cache: torch.Tensor, v_cache: torch.Tensor, k_val: torch.Tensor, v_val: torch.Tensor, input_pos: torch.Tensor) -> None:
+ index = input_pos.reshape(-1)[:1]
+ if index.dtype != torch.long:
+ index = index.to(dtype=torch.long)
+ if index.device != k_cache.device:
+ index = index.to(device=k_cache.device)
+ k_cache[: k_val.shape[0]].index_copy_(1, index, k_val)
+ v_cache[: v_val.shape[0]].index_copy_(1, index, v_val)
+
+
+@dataclass
+class GraphKVFlashState:
+ """Marks a cache as using flash_attn_with_kvcache-compatible graph decode."""
+
+ flash_kvcache: bool = True
+
+
+class CUDAGraphRunner:
+ """Captures and replays a fixed-shape CUDA callable."""
+
+ def __init__(self, name: str, fn: Callable[..., object]) -> None:
+ self._name = name
+ self._fn = fn
+ self._graph: torch.cuda.CUDAGraph | None = None
+ self._static_inputs: list[torch.Tensor] = []
+ self._output: object = None
+
+ def _capture(self, *inputs: torch.Tensor) -> object:
+ if not inputs:
+ raise ValueError(f"[{self._name}] CUDAGraphRunner requires at least one tensor input.")
+ for tensor in inputs:
+ if not torch.is_tensor(tensor):
+ raise TypeError(f"[{self._name}] CUDAGraphRunner accepts tensor inputs only.")
+ if tensor.device.type != "cuda":
+ raise ValueError(f"[{self._name}] CUDAGraphRunner requires CUDA tensors.")
+ self._static_inputs = [tensor.detach().clone() for tensor in inputs]
+ self._graph = torch.cuda.CUDAGraph()
+ try:
+ with torch.cuda.graph(self._graph):
+ self._output = self._fn(*self._static_inputs)
+ # The capture pass records kernels but does not populate outputs for immediate use.
+ # Replay once so the first caller receives valid results.
+ self._graph.replay()
+ except Exception:
+ self.release()
+ raise
+ return self._output
+
+ def _copy_inputs(self, *inputs: torch.Tensor) -> None:
+ if len(inputs) != len(self._static_inputs):
+ raise ValueError(f"[{self._name}] Expected {len(self._static_inputs)} inputs, got {len(inputs)}.")
+ for static_tensor, tensor in zip(self._static_inputs, inputs):
+ if tensor.shape != static_tensor.shape or tensor.dtype != static_tensor.dtype or tensor.device != static_tensor.device:
+ raise ValueError(
+ f"[{self._name}] Static shape mismatch: expected {tuple(static_tensor.shape)} {static_tensor.dtype} on {static_tensor.device}, "
+ f"got {tuple(tensor.shape)} {tensor.dtype} on {tensor.device}."
+ )
+ static_tensor.copy_(tensor)
+
+ def run(self, *inputs: torch.Tensor) -> object:
+ if self._graph is None:
+ return self._capture(*inputs)
+ self._copy_inputs(*inputs)
+ self._graph.replay()
+ return self._output
+
+ def release(self) -> None:
+ self._graph = None
+ self._static_inputs = []
+ self._output = None
+
+
+class AutoRegressiveCudaGraphKit:
+ """Reusable helper to attach graph-safe KV writers and replay decode callables."""
+
+ def __init__(self, name: str) -> None:
+ self._name = name
+ self._runners: dict[str, CUDAGraphRunner] = {}
+ self._attached_caches: list[object] = []
+ self._attached_cache_ids: set[int] = set()
+
+ def attach_attention_modules(self, attention_modules: Iterable[object], max_tokens: int, graph_mode: str = "index") -> int:
+ if max_tokens <= 0:
+ raise ValueError("max_tokens must be > 0.")
+ if graph_mode not in ("index", "flash_kvcache"):
+ raise ValueError(f"Unsupported graph_mode '{graph_mode}'.")
+ final_capacity = 0
+ for module in attention_modules:
+ kv_cache = getattr(module, "kv_cache", None)
+ if kv_cache is None:
+ raise RuntimeError("KV cache must be initialized before CUDA graph attachment.")
+ kv_cache.ensure_capacity(max_tokens)
+ final_capacity = max(final_capacity, int(kv_cache.capacity))
+ cache_id = id(kv_cache)
+ if cache_id not in self._attached_cache_ids:
+ if graph_mode == "flash_kvcache":
+ kv_cache.graph_state = GraphKVFlashState()
+ else:
+ kv_cache.graph_state = GraphKVIndexWriter()
+ self._attached_cache_ids.add(cache_id)
+ self._attached_caches.append(kv_cache)
+ return final_capacity
+
+ def run(self, runner_name: str, fn: Callable[..., object], *inputs: torch.Tensor) -> object:
+ runner = self._runners.get(runner_name)
+ if runner is None:
+ runner = CUDAGraphRunner(f"{self._name}:{runner_name}", fn)
+ self._runners[runner_name] = runner
+ return runner.run(*inputs)
+
+ def release(self) -> None:
+ for runner in self._runners.values():
+ runner.release()
+ self._runners.clear()
+ for kv_cache in self._attached_caches:
+ if hasattr(kv_cache, "graph_state"):
+ kv_cache.graph_state = None
+ self._attached_caches.clear()
+ self._attached_cache_ids.clear()
diff --git a/shared/llm_engines/nanovllm/layers/rotary_embedding.py b/shared/llm_engines/nanovllm/layers/rotary_embedding.py
index 3227623..da2afc1 100644
--- a/shared/llm_engines/nanovllm/layers/rotary_embedding.py
+++ b/shared/llm_engines/nanovllm/layers/rotary_embedding.py
@@ -13,7 +13,7 @@ def apply_rotary_emb(
y2 = x2 * cos + x1 * sin
return torch.cat((y1, y2), dim=-1).to(x.dtype)
-@lru_cache(1)
+@lru_cache(2)
def _build_cache(device: torch.device | str | None, base, rotary_dim, max_position_embeddings ) -> torch.Tensor:
inv_freq = 1.0 / (
base ** (torch.arange(0, rotary_dim, 2, dtype=torch.float32, device=device) / rotary_dim)
diff --git a/shared/llm_engines/nanovllm/models/__init__.py b/shared/llm_engines/nanovllm/models/__init__.py
index 67d5754..fbf0f03 100644
--- a/shared/llm_engines/nanovllm/models/__init__.py
+++ b/shared/llm_engines/nanovllm/models/__init__.py
@@ -1,3 +1,4 @@
from .qwen3 import Qwen3ForCausalLM
+from .llama32 import Llama32ForCausalLM
-__all__ = ["Qwen3ForCausalLM"]
+__all__ = ["Qwen3ForCausalLM", "Llama32ForCausalLM"]
diff --git a/shared/llm_engines/nanovllm/vllm_support.py b/shared/llm_engines/nanovllm/vllm_support.py
index 7434544..1b95229 100644
--- a/shared/llm_engines/nanovllm/vllm_support.py
+++ b/shared/llm_engines/nanovllm/vllm_support.py
@@ -57,32 +57,37 @@ def probe_vllm_runtime(force=False):
return result
-def resolve_lm_decoder_engine(requested_engine):
+def resolve_lm_decoder_engine(requested_engine, engines_available = []):
requested_engine = str(requested_engine or "").strip().lower()
probe_result = probe_vllm_runtime()
supported = bool(probe_result.get("supported", False))
+ cg_available = "cg" in engines_available
+ vllm_available= "vllm" in engines_available
+ default_engine = "cg" if cg_available else "legacy"
if requested_engine == "vllm":
if supported:
- return "vllm"
- global _WARNED_REQUESTED_VLLM_UNAVAILABLE
- if not _WARNED_REQUESTED_VLLM_UNAVAILABLE:
- checks = probe_result.get("checks", {})
- reasons = []
- if isinstance(checks, dict):
- for check_name, check_data in checks.items():
- if isinstance(check_data, dict) and not check_data.get("ok", False):
- msg = str(check_data.get("message", "failed")).replace("\n", " ").strip()
- if len(msg) > 220:
- msg = msg[:220] + "..."
- reasons.append(f"{check_name}={msg}")
- reason_text = "; ".join(reasons) if len(reasons) > 0 else "unknown reason"
- print(f"[LM] Requested decoder engine 'vllm' is unavailable at startup ({reason_text}).")
- _WARNED_REQUESTED_VLLM_UNAVAILABLE = True
- return "legacy"
+ if vllm_available: return "vllm"
+ requested_engine = default_engine
+ else:
+ global _WARNED_REQUESTED_VLLM_UNAVAILABLE
+ if not _WARNED_REQUESTED_VLLM_UNAVAILABLE:
+ checks = probe_result.get("checks", {})
+ reasons = []
+ if isinstance(checks, dict):
+ for check_name, check_data in checks.items():
+ if isinstance(check_data, dict) and not check_data.get("ok", False):
+ msg = str(check_data.get("message", "failed")).replace("\n", " ").strip()
+ if len(msg) > 220:
+ msg = msg[:220] + "..."
+ reasons.append(f"{check_name}={msg}")
+ reason_text = "; ".join(reasons) if len(reasons) > 0 else "unknown reason"
+ print(f"[LM] Requested decoder engine 'vllm' is unavailable at startup ({reason_text}).")
+ _WARNED_REQUESTED_VLLM_UNAVAILABLE = True
+ return default_engine
if requested_engine == "":
- return "vllm" if supported else "legacy"
- if requested_engine == "legacy":
- return "legacy"
+ return "vllm" if supported and vllm_available else default_engine
+ if requested_engine in ("legacy", "cg"):
+ return requested_engine
print(f"[LM] Unknown decoder engine '{requested_engine}', falling back to 'legacy'.")
return "legacy"
diff --git a/wgp.py b/wgp.py
index 5635c93..3cc3acc 100644
--- a/wgp.py
+++ b/wgp.py
@@ -103,7 +103,6 @@ CUSTOM_SETTINGS_MAX = 6
CUSTOM_SETTINGS_PER_ROW = 2
CUSTOM_SETTING_TYPES = {"int", "float", "text"}
lm_decoder_engine = ""
-lm_decoder_engine_obtained = "legacy"
enable_int8_kernels = 0
# All media attachment keys for queue save/load
ATTACHMENT_KEYS = ["image_start", "image_end", "image_refs", "image_guide", "image_mask",
@@ -2433,7 +2432,6 @@ def _normalize_output_paths(config):
_normalize_profile_defaults(server_config)
_normalize_output_paths(server_config)
lm_decoder_engine = server_config.get("lm_decoder_engine", "")
-lm_decoder_engine_obtained = resolve_lm_decoder_engine(lm_decoder_engine)
# Deprecated models
for path in ["wan2.1_Vace_1.3B_preview_bf16.safetensors", "sky_reels2_diffusion_forcing_1.3B_bf16.safetensors","sky_reels2_diffusion_forcing_720p_14B_bf16.safetensors",
@@ -3573,11 +3571,9 @@ def setup_prompt_enhancer(pipe, kwargs):
def load_models(model_type, override_profile = -1, output_type="video", **model_kwargs):
- global transformer_type, loaded_profile, lm_decoder_engine_obtained
+ global transformer_type, loaded_profile
base_model_type = get_base_model_type(model_type)
model_def = get_model_def(model_type)
- requested_lm_decoder_engine = model_kwargs.pop("lm_decoder_engine", lm_decoder_engine)
- lm_decoder_engine_obtained = resolve_lm_decoder_engine(requested_lm_decoder_engine)
save_quantized = args.save_quantized and model_def != None
model_filename = get_model_filename(model_type=model_type, quantization= "" if save_quantized else transformer_quantization, dtype_policy = transformer_dtype_policy)
if "URLs2" in model_def:
@@ -3662,6 +3658,7 @@ def load_models(model_type, override_profile = -1, output_type="video", **model_
profile = compute_profile(override_profile, output_type)
+ lm_decoder_engine_obtained = resolve_lm_decoder_engine(lm_decoder_engine, model_def.get("lm_engines", []) )
torch.set_default_device('cpu')
wan_model, pipe = model_type_handler.load_model(
local_model_file_list, model_type, base_model_type, model_def, quantizeTransformer = quantizeTransformer, text_encoder_quantization = text_encoder_quantization,