Skip to content
Python

added cudagraph support for kugel audio

DeepBeepMeep1b2d65e4aca2
diff --git a/models/TTS/kugelaudio/models/cudagraph_hooks.py b/models/TTS/kugelaudio/models/cudagraph_hooks.py
new file mode 100644
index 0000000..973b4de
--- /dev/null
+++ b/models/TTS/kugelaudio/models/cudagraph_hooks.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import torch
+from transformers.cache_utils import StaticCache
+
+from shared.llm_engines.cudagraph_kit import AutoRegressiveCudaGraphKit
+
+if TYPE_CHECKING:
+ from .kugelaudio_inference import KugelAudioForConditionalGenerationInference
+
+
+class KugelAudioCudaGraphHooks:
+ def __init__(self, model: "KugelAudioForConditionalGenerationInference") -> None:
+ self.model = model
+ self._enabled = False
+ self._kit: AutoRegressiveCudaGraphKit | None = None
+ self._cache: StaticCache | None = None
+ self._max_batch_size = 0
+ self._max_cache_tokens = 0
+ self._last_prepare_reused = False
+ self._decode_cache_position: torch.Tensor | None = None
+
+ 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()
+
+ def prepare(self, *, max_batch_size: int, max_cache_tokens: int) -> None:
+ self._last_prepare_reused = False
+ if not self._enabled:
+ return
+ if max_batch_size <= 0 or max_cache_tokens <= 0:
+ raise ValueError("KugelAudio CUDA graph capacities must be > 0.")
+ model_device = next(self.model.parameters()).device
+ if model_device.type != "cuda":
+ return
+ if (
+ self._cache is not None
+ and self._kit is not None
+ and self._max_batch_size >= int(max_batch_size)
+ and self._max_cache_tokens >= int(max_cache_tokens)
+ ):
+ self._last_prepare_reused = True
+ self._cache.reset()
+ if self._decode_cache_position is None or self._decode_cache_position.device != model_device:
+ self._decode_cache_position = torch.zeros(1, device=model_device, dtype=torch.long)
+ return
+ self.release()
+ model_dtype = next(self.model.parameters()).dtype
+ self._cache = StaticCache(
+ config=self.model.config.decoder_config,
+ max_batch_size=int(max_batch_size),
+ max_cache_len=int(max_cache_tokens),
+ device=model_device,
+ dtype=model_dtype,
+ )
+ self._decode_cache_position = torch.zeros(1, device=model_device, dtype=torch.long)
+ self._kit = AutoRegressiveCudaGraphKit("kugelaudio")
+ self._max_batch_size = int(max_batch_size)
+ self._max_cache_tokens = int(max_cache_tokens)
+
+ def release(self) -> None:
+ if self._kit is not None:
+ self._kit.release()
+ self._kit = None
+ self._cache = None
+ self._decode_cache_position = None
+ self._max_batch_size = 0
+ self._max_cache_tokens = 0
+ self._last_prepare_reused = False
+
+ def is_active(self) -> bool:
+ return self._kit is not None and self._cache is not None and self._max_cache_tokens > 0
+
+ def is_enabled(self) -> bool:
+ return bool(self._enabled)
+
+ def last_prepare_reused(self) -> bool:
+ return bool(self._last_prepare_reused)
+
+ def has_capacity(self, token_position: int) -> bool:
+ return int(token_position) < self._max_cache_tokens
+
+ def _check_batch_size(self, batch_size: int) -> None:
+ if int(batch_size) > self._max_batch_size:
+ raise RuntimeError(
+ f"KugelAudio CUDA graph batch size {int(batch_size)} exceeds prepared capacity {self._max_batch_size}."
+ )
+
+ def prefill(self, inputs_embeds: torch.Tensor):
+ if not self.is_active():
+ raise RuntimeError("KugelAudio CUDA graph prefill called while CUDA graph is inactive.")
+ self._check_batch_size(int(inputs_embeds.shape[0]))
+ self._cache.reset()
+ prompt_len = int(inputs_embeds.shape[1])
+ if prompt_len <= 0:
+ raise RuntimeError("KugelAudio CUDA graph prefill requires at least one prompt token.")
+ if prompt_len > self._max_cache_tokens:
+ raise RuntimeError(
+ f"KugelAudio prompt length {prompt_len} exceeds CUDA graph cache capacity {self._max_cache_tokens}."
+ )
+ cache_position = torch.arange(prompt_len, device=inputs_embeds.device, dtype=torch.long)
+ try:
+ return self.model(
+ inputs_embeds=inputs_embeds,
+ past_key_values=self._cache,
+ use_cache=True,
+ return_dict=True,
+ cache_position=cache_position,
+ )
+ except Exception as exc:
+ self.release()
+ raise RuntimeError(f"KugelAudio CUDA graph prefill failed: {exc}") from exc
+
+ def _decode_step(self, token_embeds: torch.Tensor, cache_position: torch.Tensor):
+ outputs = self.model(
+ inputs_embeds=token_embeds,
+ past_key_values=self._cache,
+ use_cache=True,
+ return_dict=True,
+ cache_position=cache_position,
+ )
+ return outputs.logits, outputs.last_hidden_state
+
+ def run_decode(self, token_embeds: torch.Tensor, token_position: int) -> tuple[torch.Tensor, torch.Tensor]:
+ if not self.is_active():
+ raise RuntimeError("KugelAudio CUDA graph decode called while CUDA graph is inactive.")
+ self._check_batch_size(int(token_embeds.shape[0]))
+ if int(token_embeds.shape[1]) != 1:
+ raise RuntimeError(
+ f"KugelAudio CUDA graph decode expects a single token, got seq_len={int(token_embeds.shape[1])}."
+ )
+ absolute_pos = int(token_position)
+ if absolute_pos < 0 or absolute_pos >= self._max_cache_tokens:
+ raise RuntimeError(
+ f"KugelAudio decode position {absolute_pos} exceeds CUDA graph cache capacity {self._max_cache_tokens}."
+ )
+ if self._decode_cache_position is None or self._decode_cache_position.device != token_embeds.device:
+ self._decode_cache_position = torch.empty(1, device=token_embeds.device, dtype=torch.long)
+ cache_position = self._decode_cache_position.fill_(absolute_pos)
+ try:
+ return self._kit.run("lm_decode", self._decode_step, token_embeds, cache_position)
+ except Exception as exc:
+ self.release()
+ raise RuntimeError(f"KugelAudio CUDA graph decode failed: {exc}") from exc
diff --git a/models/TTS/kugelaudio/models/kugelaudio_inference.py b/models/TTS/kugelaudio/models/kugelaudio_inference.py
index 6d59536..05b02f5 100644
--- a/models/TTS/kugelaudio/models/kugelaudio_inference.py
+++ b/models/TTS/kugelaudio/models/kugelaudio_inference.py
@@ -4,13 +4,14 @@ This is the open-source inference implementation without optimizations.
Based on the original VibeVoice model architecture.
"""
+import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn as nn
from tqdm import tqdm
-from transformers.cache_utils import DynamicCache
+from transformers.cache_utils import DynamicCache, StaticCache
from transformers.generation import (
GenerationConfig,
GenerationMixin,
@@ -25,6 +26,7 @@ from transformers.utils import logging
from ..configs import KugelAudioConfig
from ..schedule.dpm_solver import DPMSolverMultistepScheduler
+from .cudagraph_hooks import KugelAudioCudaGraphHooks
from .diffusion_head import KugelAudioDiffusionHead
from .kugelaudio_model import KugelAudioModel, KugelAudioPreTrainedModel
from .tokenizer import (
@@ -97,6 +99,7 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
def __init__(self, config):
super().__init__(config)
self.model = KugelAudioModel(config)
+ self._cuda_graph_hooks = KugelAudioCudaGraphHooks(self)
self.lm_head = nn.Linear(
config.decoder_config.hidden_size,
config.decoder_config.vocab_size,
@@ -154,6 +157,15 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
num_steps or self.config.diffusion_head_config.ddpm_num_inference_steps
)
+ 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_batch_size: int, max_cache_tokens: int) -> None:
+ self._cuda_graph_hooks.prepare(max_batch_size=max_batch_size, max_cache_tokens=max_cache_tokens)
+
+ def release_decode_cuda_graph(self) -> None:
+ self._cuda_graph_hooks.release()
+
def _process_speech_inputs(
self,
speech_tensors: Optional[torch.Tensor],
@@ -237,8 +249,7 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
# Combine embeddings and index by speech_masks
combined_embed = acoustic_embed + semantic_embed
- # Move speech_masks to CPU for indexing (matches working implementation)
- speech_embeds = combined_embed[speech_masks.cpu()]
+ speech_embeds = combined_embed[speech_masks.to(device=combined_embed.device, dtype=torch.bool)]
return acoustic_features, speech_embeds
@@ -327,28 +338,21 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
speech = self.model.noise_scheduler.step(eps, t, speech).prev_sample
return speech
- # With CFG - batched forward pass
- combined_condition = torch.cat([condition, neg_condition], dim=0).to(
- self.model.prediction_head.device
- )
- speech = torch.randn(combined_condition.shape[0], self.config.acoustic_vae_dim).to(
- combined_condition
- )
+ # With CFG - run guidance on one latent batch (N), not duplicated scheduler states (2N).
+ combined_condition = torch.cat([condition, neg_condition], dim=0).to(self.model.prediction_head.device)
+ batch = int(condition.shape[0])
+ speech = torch.randn(batch, self.config.acoustic_vae_dim).to(combined_condition)
for t in self.model.noise_scheduler.timesteps:
if abort_check is not None and abort_check():
return None
- half = speech[: len(speech) // 2]
- combined = torch.cat([half, half], dim=0)
- eps = self.model.prediction_head(
- combined, t.repeat(combined.shape[0]).to(combined), condition=combined_condition
- )
- cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)
- half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
- eps = torch.cat([half_eps, half_eps], dim=0)
- speech = self.model.noise_scheduler.step(eps, t, speech).prev_sample
+ combined = torch.cat([speech, speech], dim=0)
+ eps = self.model.prediction_head(combined, t.repeat(combined.shape[0]).to(combined), condition=combined_condition)
+ cond_eps, uncond_eps = torch.split(eps, batch, dim=0)
+ guided_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)
+ speech = self.model.noise_scheduler.step(guided_eps, t, speech).prev_sample
- return speech[: len(speech) // 2]
+ return speech
@torch.no_grad()
def encode_voice_prompt(
@@ -401,6 +405,7 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
early_stop_check=None,
callback=None,
progress_interval: int = 10,
+ release_decode_graph_on_exit: bool = True,
**kwargs,
) -> KugelAudioGenerationOutput:
"""Generate speech from text.
@@ -457,12 +462,21 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
semantic_cache = KugelAudioTokenizerStreamingCache()
# Initialize sequences and attention masks
- current_ids = text_ids
- attention_mask = torch.ones_like(current_ids)
+ input_embedding_layer = self.model.get_input_embeddings()
+ prompt_ids = text_ids
+ generated_tokens: list[torch.Tensor] = []
+ positive_seq_len = int(prompt_ids.shape[1])
+ attention_mask = torch.ones_like(prompt_ids)
# For CFG, create negative prompt (just speech_start token)
- negative_ids = torch.full((batch_size, 1), speech_start_id, dtype=torch.long, device=device)
- negative_attention_mask = torch.ones_like(negative_ids)
+ max_cache_tokens = int(prompt_ids.shape[1]) + max(1, int(max_new_tokens))
+ embed_dim = int(input_embedding_layer.weight.shape[1])
+ negative_ids = torch.full((batch_size, max_cache_tokens), speech_start_id, dtype=torch.long, device=device)
+ negative_attention_mask = torch.zeros((batch_size, max_cache_tokens), dtype=attention_mask.dtype, device=device)
+ negative_attention_mask[:, 0] = 1
+ negative_inputs_embeds = torch.empty((batch_size, max_cache_tokens, embed_dim), device=device, dtype=dtype)
+ negative_inputs_embeds[:, :1, :] = input_embedding_layer(negative_ids[:, :1])
+ negative_seq_len = 1
# Storage for generated audio and tracking
audio_chunks = [[] for _ in range(batch_size)]
@@ -474,7 +488,7 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
tail_exhausted = torch.zeros(batch_size, dtype=torch.bool, device=device)
# Get initial embeddings
- inputs_embeds = self.model.get_input_embeddings()(current_ids)
+ inputs_embeds = input_embedding_layer(prompt_ids)
# Process voice/speech input if provided
if speech_tensors is not None or voice_cache is not None:
@@ -522,8 +536,6 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
)
inputs_embeds[speech_input_mask] = speech_embeds
- negative_inputs_embeds = self.model.get_input_embeddings()(negative_ids)
-
# Setup logits processor to constrain to valid tokens
valid_tokens = [speech_start_id, speech_end_id, speech_diffusion_id, eos_token_id]
token_constraint = KugelAudioTokenConstraintProcessor(valid_tokens, device=device)
@@ -531,16 +543,46 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
# Initialize KV caches
past_key_values = None
negative_past_key_values = None
+ self.prepare_decode_cuda_graph(max_batch_size=int(batch_size), max_cache_tokens=max_cache_tokens)
+ graph_active = self._cuda_graph_hooks.is_active()
+ use_fast_kvcache = False
+ static_past_key_values = None
+ static_decode_cache_position = None
+ lm_attn_backend = str(
+ getattr(getattr(self.model.language_model, "config", None), "_attn_implementation", None)
+ or getattr(getattr(self.model.language_model, "config", None), "attn_implementation", None)
+ or ""
+ ).strip().lower()
+ if not graph_active and device.type == "cuda" and lm_attn_backend != "flash_attention_2":
+ static_past_key_values = StaticCache(
+ config=self.config.decoder_config,
+ max_batch_size=int(batch_size),
+ max_cache_len=int(max_cache_tokens),
+ device=device,
+ dtype=dtype,
+ )
+ static_decode_cache_position = torch.empty(1, device=device, dtype=torch.long)
+ use_fast_kvcache = True
+ if self._cuda_graph_hooks.is_enabled():
+ prepare_status = "reused" if self._cuda_graph_hooks.last_prepare_reused() else "new"
+ state = "active" if graph_active else "inactive"
+ if state == "inactive" or prepare_status == "new":
+ print(f"[KugelAudio][cg] decode graph {state} ({prepare_status})")
+ if use_fast_kvcache:
+ print("[KugelAudio][kv] fast static cache active (legacy)")
# Progress bar
progress_iter = (
- tqdm(range(max_new_tokens), desc="KugelAudio", leave=False)
+ tqdm(range(max_new_tokens), desc="KugelAudio", leave=False, mininterval=0.33)
if show_progress
else range(max_new_tokens)
)
total_steps = max(1, int(max_new_tokens))
progress_interval = max(1, int(progress_interval or 1))
+ progress_refresh_interval_s = 0.33
+ last_progress_callback_ts = 0.0
+ eos_token_tensor = torch.tensor(eos_token_id, device=device)
if callback is not None:
callback(
step_idx=-1,
@@ -548,9 +590,12 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
denoising_extra=f"0/{total_steps} tokens",
progress_unit="tokens",
)
+ last_progress_callback_ts = time.monotonic()
for step in progress_iter:
if abort_check is not None and abort_check():
+ if release_decode_graph_on_exit:
+ self.release_decode_cuda_graph()
return None
if early_stop_check is not None and early_stop_check():
break
@@ -558,27 +603,55 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
break
# Forward pass for positive (main) model
- if past_key_values is None:
- outputs = self(
- inputs_embeds=inputs_embeds,
- attention_mask=attention_mask,
- use_cache=True,
- return_dict=True,
+ if step == 0:
+ outputs = (
+ self._cuda_graph_hooks.prefill(inputs_embeds)
+ if graph_active
+ else self(
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask if not use_fast_kvcache else None,
+ past_key_values=static_past_key_values,
+ use_cache=True,
+ return_dict=True,
+ cache_position=torch.arange(positive_seq_len, device=device, dtype=torch.long)
+ if use_fast_kvcache
+ else None,
+ )
)
+ if not graph_active and not use_fast_kvcache:
+ past_key_values = outputs.past_key_values
+ logits = outputs.logits[:, -1, :]
+ positive_last_hidden = outputs.last_hidden_state
else:
- outputs = self(
- inputs_embeds=inputs_embeds[:, -1:],
- attention_mask=attention_mask,
- past_key_values=past_key_values,
- use_cache=True,
- return_dict=True,
- )
-
- past_key_values = outputs.past_key_values
- logits = outputs.logits[:, -1, :]
+ if graph_active:
+ decode_position = int(positive_seq_len - 1)
+ if not self._cuda_graph_hooks.has_capacity(decode_position):
+ # Static cache replay cannot compact KV; stop when max duration/token budget is reached.
+ break
+ step_logits, positive_last_hidden = self._cuda_graph_hooks.run_decode(
+ inputs_embeds[:, -1:], decode_position
+ )
+ logits = step_logits[:, -1, :]
+ else:
+ outputs = self(
+ inputs_embeds=inputs_embeds[:, -1:],
+ attention_mask=attention_mask if not use_fast_kvcache else None,
+ past_key_values=past_key_values if not use_fast_kvcache else static_past_key_values,
+ use_cache=True,
+ return_dict=True,
+ cache_position=(
+ static_decode_cache_position.fill_(positive_seq_len - 1)
+ if use_fast_kvcache
+ else None
+ ),
+ )
+ if not use_fast_kvcache:
+ past_key_values = outputs.past_key_values
+ logits = outputs.logits[:, -1, :]
+ positive_last_hidden = outputs.last_hidden_state
# Apply token constraint
- logits = token_constraint(current_ids, logits)
+ logits = token_constraint(prompt_ids, logits)
# If tail mode is active, prevent EOS/speech_end for those samples.
@@ -618,19 +691,19 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
# Force finished samples to output EOS
force_eos_mask = finished
- next_tokens = torch.where(
- force_eos_mask, torch.tensor(eos_token_id, device=device), next_tokens
- )
+ next_tokens = torch.where(force_eos_mask, eos_token_tensor, next_tokens)
# Update sequences
- current_ids = torch.cat([current_ids, next_tokens.unsqueeze(-1)], dim=-1)
- attention_mask = torch.cat(
- [
- attention_mask,
- torch.ones((batch_size, 1), device=device, dtype=attention_mask.dtype),
- ],
- dim=-1,
- )
+ generated_tokens.append(next_tokens.unsqueeze(-1))
+ positive_seq_len += 1
+ if not graph_active and not use_fast_kvcache:
+ attention_mask = torch.cat(
+ [
+ attention_mask,
+ torch.ones((batch_size, 1), device=device, dtype=attention_mask.dtype),
+ ],
+ dim=-1,
+ )
# Check for EOS/speech_end tokens (optionally extend with tail tokens)
eos_mask = (next_tokens == eos_token_id) & ~finished
@@ -674,20 +747,20 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
speech_start_indices = speech_start_mask.nonzero(as_tuple=False).squeeze(-1)
if speech_start_indices.dim() == 0:
speech_start_indices = speech_start_indices.unsqueeze(0)
+ key_caches, value_caches = _get_cache_tensors(negative_past_key_values)
for sample_idx in speech_start_indices.tolist():
- negative_attention_mask[sample_idx, :] = 0
- negative_attention_mask[sample_idx, -1] = 1
+ negative_attention_mask[sample_idx, :negative_seq_len] = 0
+ negative_attention_mask[sample_idx, negative_seq_len - 1] = 1
- key_caches, value_caches = _get_cache_tensors(negative_past_key_values)
for k_cache, v_cache in zip(key_caches, value_caches):
k_cache[sample_idx, :, -1, :] = k_cache[sample_idx, :, 0, :].clone()
v_cache[sample_idx, :, -1, :] = v_cache[sample_idx, :, 0, :].clone()
- negative_ids[sample_idx, -1] = speech_start_id
+ negative_ids[sample_idx, negative_seq_len - 1] = speech_start_id
# Prepare next input embeddings
- next_inputs_embeds = self.model.get_input_embeddings()(next_tokens).unsqueeze(1)
+ next_inputs_embeds = input_embedding_layer(next_tokens).unsqueeze(1)
# Handle diffusion tokens - generate speech
diffusion_mask = (next_tokens == speech_diffusion_id) & ~finished
@@ -700,15 +773,15 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
if cfg_scale != 1.0:
if negative_past_key_values is None:
neg_outputs = self(
- inputs_embeds=negative_inputs_embeds,
- attention_mask=negative_attention_mask,
+ inputs_embeds=negative_inputs_embeds[:, :negative_seq_len],
+ attention_mask=negative_attention_mask[:, :negative_seq_len],
use_cache=True,
return_dict=True,
)
else:
neg_outputs = self(
- inputs_embeds=negative_inputs_embeds[:, -1:],
- attention_mask=negative_attention_mask,
+ inputs_embeds=negative_inputs_embeds[:, negative_seq_len - 1 : negative_seq_len],
+ attention_mask=negative_attention_mask[:, :negative_seq_len],
past_key_values=negative_past_key_values,
use_cache=True,
return_dict=True,
@@ -727,26 +800,26 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
key_caches, value_caches = _get_cache_tensors(negative_past_key_values)
for sample_idx in non_diffusion_indices.tolist():
start_idx = correct_cnt[sample_idx].item()
- seq_len = negative_attention_mask.shape[1]
+ seq_len = int(negative_seq_len)
if start_idx + 1 < seq_len - 1:
- negative_attention_mask[sample_idx, start_idx + 1 :] = (
- negative_attention_mask[sample_idx, start_idx:-1].clone()
+ negative_attention_mask[sample_idx, start_idx + 1 : seq_len] = (
+ negative_attention_mask[sample_idx, start_idx : seq_len - 1].clone()
)
negative_attention_mask[sample_idx, start_idx] = 0
for k_cache, v_cache in zip(key_caches, value_caches):
- if start_idx + 1 < k_cache.shape[2] - 1:
- k_cache[sample_idx, :, start_idx + 1 :, :] = k_cache[
- sample_idx, :, start_idx:-1, :
+ if start_idx + 1 < seq_len - 1:
+ k_cache[sample_idx, :, start_idx + 1 : seq_len, :] = k_cache[
+ sample_idx, :, start_idx : seq_len - 1, :
].clone()
- v_cache[sample_idx, :, start_idx + 1 :, :] = v_cache[
- sample_idx, :, start_idx:-1, :
+ v_cache[sample_idx, :, start_idx + 1 : seq_len, :] = v_cache[
+ sample_idx, :, start_idx : seq_len - 1, :
].clone()
- if start_idx + 1 < negative_ids.shape[1] - 1:
- negative_ids[sample_idx, start_idx + 1 :] = negative_ids[
- sample_idx, start_idx:-1
+ if start_idx + 1 < seq_len - 1:
+ negative_ids[sample_idx, start_idx + 1 : seq_len] = negative_ids[
+ sample_idx, start_idx : seq_len - 1
].clone()
correct_cnt[non_diffusion_indices] += 1
@@ -761,13 +834,15 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
)
# Get conditioning from last hidden state
- condition = outputs.last_hidden_state[diffusion_indices, -1, :]
+ condition = positive_last_hidden[diffusion_indices, -1, :]
# Sample speech latents using diffusion
speech_latents = self.sample_speech_tokens(
condition, neg_condition, cfg_scale, abort_check=abort_check
)
if speech_latents is None:
+ if release_decode_graph_on_exit:
+ self.release_decode_cuda_graph()
return None
# Unscale latents
@@ -786,9 +861,9 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
# Store audio chunks
for i, idx in enumerate(diffusion_indices.tolist()):
if not finished[idx]:
- audio_chunks[idx].append(audio[i].cpu())
+ audio_chunks[idx].append(audio[i].detach().clone())
- # Encode audio to semantic features with streaming cache
+ # Keep both acoustic + semantic conditioning for diffusion tokens.
semantic_output = self.semantic_tokenizer.encode(
audio,
cache=semantic_cache,
@@ -796,38 +871,42 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
use_cache=True,
)
semantic_features = semantic_output.mean
-
- # Compute embeddings for next step
acoustic_embed = self.acoustic_connector(speech_latents.unsqueeze(1))
semantic_embed = self.semantic_connector(semantic_features)
- diffusion_embeds = (acoustic_embed + semantic_embed).squeeze(1)
# Update embeddings for diffusion samples
- next_inputs_embeds[diffusion_indices] = diffusion_embeds.unsqueeze(1)
+ next_inputs_embeds[diffusion_indices] = acoustic_embed + semantic_embed
- # Update embeddings for next iteration
- inputs_embeds = torch.cat([inputs_embeds, next_inputs_embeds], dim=1)
+ # Positive decode only consumes the latest token after prefill.
+ inputs_embeds = next_inputs_embeds
# Update negative model
- negative_inputs_embeds = torch.cat([negative_inputs_embeds, next_inputs_embeds], dim=1)
- negative_attention_mask = torch.cat(
- [
- negative_attention_mask,
- torch.ones((batch_size, 1), device=device, dtype=negative_attention_mask.dtype),
- ],
- dim=-1,
- )
- negative_ids = torch.cat([negative_ids, next_tokens.unsqueeze(-1)], dim=-1)
-
- if callback is not None and (step % progress_interval == 0 or step + 1 == total_steps):
- callback(
- step_idx=step,
- override_num_inference_steps=total_steps,
- denoising_extra=f"{step + 1}/{total_steps} tokens",
- progress_unit="tokens",
+ if cfg_scale != 1.0:
+ if negative_seq_len >= max_cache_tokens:
+ break
+ negative_inputs_embeds[:, negative_seq_len : negative_seq_len + 1, :] = next_inputs_embeds
+ negative_attention_mask[:, negative_seq_len] = 1
+ negative_ids[:, negative_seq_len] = next_tokens
+ negative_seq_len += 1
+
+ if callback is not None:
+ now = time.monotonic()
+ should_refresh = (
+ step + 1 == total_steps
+ or (step % progress_interval == 0 and (now - last_progress_callback_ts) >= progress_refresh_interval_s)
)
+ if should_refresh:
+ callback(
+ step_idx=step,
+ override_num_inference_steps=total_steps,
+ denoising_extra=f"{step + 1}/{total_steps} tokens",
+ progress_unit="tokens",
+ )
+ last_progress_callback_ts = now
if abort_check is not None and abort_check():
+ if release_decode_graph_on_exit:
+ self.release_decode_cuda_graph()
return None
# Concatenate audio chunks with normalization
@@ -841,14 +920,18 @@ class KugelAudioForConditionalGenerationInference(KugelAudioPreTrainedModel, Gen
concatenated = concatenated * (0.95 / max_val)
# Apply watermark to all generated audio
# concatenated = self._apply_watermark(concatenated, sample_rate=24000)
- speech_outputs.append(concatenated)
+ speech_outputs.append(concatenated.cpu())
else:
speech_outputs.append(None)
- return KugelAudioGenerationOutput(
- sequences=current_ids,
- speech_outputs=speech_outputs,
- )
+ if generated_tokens:
+ sequences = torch.cat([prompt_ids] + generated_tokens, dim=-1)
+ else:
+ sequences = prompt_ids
+ output = KugelAudioGenerationOutput(sequences=sequences, speech_outputs=speech_outputs)
+ if release_decode_graph_on_exit:
+ self.release_decode_cuda_graph()
+ return output
def _apply_watermark(self, audio: torch.Tensor, sample_rate: int = 24000) -> torch.Tensor:
"""Apply imperceptible watermark to generated audio.
diff --git a/models/TTS/kugelaudio/pipeline.py b/models/TTS/kugelaudio/pipeline.py
index 654fed9..d67e42c 100644
--- a/models/TTS/kugelaudio/pipeline.py
+++ b/models/TTS/kugelaudio/pipeline.py
@@ -63,9 +63,11 @@ class KugelAudioPipeline:
*,
ckpt_root: Optional[Path] = None,
device: Optional[torch.device] = None,
+ lm_decoder_engine: Optional[str] = None,
) -> None:
self.device = device or torch.device("cpu")
self.ckpt_root = Path(ckpt_root) if ckpt_root is not None else Path(fl.get_download_location())
+ self.lm_decoder_engine = str(lm_decoder_engine or "legacy").strip().lower()
self._interrupt = False
self._early_stop = False
@@ -75,6 +77,9 @@ class KugelAudioPipeline:
self.sample_rate = getattr(self.processor.audio_processor, "sampling_rate", 24000)
self.generation_config = self._load_generation_config(assets["generation_config_path"])
+ engine = "cg" if self.lm_decoder_engine == "cg" else "legacy"
+ attn = getattr(self.model, "_attn_implementation", "sdpa")
+ print(f"[KugelAudio] LM engine='{engine}', attention='{attn}'")
def _abort_requested(self) -> bool:
return bool(self._interrupt)
@@ -134,6 +139,12 @@ class KugelAudioPipeline:
with open(config_path, "r", encoding="utf-8") as handle:
config_dict = json.load(handle)
config = KugelAudioConfig(**config_dict)
+ attn_implementation = "sdpa"
+ if hasattr(config, "decoder_config") and config.decoder_config is not None:
+ config.decoder_config._attn_implementation = attn_implementation
+ config.decoder_config.attn_implementation = attn_implementation
+ config._attn_implementation = attn_implementation
+ config.attn_implementation = attn_implementation
with init_empty_weights():
model = KugelAudioForConditionalGenerationInference(config)
offload.load_model_data(
@@ -142,7 +153,22 @@ class KugelAudioPipeline:
default_dtype=None,
writable_tensors=False,
)
+ model.set_lm_decoder_engine(self.lm_decoder_engine)
model.eval()
+ language_model = getattr(getattr(model, "model", None), "language_model", None)
+ if language_model is not None and hasattr(language_model, "config"):
+ language_model.config._attn_implementation = attn_implementation
+ language_model.config.attn_implementation = attn_implementation
+ if hasattr(model, "config"):
+ model.config._attn_implementation = attn_implementation
+ model.config.attn_implementation = attn_implementation
+ if hasattr(model.config, "decoder_config") and model.config.decoder_config is not None:
+ model.config.decoder_config._attn_implementation = attn_implementation
+ model.config.decoder_config.attn_implementation = attn_implementation
+ if hasattr(model, "generation_config") and model.generation_config is not None:
+ model.generation_config._attn_implementation = attn_implementation
+ model.generation_config.attn_implementation = attn_implementation
+ model._attn_implementation = attn_implementation
if KUGELAUDIO_DEBUG:
try:
print(
@@ -316,6 +342,9 @@ class KugelAudioPipeline:
):
self._interrupt = False
self._early_stop = False
+ def _finish(value):
+ self.model.release_decode_cuda_graph()
+ return value
text = _read_text_or_file(input_prompt, "Prompt")
if not text.strip():
@@ -457,6 +486,7 @@ class KugelAudioPipeline:
abort_check=self._abort_requested,
early_stop_check=self._early_stop_requested,
callback=active_callback,
+ release_decode_graph_on_exit=False,
)
if outputs is None:
return None
@@ -530,7 +560,7 @@ class KugelAudioPipeline:
completed_lines = 0
for speaker_id, line_text, append_pause_after in expanded:
if self._abort_requested():
- return None
+ return _finish(None)
duration_left = None
if total_duration_seconds is not None:
duration_left = max(0.0, total_duration_seconds - elapsed_seconds)
@@ -552,8 +582,8 @@ class KugelAudioPipeline:
if segment is None:
if self._early_stop_requested() and audio_segments:
audio = torch.cat(audio_segments, dim=-1)
- return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}
- return None
+ return _finish({"x": audio, "audio_sampling_rate": int(self.sample_rate)})
+ return _finish(None)
audio_segments.append(segment)
completed_lines += 1
# No extra callback here; per-line callback handles progress.
@@ -565,7 +595,7 @@ class KugelAudioPipeline:
break
if audio_segments:
audio = torch.cat(audio_segments, dim=-1)
- return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}
+ return _finish({"x": audio, "audio_sampling_rate": int(self.sample_rate)})
voice_prompt = audio_guide
single_segments = self._split_text_sequence(text, auto_split_tokens)
@@ -577,7 +607,7 @@ class KugelAudioPipeline:
)
for idx, one_segment in enumerate(single_segments):
if self._abort_requested():
- return None
+ return _finish(None)
duration_left = None
if total_duration_seconds is not None:
duration_left = max(0.0, total_duration_seconds - elapsed_seconds)
@@ -595,16 +625,16 @@ class KugelAudioPipeline:
if segment is None:
if self._early_stop_requested() and audio_segments:
audio = torch.cat(audio_segments, dim=-1)
- return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}
- return None
+ return _finish({"x": audio, "audio_sampling_rate": int(self.sample_rate)})
+ return _finish(None)
audio_segments.append(segment)
elapsed_seconds += float(segment.shape[-1]) / float(self.sample_rate)
if self._early_stop_requested():
break
if len(audio_segments) > 0:
audio = torch.cat(audio_segments, dim=-1)
- return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}
- return None
+ return _finish({"x": audio, "audio_sampling_rate": int(self.sample_rate)})
+ return _finish(None)
# Default single-pass generation
inputs = self.processor(
@@ -665,22 +695,25 @@ class KugelAudioPipeline:
abort_check=self._abort_requested,
early_stop_check=self._early_stop_requested,
callback=callback,
+ release_decode_graph_on_exit=False,
)
if outputs is None:
- return None
+ return _finish(None)
if self._abort_requested():
- return None
+ return _finish(None)
audio = None
if getattr(outputs, "speech_outputs", None):
audio = outputs.speech_outputs[0]
if audio is None:
- return None
+ return _finish(None)
- return {"x": audio, "audio_sampling_rate": int(self.sample_rate)}
+ return _finish({"x": audio, "audio_sampling_rate": int(self.sample_rate)})
def release(self) -> None:
+ if self.model is not None and hasattr(self.model, "release_decode_cuda_graph"):
+ self.model.release_decode_cuda_graph()
if hasattr(self.model, "to"):
self.model.to("cpu")
self.model = None
diff --git a/models/TTS/kugelaudio_handler.py b/models/TTS/kugelaudio_handler.py
index 9e86cf9..ccd6eb5 100644
--- a/models/TTS/kugelaudio_handler.py
+++ b/models/TTS/kugelaudio_handler.py
@@ -42,6 +42,25 @@ KUGELAUDIO_CUSTOM_SETTINGS = [
]
+def _configure_diffusion_compile_targets(model):
+ for _, submodule in model.named_modules():
+ submodule._compile_me = False
+
+ prediction_head = getattr(model, "prediction_head", None)
+ if prediction_head is None:
+ prediction_head = getattr(getattr(model, "model", None), "prediction_head", None)
+ if prediction_head is None:
+ raise RuntimeError("KugelAudio diffusion head is missing; cannot configure compile targets.")
+
+ layers = getattr(prediction_head, "layers", None)
+ if layers is not None:
+ for layer in layers:
+ layer._compile_me = True
+ final_layer = getattr(prediction_head, "final_layer", None)
+ if final_layer is not None:
+ final_layer._compile_me = True
+
+
def _get_kugelaudio_model_def():
return {
"audio_only": True,
@@ -54,6 +73,7 @@ def _get_kugelaudio_model_def():
"image_prompt_types_allowed": "",
"supports_early_stop": True,
"profiles_dir": ["kugelaudio_0_open"],
+ "lm_engines": ["cg"],
"duration_slider": dict(KUGELAUDIO_DURATION_SLIDER),
"custom_settings": [one.copy() for one in KUGELAUDIO_CUSTOM_SETTINGS],
"preserve_empty_prompt_lines": True,
@@ -73,7 +93,7 @@ def _get_kugelaudio_model_def():
},
"text_prompt_enhancer_instructions": TTS_MONOLOGUE_OR_DIALOGUE_PROMPT,
"prompt_enhancer_button_label": "Write Speech",
- "compile": False,
+ "compile": ["transformer"],
}
@@ -140,6 +160,7 @@ class family_handler:
submodel_no_list=None,
text_encoder_filename=None,
profile=0,
+ lm_decoder_engine="legacy",
**kwargs,
):
from .kugelaudio.pipeline import KugelAudioPipeline
@@ -149,7 +170,14 @@ class family_handler:
model_weights_path=weights_path,
ckpt_root=fl.get_download_location(),
device=torch.device("cpu"),
+ lm_decoder_engine=lm_decoder_engine,
)
+ if lm_decoder_engine == "cg":
+ pipeline.model._budget = 0
+ language_model = getattr(getattr(pipeline.model, "model", None), "language_model", None)
+ if language_model is not None:
+ language_model._budget = 0
+ _configure_diffusion_compile_targets(pipeline.model)
pipe = {
"transformer": pipeline.model,