Skip to content
Python

added int8 optimized kernels & overcharged Ace Step 1.5

DeepBeepMeep1c36b24d5b56
diff --git a/README.md b/README.md
index 99e053b..5d516ef 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,24 @@ WanGP supports the Wan (and derived models) but also Hunyuan Video, Flux, Qwen,
## 🔥 Latest Updates :
+### February 9rd 2026: WanGP v10.80, Easy Metal
+
+- **Ace Step 1.5 Turbo Super Charged**: all the best features of *Ace Step 1.5* are now in *WanGP* and are *Fast* & *Easy* to use:
+ * Manual Selection of *Bpm*, *Keyscale*, *Time Signature* & *Language*
+ * Use *LM* to auto detect *Bpm*, *Keyscale*, *Time Signature* & *Language* that best suits your *Lyrics*
+ * Use *LM* to refine *Music Caption* or auto detect *Song Duration*
+ * Choice of *vllm* engine for *LM* for up to *10x faster LM generation!!!*. Also as a WanGP exclusive, *vllm* is offered in *INT8 quantized* format for lower VRAM requirements. Please note you will need to install *Triton* and *Flash Attention 2* (check the *INSTALLATION.Md* for easy install)
+ * Use *LM* to refine *Music Caption* (usually the key to get the song theme you expected)
+ * UI Makeover to better match vocabulary used in original Ace Step App (but without its complexity...)
+ * Refined *System Prompt* used in *Prompt Enhancer* to generate *Lyrics* (I recommend to use the *LLama Joy Prompt Enhancer*)
+
+- **LoKr support**: this "Lora" like format has been tested with *Flux Klein 9B*
+
+- **Optimized Int8 Kernels**: all the *Quantized INT8 checkpoints* (most of the quantized checkpoints) used with WanGP should be now *10% faster !!!*. You will need to install *Triton*. It is experimental, so for the moment it needs to be enabled manually in the *Config / Performance* tab. Please share your feedback on *discord* by mentioning your GPU so that I know if it works properly.
+
+- **Auto Queue Saved if Gen Error**: if for whatever reason you have got an error during a Gen, the queue will now be automatically saved. So you can try again this queue later (with a different config or when the related bug is fixed, if ever ...).
+
+
### February 4rd 2026: WanGP v10.70, Let's Get Ready To Rumble !
*The competition between Open Source & Close Source has never been that hot !*
diff --git a/defaults/ace_step_v1_5.json b/defaults/ace_step_v1_5.json
index ca8dac5..4969517 100644
--- a/defaults/ace_step_v1_5.json
+++ b/defaults/ace_step_v1_5.json
@@ -7,7 +7,6 @@
"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"
},
@@ -15,7 +14,7 @@
"alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
"audio_prompt_type": "",
"audio_scale": 0.5,
- "duration_seconds": 60,
+ "duration_seconds": 120,
"num_inference_steps": 8,
"shift": 1.0,
"guidance_scale": 1.0,
diff --git a/defaults/ace_step_v1_5_turbo_lm_0_6b.json b/defaults/ace_step_v1_5_turbo_lm_0_6b.json
index 266ad53..63fc5d4 100644
--- a/defaults/ace_step_v1_5_turbo_lm_0_6b.json
+++ b/defaults/ace_step_v1_5_turbo_lm_0_6b.json
@@ -2,12 +2,11 @@
"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.",
+ "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 triggers a Medium/Weak Think Mode that will increase the Audio Output Quality and Lyrics Matching.",
"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"
},
@@ -15,7 +14,7 @@
"alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
"audio_prompt_type": "",
"audio_scale": 0.5,
- "duration_seconds": 60,
+ "duration_seconds": 120,
"num_inference_steps": 8,
"shift": 1.0,
"guidance_scale": 1.0,
diff --git a/defaults/ace_step_v1_5_turbo_lm_1_7b.json b/defaults/ace_step_v1_5_turbo_lm_1_7b.json
index ac3ca06..46a18be 100644
--- a/defaults/ace_step_v1_5_turbo_lm_1_7b.json
+++ b/defaults/ace_step_v1_5_turbo_lm_1_7b.json
@@ -2,13 +2,12 @@
"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.",
+ "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 triggers a Medium Think Mode that will increase the Audio Output Quality and Lyrics Matching.",
"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"
},
@@ -16,7 +15,7 @@
"alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
"audio_prompt_type": "",
"audio_scale": 0.5,
- "duration_seconds": 60,
+ "duration_seconds": 120,
"num_inference_steps": 8,
"shift": 1.0,
"guidance_scale": 1.0,
diff --git a/defaults/ace_step_v1_5_turbo_lm_4b.json b/defaults/ace_step_v1_5_turbo_lm_4b.json
index 6f64ea4..f4d874e 100644
--- a/defaults/ace_step_v1_5_turbo_lm_4b.json
+++ b/defaults/ace_step_v1_5_turbo_lm_4b.json
@@ -2,13 +2,12 @@
"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.",
+ "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 triggers a Strong Think Mode that will increase the Audio Output Quality and Lyrics Matching.",
"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"
},
@@ -16,7 +15,7 @@
"alt_prompt": "Dreamy synth-pop with shimmering pads, soft vocals, and a slow dance groove.",
"audio_prompt_type": "",
"audio_scale": 0.5,
- "duration_seconds": 60,
+ "duration_seconds": 120,
"num_inference_steps": 8,
"shift": 1.0,
"guidance_scale": 1.0,
diff --git a/defaults/chatterbox.json b/defaults/chatterbox.json
index 1030f87..9878043 100644
--- a/defaults/chatterbox.json
+++ b/defaults/chatterbox.json
@@ -12,7 +12,9 @@
"repeat_generation": 1,
"video_length": 0,
"num_inference_steps": 0,
- "pace": 0.5,
- "exaggeration": 0.5,
+ "custom_settings": {
+ "exaggeration": 0.5,
+ "pace": 0.5
+ },
"temperature": 0.8
}
diff --git a/extract_source_images.py b/extract_source_images.py
deleted file mode 100755
index 1003ccd..0000000
--- a/extract_source_images.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/env python3
-"""
-Extract Source Images from Video Files
-
-This utility extracts source images that were embedded in video files
-generated by Wan2GP with source image embedding enabled.
-Supports MKV (attachments) and MP4 (cover art) formats.
-"""
-
-import sys
-import os
-import argparse
-import glob
-from shared.utils.audio_video import extract_source_images
-
-
-def main():
- parser = argparse.ArgumentParser(
- description="Extract source images from video files with embedded images (MKV attachments or MP4 cover art)",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog=__doc__
- )
-
- parser.add_argument(
- 'video_files',
- nargs='+',
- help='Video file(s) to extract source images from (MKV or MP4)'
- )
-
- parser.add_argument(
- '-o', '--output-dir',
- help='Output directory for extracted images (default: same as video directory)'
- )
-
- parser.add_argument(
- '-v', '--verbose',
- action='store_true',
- help='Enable verbose output'
- )
-
- args = parser.parse_args()
-
- # Expand glob patterns
- video_files = []
- for pattern in args.video_files:
- if '*' in pattern or '?' in pattern:
- video_files.extend(glob.glob(pattern))
- else:
- video_files.append(pattern)
-
- if not video_files:
- print("No video files found matching the specified patterns.")
- return 1
-
- total_extracted = 0
-
- for video_file in video_files:
- if not os.path.exists(video_file):
- print(f"Warning: File not found: {video_file}")
- continue
-
- if not (video_file.lower().endswith('.mkv') or video_file.lower().endswith('.mp4')):
- print(f"Warning: Skipping unsupported file: {video_file} (only MKV and MP4 supported)")
- continue
-
- if args.verbose:
- print(f"\nProcessing: {video_file}")
-
- # Determine output directory
- if args.output_dir:
- output_dir = args.output_dir
- else:
- # Create subdirectory next to video file
- video_dir = os.path.dirname(video_file) or '.'
- video_name = os.path.splitext(os.path.basename(video_file))[0]
- output_dir = os.path.join(video_dir, f"{video_name}_sources")
-
- try:
- extracted_files = extract_source_images(video_file, output_dir)
-
- if extracted_files:
- print(f"✓ Extracted {len(extracted_files)} source image(s) from {video_file}")
- if args.verbose:
- for img_file in extracted_files:
- print(f" → {img_file}")
- total_extracted += len(extracted_files)
- else:
- print(f"ℹ No source images found in {video_file}")
-
- except Exception as e:
- print(f"✗ Error processing {video_file}: {e}")
-
- print(f"\nTotal: Extracted {total_extracted} source image(s) from {len(video_files)} video file(s)")
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/favicon.png b/favicon.png
deleted file mode 100644
index 30d361d..0000000
Binary files a/favicon.png and /dev/null differ
diff --git a/models/TTS/ace_step/pipeline_ace_step.py b/models/TTS/ace_step/pipeline_ace_step.py
index 48a2260..09d44fd 100644
--- a/models/TTS/ace_step/pipeline_ace_step.py
+++ b/models/TTS/ace_step/pipeline_ace_step.py
@@ -1715,6 +1715,45 @@ class ACEStepPipeline:
*,
alt_prompt=None,
temperature: float = 1.0,
+ duration_seconds=None,
+ audio_duration=None,
+ sampling_steps=None,
+ num_inference_steps=None,
+ cfg_scale=None,
+ guidance_scale=7.0,
+ sample_solver=None,
+ scheduler_type="euler",
+ seed=None,
+ batch_size=1,
+ guidance_scale_text=None,
+ guidance_scale_lyric=None,
+ callback=None,
+ task="text2music",
+ src_audio_path=None,
+ edit_target_prompt=None,
+ edit_target_lyrics=None,
+ edit_n_min=None,
+ edit_n_max=None,
+ cfg_type="apg",
+ omega_scale=10.0,
+ guidance_interval=0.5,
+ guidance_interval_decay=0.0,
+ min_guidance_scale=3.0,
+ use_erg_tag=True,
+ use_erg_lyric=True,
+ use_erg_diffusion=True,
+ oss_steps=None,
+ audio_scale=None,
+ ref_audio_strength=0.5,
+ lora_name_or_path="none",
+ lora_weight=1.0,
+ retake_seeds=None,
+ retake_variance=0.5,
+ repaint_start=0,
+ repaint_end=0,
+ edit_n_avg=1,
+ debug=False,
+ loras_slists=None,
**kwargs,
):
self._interrupt = False
@@ -1731,59 +1770,34 @@ class ACEStepPipeline:
if alt_prompt:
prompt = self._read_text_or_file(str(alt_prompt), "Prompt")
- duration_seconds = kwargs.get("duration_seconds", None)
if duration_seconds is None:
- duration_seconds = kwargs.get("audio_duration", None)
- try:
- duration_seconds = float(duration_seconds) if duration_seconds is not None else None
- except (TypeError, ValueError):
- duration_seconds = None
+ duration_seconds = audio_duration
if duration_seconds is None or duration_seconds <= 0:
duration_seconds = 20.0
- sampling_steps = kwargs.get("sampling_steps", None)
if sampling_steps is None:
- sampling_steps = kwargs.get("num_inference_steps", None)
- try:
- infer_step = int(sampling_steps) if sampling_steps is not None else 0
- except (TypeError, ValueError):
- infer_step = 0
+ sampling_steps = num_inference_steps
+ infer_step = 0 if sampling_steps is None else sampling_steps
if infer_step <= 0:
infer_step = 30
- guidance_scale = kwargs.get("cfg_scale", kwargs.get("guidance_scale", 7.0))
- try:
- guidance_scale = float(guidance_scale)
- except (TypeError, ValueError):
+ if cfg_scale is not None:
+ guidance_scale = cfg_scale
+ if guidance_scale is None:
guidance_scale = 7.0
- scheduler_type = (model_mode or kwargs.get("scheduler_type", "euler")).lower()
+ scheduler_type = (model_mode or sample_solver or scheduler_type).lower()
if scheduler_type not in ("euler", "heun", "pingpong"):
scheduler_type = "euler"
- seed = kwargs.get("seed", None)
- try:
- seed = int(seed) if seed is not None else None
- except (TypeError, ValueError):
+ if seed is not None and seed < 0:
seed = None
manual_seeds = seed if seed is not None and seed >= 0 else None
- batch_size = kwargs.get("batch_size", 1)
- try:
- batch_size = int(batch_size)
- except (TypeError, ValueError):
+ if batch_size is None or batch_size <= 0:
batch_size = 1
- guidance_scale_text = kwargs.get("guidance_scale_text", None)
- guidance_scale_lyric = kwargs.get("guidance_scale_lyric", None)
-
- callback = kwargs.get("callback")
- task = kwargs.get("task", "text2music")
- src_audio_path = kwargs.get("src_audio_path", None)
- edit_target_prompt = kwargs.get("edit_target_prompt", None)
- edit_target_lyrics = kwargs.get("edit_target_lyrics", None)
- edit_n_min = kwargs.get("edit_n_min", None)
- edit_n_max = kwargs.get("edit_n_max", None)
+ effective_ref_audio_strength = audio_scale if audio_scale is not None else ref_audio_strength
return self.__call__(
format="wav",
@@ -1793,38 +1807,38 @@ class ACEStepPipeline:
infer_step=infer_step,
guidance_scale=guidance_scale,
scheduler_type=scheduler_type,
- cfg_type=kwargs.get("cfg_type", "apg"),
- omega_scale=kwargs.get("omega_scale", 10.0),
+ cfg_type=cfg_type,
+ omega_scale=omega_scale,
manual_seeds=manual_seeds,
- guidance_interval=kwargs.get("guidance_interval", 0.5),
- guidance_interval_decay=kwargs.get("guidance_interval_decay", 0.0),
- min_guidance_scale=kwargs.get("min_guidance_scale", 3.0),
- use_erg_tag=kwargs.get("use_erg_tag", True),
- use_erg_lyric=kwargs.get("use_erg_lyric", True),
- use_erg_diffusion=kwargs.get("use_erg_diffusion", True),
- oss_steps=kwargs.get("oss_steps", None),
+ guidance_interval=guidance_interval,
+ guidance_interval_decay=guidance_interval_decay,
+ min_guidance_scale=min_guidance_scale,
+ use_erg_tag=use_erg_tag,
+ use_erg_lyric=use_erg_lyric,
+ use_erg_diffusion=use_erg_diffusion,
+ oss_steps=oss_steps,
guidance_scale_text=0.0 if guidance_scale_text is None else guidance_scale_text,
guidance_scale_lyric=0.0 if guidance_scale_lyric is None else guidance_scale_lyric,
audio2audio_enable=audio2audio_enable,
- ref_audio_strength=kwargs.get("audio_scale", kwargs.get("ref_audio_strength", 0.5)),
+ ref_audio_strength=effective_ref_audio_strength,
ref_audio_input=ref_audio_input,
- lora_name_or_path=kwargs.get("lora_name_or_path", "none"),
- lora_weight=kwargs.get("lora_weight", 1.0),
- retake_seeds=kwargs.get("retake_seeds", None),
- retake_variance=kwargs.get("retake_variance", 0.5),
+ lora_name_or_path=lora_name_or_path,
+ lora_weight=lora_weight,
+ retake_seeds=retake_seeds,
+ retake_variance=retake_variance,
task=task,
- repaint_start=kwargs.get("repaint_start", 0),
- repaint_end=kwargs.get("repaint_end", 0),
+ repaint_start=repaint_start,
+ repaint_end=repaint_end,
src_audio_path=src_audio_path,
edit_target_prompt=edit_target_prompt,
edit_target_lyrics=edit_target_lyrics,
edit_n_min=0.0 if edit_n_min is None else edit_n_min,
edit_n_max=1.0 if edit_n_max is None else edit_n_max,
- edit_n_avg=kwargs.get("edit_n_avg", 1),
+ edit_n_avg=edit_n_avg,
save_path=None,
batch_size=batch_size,
- debug=kwargs.get("debug", False),
+ debug=debug,
callback=callback,
return_audio=True,
- loras_slists=kwargs["loras_slists"],
+ loras_slists=loras_slists,
)
diff --git a/models/TTS/ace_step15/pipeline_ace_step15.py b/models/TTS/ace_step15/pipeline_ace_step15.py
index c49c367..f984d2e 100644
--- a/models/TTS/ace_step15/pipeline_ace_step15.py
+++ b/models/TTS/ace_step15/pipeline_ace_step15.py
@@ -7,6 +7,8 @@ import math
import os
import random
import re
+import sys
+from typing import Any
import torch
import torchaudio
@@ -40,6 +42,28 @@ _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:"
+_ACE_STEP15_MODEL_MODE_DEFAULT = 0
+_ACE_STEP15_MODEL_MODE_INFER_MISSING = 1
+_ACE_STEP15_MODEL_MODE_INFER_AND_REFINE = 2
+_ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION = 3
+_ACE_STEP15_DEFAULT_BPM = 120
+_ACE_STEP15_DEFAULT_TIMESIGNATURE = 2
+_ACE_STEP15_DEFAULT_KEYSCALE = "C major"
+_ACE_STEP15_DURATION_MIN_SECONDS = 5
+_ACE_STEP15_DURATION_MAX_SECONDS = 600
+_ACE_STEP15_ALLOWED_TIMESIGNATURES = {2, 3, 4, 6}
+_ACE_STEP15_BPM_OPTIONS = [str(v) for v in range(30, 301)]
+_ACE_STEP15_TIMESIGNATURE_OPTIONS = ["2", "3", "4", "6"]
+_ACE_STEP15_KEYSCALE_OPTIONS = [f"{note}{accidental} {mode}" for note in ("A", "B", "C", "D", "E", "F", "G") for accidental in ("", "#", "b") for mode in ("major", "minor")]
+_ACE_STEP15_VALID_LANGUAGES = (
+ "ar", "az", "bg", "bn", "ca", "cs", "da", "de", "el", "en",
+ "es", "fa", "fi", "fr", "he", "hi", "hr", "ht", "hu", "id",
+ "is", "it", "ja", "ko", "la", "lt", "ms", "ne", "nl", "no",
+ "pa", "pl", "pt", "ro", "ru", "sa", "sk", "sr", "sv", "sw",
+ "ta", "te", "th", "tl", "tr", "uk", "ur", "vi", "yue", "zh",
+ "unknown",
+)
+_ACE_STEP15_VALID_LANGUAGE_SET = set(_ACE_STEP15_VALID_LANGUAGES)
_SFT_GEN_PROMPT = """# Instruction
{}
@@ -84,7 +108,9 @@ class ACEStep15Pipeline:
lm_tokenizer_dir: str,
silence_latent_path: str | None = None,
enable_lm: bool = True,
- ignore_lm_cache_seed: bool = True,
+ ignore_lm_cache_seed: bool = False,
+ lm_decoder_engine: str = "legacy",
+ lm_vllm_weight_mode: str = "lazy",
device=None,
dtype=torch.bfloat16,
):
@@ -109,6 +135,10 @@ class ACEStep15Pipeline:
self.lm_tokenizer_dir = lm_tokenizer_dir
self.silence_latent_path = silence_latent_path
self.ignore_lm_cache_seed = bool(ignore_lm_cache_seed)
+ self.lm_engine = (lm_decoder_engine or "legacy").strip().lower()
+ if self.lm_engine not in ("legacy", "pt", "vllm"):
+ self.lm_engine = "legacy"
+ self.lm_vllm_weight_mode = (lm_vllm_weight_mode or "lazy").strip().lower()
self._interrupt = False
self._early_stop = False
@@ -116,16 +146,25 @@ class ACEStep15Pipeline:
self._latent_hop_length = 1920
self.lm_code_cache = TextEncoderCache()
+ self._lm_engine_impl = None
+ self._lm_create_engine_fn = None
+ self._lm_legacy_generate_fn = None
+ self._lm_legacy_text_fn = None
+ self._ref_metadata_processor = None
+ self._ref_metadata_processor_class = None
+ self._ref_caption_postprocess_fn = None
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:
+ if self.enable_lm and self.lm_engine != "vllm":
self._load_lm()
else:
self.lm_model = None
self._load_silence_latent()
+ if self.enable_lm:
+ self._init_lm_engine()
self.loaded = True
@@ -200,26 +239,43 @@ class ACEStep15Pipeline:
self.lm_tokenizer = None
if not self.enable_lm:
return
+ lm_loader = lambda: AutoTokenizer.from_pretrained(
+ self.lm_tokenizer_dir,
+ local_files_only=True,
+ trust_remote_code=True,
+ )
+ cache_tag = os.path.basename(os.path.normpath(str(self.lm_tokenizer_dir or ""))) or "lm"
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,
- ),
- )
+ self.lm_tokenizer = load_cached_lm_tokenizer(self.lm_tokenizer_dir, lm_loader, cache_tag=cache_tag)
+ audio_token_count = self._count_audio_code_tokens(self.lm_tokenizer)
+ if audio_token_count == 0:
+ print("[ace_step15] LM tokenizer cache has no audio_code tokens; reloading tokenizer without stale cache.")
+ rebuild_tag = f"{cache_tag}.rebuild"
+ self.lm_tokenizer = load_cached_lm_tokenizer(self.lm_tokenizer_dir, lm_loader, cache_tag=rebuild_tag)
except Exception:
- self.lm_tokenizer = AutoTokenizer.from_pretrained(
- self.lm_tokenizer_dir,
- local_files_only=True,
- trust_remote_code=True,
- )
+ self.lm_tokenizer = lm_loader()
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()
+ if len(getattr(self, "_audio_code_token_ids", [])) == 0:
+ raise RuntimeError(
+ f"No audio_code tokens found in LM tokenizer at '{self.lm_tokenizer_dir}'. "
+ "Tokenizer cache/files are invalid for ACE-Step 1.5."
+ )
+
+ @staticmethod
+ def _count_audio_code_tokens(tokenizer):
+ try:
+ vocab = tokenizer.get_vocab()
+ except Exception:
+ return 0
+ count = 0
+ for token_text in vocab.keys():
+ if _AUDIO_CODE_TOKEN_RE.match(token_text):
+ count += 1
+ return count
def _load_text_encoder_2(self):
config_path = os.path.join(os.path.dirname(self.text_encoder_2_weights_path), "config.json")
@@ -254,6 +310,44 @@ class ACEStep15Pipeline:
ignore_unused_weights=True,
)
self.lm_model.eval()
+ self._disable_lm_compile_for_mmgp()
+
+ def _disable_lm_compile_for_mmgp(self):
+ if self.lm_model is None:
+ return
+ try:
+ self.lm_model._compile_me = False
+ for submodule in self.lm_model.modules():
+ submodule._compile_me = False
+ except Exception:
+ return
+
+ def _ensure_lm_module_loaded(self):
+ if self._lm_create_engine_fn is not None and self._lm_legacy_generate_fn is not None and self._lm_legacy_text_fn is not None:
+ return
+ from .qwen3_audio_codes import create_qwen3_lm_engine, generate_audio_codes_legacy, generate_text_legacy
+
+ self._lm_create_engine_fn = create_qwen3_lm_engine
+ self._lm_legacy_generate_fn = generate_audio_codes_legacy
+ self._lm_legacy_text_fn = generate_text_legacy
+
+ def _init_lm_engine(self):
+ self._ensure_lm_module_loaded()
+ self._lm_engine_impl = self._lm_create_engine_fn(
+ engine_name=self.lm_engine,
+ model=self.lm_model,
+ tokenizer=self.lm_tokenizer,
+ device=self.device,
+ lm_weights_path=self.lm_weights_path,
+ audio_code_mask=getattr(self, "_audio_code_mask", None),
+ audio_code_token_map=getattr(self, "_audio_code_token_map", {}),
+ weight_load_mode=self.lm_vllm_weight_mode,
+ )
+ if self.lm_engine in ("pt", "vllm") and self._lm_engine_impl is None:
+ raise RuntimeError(
+ f"Failed to initialize LM engine '{self.lm_engine}'. "
+ "Check LM weights path and tokenizer availability."
+ )
def _load_silence_latent(self):
if not self.silence_latent_path or not os.path.isfile(self.silence_latent_path):
@@ -421,6 +515,376 @@ class ACEStep15Pipeline:
def _build_lyrics_prompt(self, lyrics, language):
return "# Languages\n{}\n\n# Lyric\n{}<|endoftext|>".format(language, lyrics)
+ @staticmethod
+ def _parse_model_mode(model_mode) -> int:
+ if model_mode is None:
+ return _ACE_STEP15_MODEL_MODE_DEFAULT
+ try:
+ parsed_mode = int(model_mode)
+ except Exception:
+ return _ACE_STEP15_MODEL_MODE_DEFAULT
+ if parsed_mode not in (
+ _ACE_STEP15_MODEL_MODE_DEFAULT,
+ _ACE_STEP15_MODEL_MODE_INFER_MISSING,
+ _ACE_STEP15_MODEL_MODE_INFER_AND_REFINE,
+ _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION,
+ ):
+ return _ACE_STEP15_MODEL_MODE_DEFAULT
+ return parsed_mode
+
+ @staticmethod
+ def _parse_optional_int_custom_setting(value):
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ if value.is_integer():
+ return int(value)
+ return None
+ try:
+ parsed = float(str(value).strip())
+ except Exception:
+ return None
+ if not parsed.is_integer():
+ return None
+ return int(parsed)
+
+ @staticmethod
+ def _normalize_optional_keyscale(value):
+ if value is None:
+ return None
+ keyscale = str(value).strip()
+ if len(keyscale) == 0:
+ return None
+ keyscale = keyscale.replace("♯", "#").replace("♭", "b")
+ short_minor = re.fullmatch(r"([A-Ga-g])\s*([#b]?)\s*[mM]", keyscale)
+ if short_minor:
+ note = short_minor.group(1).upper()
+ accidental = short_minor.group(2)
+ return f"{note}{accidental} minor"
+ full = re.fullmatch(r"([A-Ga-g])\s*([#b]?)\s*(major|minor|maj|min)", keyscale, flags=re.IGNORECASE)
+ if not full:
+ return keyscale
+ note = full.group(1).upper()
+ accidental = full.group(2)
+ mode = full.group(3).lower()
+ if mode == "maj":
+ mode = "major"
+ elif mode == "min":
+ mode = "minor"
+ return f"{note}{accidental} {mode}"
+
+ @staticmethod
+ def _format_known_metadata_lines(metadata: dict) -> str:
+ lines = []
+ for key in ("bpm", "keyscale", "timesignature"):
+ value = metadata.get(key, None)
+ if value is None:
+ continue
+ lines.append(f"- {key}: {value}")
+ return "\n".join(lines)
+
+ def _build_lm_chat_prompt(self, system_instruction: str, user_content: str) -> str:
+ formatted = self.lm_tokenizer.apply_chat_template(
+ [
+ {"role": "system", "content": system_instruction},
+ {"role": "user", "content": user_content},
+ ],
+ tokenize=False,
+ add_generation_prompt=True,
+ )
+ if not formatted.endswith("\n"):
+ formatted += "\n"
+ return formatted
+
+ def _generate_lm_text(
+ self,
+ prompt: str,
+ *,
+ prompt_negative: str,
+ max_tokens: int,
+ temperature,
+ top_p,
+ top_k,
+ cfg_scale: float,
+ seed: int | None,
+ callback=None,
+ logits_processor=None,
+ logits_processor_update_state=None,
+ stop_checker=None,
+ progress_label: str = "LM text",
+ ):
+ if self._lm_engine_impl is not None and hasattr(self._lm_engine_impl, "generate_text"):
+ return self._lm_engine_impl.generate_text(
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=self._should_abort,
+ logits_processor=logits_processor,
+ logits_processor_update_state=logits_processor_update_state,
+ stop_checker=stop_checker,
+ progress_label=progress_label,
+ )
+ if self.lm_engine != "legacy":
+ raise RuntimeError(f"LM engine '{self.lm_engine}' is not initialized for text generation.")
+ if self.lm_model is None or self.lm_tokenizer is None:
+ raise RuntimeError("Legacy LM engine requires loaded LM model and tokenizer.")
+ self._ensure_lm_module_loaded()
+ return self._lm_legacy_text_fn(
+ model=self.lm_model,
+ tokenizer=self.lm_tokenizer,
+ device=self.device,
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=self._should_abort,
+ logits_processor=logits_processor,
+ logits_processor_update_state=logits_processor_update_state,
+ stop_checker=stop_checker,
+ progress_label=progress_label,
+ ignore_eos=False,
+ )
+
+ def _ensure_reference_phase1_modules(self):
+ if self._ref_metadata_processor_class is not None:
+ return
+ acestep_root = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "ACE-Step-1.5"))
+ if not os.path.isdir(acestep_root):
+ raise RuntimeError(f"ACE-Step reference folder is missing: '{acestep_root}'")
+ if acestep_root not in sys.path:
+ sys.path.insert(0, acestep_root)
+ from acestep.constrained_logits_processor import MetadataConstrainedLogitsProcessor
+
+ self._ref_metadata_processor_class = MetadataConstrainedLogitsProcessor
+ postprocess_caption = getattr(MetadataConstrainedLogitsProcessor, "postprocess_caption", None)
+ if callable(postprocess_caption):
+ self._ref_caption_postprocess_fn = postprocess_caption
+ else:
+ self._ref_caption_postprocess_fn = lambda x: str(x).strip()
+
+ def _get_reference_phase1_processor(self):
+ self._ensure_reference_phase1_modules()
+ if self._ref_metadata_processor is None:
+ self._ref_metadata_processor = self._ref_metadata_processor_class(
+ self.lm_tokenizer,
+ enabled=True,
+ debug=False,
+ skip_genres=True,
+ max_duration=600,
+ )
+ return self._ref_metadata_processor
+
+ def _build_reference_phase1_prompt(self, caption: str, lyrics: str, is_negative_prompt: bool = False, negative_prompt: str = "NO USER INPUT") -> str:
+ if self.lm_tokenizer is None:
+ raise RuntimeError("LM tokenizer is required for ACE-Step phase1 prompt formatting.")
+ if is_negative_prompt:
+ has_negative = bool(negative_prompt and str(negative_prompt).strip() and str(negative_prompt).strip() != "NO USER INPUT")
+ if has_negative:
+ user_prompt = f"# Caption\n{negative_prompt}\n\n# Lyric\n{lyrics}\n"
+ else:
+ user_prompt = f"# Lyric\n{lyrics}\n"
+ else:
+ user_prompt = f"# Caption\n{caption}\n\n# Lyric\n{lyrics}\n"
+ return self.lm_tokenizer.apply_chat_template(
+ [
+ {"role": "system", "content": f"# Instruction\n{_DEFAULT_LM_INSTRUCTION}\n\n"},
+ {"role": "user", "content": user_prompt},
+ ],
+ tokenize=False,
+ add_generation_prompt=True,
+ )
+
+ def _parse_reference_lm_output(self, output_text: str):
+ metadata = {}
+ audio_codes = ""
+ code_matches = re.findall(r"<\|audio_code_\d+\|>", str(output_text or ""))
+ if code_matches:
+ audio_codes = "".join(code_matches)
+ reasoning_text = None
+ for pattern in (r"<think>(.*?)</think>", r"<reasoning>(.*?)</reasoning>"):
+ match = re.search(pattern, str(output_text or ""), re.DOTALL)
+ if match:
+ reasoning_text = match.group(1).strip()
+ break
+ if not reasoning_text:
+ reasoning_text = str(output_text or "").split("<|audio_code_")[0].strip()
+ if reasoning_text:
+ lines = reasoning_text.split("\n")
+ current_key = None
+ current_value_lines = []
+
+ def _save_current_field():
+ nonlocal current_key, current_value_lines
+ if current_key and current_value_lines:
+ value = "\n".join(current_value_lines)
+ if current_key == "bpm":
+ try:
+ metadata["bpm"] = int(str(value).strip())
+ except Exception:
+ metadata["bpm"] = str(value).strip()
+ elif current_key == "caption":
+ metadata["caption"] = self._ref_caption_postprocess_fn(value) if self._ref_caption_postprocess_fn is not None else str(value).strip()
+ elif current_key == "duration":
+ try:
+ metadata["duration"] = int(str(value).strip())
+ except Exception:
+ metadata["duration"] = str(value).strip()
+ elif current_key == "genres":
+ metadata["genres"] = str(value).strip()
+ elif current_key == "keyscale":
+ metadata["keyscale"] = str(value).strip()
+ elif current_key == "language":
+ metadata["language"] = str(value).strip()
+ elif current_key == "timesignature":
+ metadata["timesignature"] = str(value).strip()
+ current_key = None
+ current_value_lines = []
+
+ for line in lines:
+ if line.strip().startswith("<"):
+ continue
+ if line and not line[0].isspace() and ":" in line:
+ _save_current_field()
+ parts = line.split(":", 1)
+ if len(parts) == 2:
+ current_key = parts[0].strip().lower()
+ first_value = parts[1]
+ if first_value.strip():
+ current_value_lines.append(first_value)
+ elif line.startswith(" ") or line.startswith("\t"):
+ if current_key:
+ current_value_lines.append(line)
+ _save_current_field()
+ return metadata, audio_codes
+
+ def _run_phase1_metadata(
+ self,
+ tags: str,
+ lyrics: str,
+ metadata: dict,
+ refine_caption: bool,
+ infer_language: bool,
+ seed: int | None,
+ cfg_scale: float,
+ negative_prompt: str,
+ temperature,
+ top_p,
+ top_k,
+ callback=None,
+ ):
+ phase1_metadata = dict(metadata)
+ if self._should_abort():
+ return None, None
+ processor = self._get_reference_phase1_processor()
+ processor.reset()
+ processor.enabled = True
+ processor.debug = False
+ processor.set_target_duration(None)
+
+ constrained_metadata = {}
+ if phase1_metadata.get("bpm", None) is not None:
+ constrained_metadata["bpm"] = str(int(phase1_metadata["bpm"]))
+ if phase1_metadata.get("keyscale", None) is not None:
+ constrained_metadata["keyscale"] = str(phase1_metadata["keyscale"])
+ if phase1_metadata.get("timesignature", None) is not None:
+ constrained_metadata["timesignature"] = str(int(phase1_metadata["timesignature"]))
+ if phase1_metadata.get("language", None) is not None:
+ constrained_metadata["language"] = str(phase1_metadata["language"]).strip().lower()
+ processor.set_user_metadata(constrained_metadata if len(constrained_metadata) > 0 else None)
+ processor.set_stop_at_reasoning(True)
+ processor.set_skip_genres(True)
+ processor.set_skip_caption(not refine_caption)
+ processor.set_skip_language(not infer_language)
+ processor.set_generation_phase("cot")
+
+ prompt = self._build_reference_phase1_prompt(tags, lyrics, is_negative_prompt=False, negative_prompt=negative_prompt)
+ prompt_negative = self._build_reference_phase1_prompt(tags, lyrics, is_negative_prompt=True, negative_prompt=negative_prompt)
+ metadata_seed = None if seed is None else int(seed)
+ text_out = self._generate_lm_text(
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=512,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=metadata_seed,
+ callback=callback,
+ logits_processor=processor,
+ logits_processor_update_state=processor.update_state,
+ stop_checker=None,
+ progress_label="LM Compute Metadata",
+ )
+ if text_out is None:
+ raise RuntimeError("LM phase1 failed while inferring metadata.")
+
+ phase1_text = text_out.get("text", "") if isinstance(text_out, dict) else ""
+ parsed_metadata, _ = self._parse_reference_lm_output(phase1_text)
+
+ bpm_value = self._parse_optional_int_custom_setting(parsed_metadata.get("bpm", None))
+ if bpm_value is not None:
+ if bpm_value < 30 or bpm_value > 300:
+ raise RuntimeError(f"LM phase1 produced unsupported bpm '{bpm_value}'.")
+ phase1_metadata["bpm"] = bpm_value
+
+ keyscale_value = self._normalize_optional_keyscale(parsed_metadata.get("keyscale", None))
+ if keyscale_value is not None:
+ if keyscale_value not in _ACE_STEP15_KEYSCALE_OPTIONS:
+ raise RuntimeError(f"LM phase1 produced unsupported keyscale '{keyscale_value}'.")
+ phase1_metadata["keyscale"] = keyscale_value
+
+ timesig_raw = parsed_metadata.get("timesignature", None)
+ if timesig_raw is not None:
+ timesig_text = str(timesig_raw).strip()
+ if "/" in timesig_text:
+ timesig_text = timesig_text.split("/", 1)[0].strip()
+ timesig_value = self._parse_optional_int_custom_setting(timesig_text)
+ if timesig_value is None or timesig_value not in _ACE_STEP15_ALLOWED_TIMESIGNATURES:
+ raise RuntimeError(f"LM phase1 produced unsupported timesignature '{timesig_raw}'.")
+ phase1_metadata["timesignature"] = timesig_value
+
+ duration_value = self._parse_optional_int_custom_setting(parsed_metadata.get("duration", None))
+ if duration_value is not None:
+ phase1_metadata["duration"] = int(duration_value)
+
+ language_raw = parsed_metadata.get("language", None)
+ if language_raw is not None:
+ language_value = str(language_raw).strip().lower()
+ if len(language_value) > 0:
+ if language_value not in _ACE_STEP15_VALID_LANGUAGE_SET:
+ raise RuntimeError(f"LM phase1 produced unsupported language '{language_raw}'.")
+ phase1_metadata["language"] = language_value
+
+ refined_caption = None
+ if refine_caption:
+ refined_caption = str(parsed_metadata.get("caption", "")).strip()
+ if "<" in refined_caption or ">" in refined_caption:
+ raise RuntimeError(f"LM phase1 produced an invalid refined caption '{refined_caption}'.")
+ if len(refined_caption) == 0:
+ raise RuntimeError("LM phase1 returned an empty refined caption.")
+
+ return phase1_metadata, refined_caption
+
+ @staticmethod
+ def _normalize_duration_cache_value(duration):
+ try:
+ return round(float(duration), 4)
+ except Exception:
+ return str(duration)
+
def _build_lm_cache_key(
self,
tags,
@@ -444,10 +908,11 @@ class ACEStep15Pipeline:
os.path.abspath(self.lm_weights_path) if self.lm_weights_path else "",
os.path.abspath(self.lm_tokenizer_dir) if self.lm_tokenizer_dir else "",
_DEFAULT_LM_INSTRUCTION,
+ self.lm_engine,
str(tags or ""),
str(lyrics or ""),
int(bpm),
- int(duration),
+ self._normalize_duration_cache_value(duration),
str(keyscale),
int(timesignature),
str(language or ""),
@@ -479,9 +944,15 @@ class ACEStep15Pipeline:
negative_prompt="NO USER INPUT",
cfg_scale=None,
callback=None,
+ offloadobj=None,
):
if cfg_scale is None:
cfg_scale = 2.5
+ if self.lm_engine == "vllm" and offloadobj is not None:
+ try:
+ offloadobj.unload_all()
+ except Exception:
+ pass
metadata = {
"bpm": bpm,
@@ -498,120 +969,43 @@ class ACEStep15Pipeline:
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,
+ if self._lm_engine_impl is not None:
+ return self._lm_engine_impl.generate_audio_codes(
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ min_tokens=min_tokens,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=self._should_abort,
)
- 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]
+ if self.lm_engine != "legacy":
+ raise RuntimeError(f"LM engine '{self.lm_engine}' is not initialized.")
+ if self.lm_model is None or self.lm_tokenizer is None:
+ raise RuntimeError("Legacy LM engine requires loaded LM model and tokenizer.")
+ self._ensure_lm_module_loaded()
+ return self._lm_legacy_generate_fn(
+ model=self.lm_model,
+ tokenizer=self.lm_tokenizer,
+ device=self.device,
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ audio_code_mask=getattr(self, "_audio_code_mask", None),
+ audio_code_token_map=getattr(self, "_audio_code_token_map", {}),
+ min_tokens=min_tokens,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=self._should_abort,
+ )
def _generate_audio_codes(
self,
@@ -631,16 +1025,13 @@ class ACEStep15Pipeline:
negative_prompt="NO USER INPUT",
cfg_scale=None,
callback=None,
+ offloadobj=None,
):
if cfg_scale is None:
cfg_scale = 2.5
- cache_seed = seed
- if self.ignore_lm_cache_seed:
- cache_seed = 0
- use_cache = self.lm_code_cache is not None and (
- (cache_seed is not None and cache_seed >= 0) or self.ignore_lm_cache_seed
- )
+ cache_seed = seed if seed is not None and seed >= 0 else None
+ use_cache = self.lm_code_cache is not None and cache_seed is not None
if not use_cache:
return self._generate_audio_codes_uncached(
tags=tags,
@@ -659,9 +1050,10 @@ class ACEStep15Pipeline:
negative_prompt=negative_prompt,
cfg_scale=cfg_scale,
callback=callback,
+ offloadobj=offloadobj,
)
- effective_seed = cache_seed if cache_seed is not None and cache_seed >= 0 else seed
+ effective_seed = cache_seed
cache_key = self._build_lm_cache_key(
tags=tags,
lyrics=lyrics,
@@ -677,7 +1069,7 @@ class ACEStep15Pipeline:
language=language,
negative_prompt=negative_prompt,
cfg_scale=cfg_scale,
- seed_value=cache_seed if self.ignore_lm_cache_seed else seed,
+ seed_value=cache_seed,
)
def encode_fn(_prompts):
@@ -698,6 +1090,7 @@ class ACEStep15Pipeline:
negative_prompt=negative_prompt,
cfg_scale=cfg_scale,
callback=callback,
+ offloadobj=offloadobj,
)
if codes is None:
return [None]
@@ -713,11 +1106,59 @@ class ACEStep15Pipeline:
if hasattr(self.lm_code_cache, "_entries"):
self.lm_code_cache._entries.pop(cache_key, None)
return None
+ # Never keep empty LM-code cache entries: force uncached regeneration so
+ # diagnostics from the LM engine are visible instead of replaying [].
+ if torch.is_tensor(cached) and cached.numel() == 0:
+ if hasattr(self.lm_code_cache, "_entries"):
+ self.lm_code_cache._entries.pop(cache_key, None)
+ return self._generate_audio_codes_uncached(
+ tags=tags,
+ lyrics=lyrics,
+ bpm=bpm,
+ duration=duration,
+ keyscale=keyscale,
+ timesignature=timesignature,
+ seed=effective_seed,
+ min_tokens=min_tokens,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ language=language,
+ negative_prompt=negative_prompt,
+ cfg_scale=cfg_scale,
+ callback=callback,
+ offloadobj=offloadobj,
+ )
+ if not torch.is_tensor(cached):
+ cached_list = list(cached)
+ if len(cached_list) == 0:
+ if hasattr(self.lm_code_cache, "_entries"):
+ self.lm_code_cache._entries.pop(cache_key, None)
+ return self._generate_audio_codes_uncached(
+ tags=tags,
+ lyrics=lyrics,
+ bpm=bpm,
+ duration=duration,
+ keyscale=keyscale,
+ timesignature=timesignature,
+ seed=effective_seed,
+ min_tokens=min_tokens,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ language=language,
+ negative_prompt=negative_prompt,
+ cfg_scale=cfg_scale,
+ callback=callback,
+ offloadobj=offloadobj,
+ )
if callback is not None:
callback(
step_idx=0,
override_num_inference_steps=1,
- denoising_extra="LM codes cached",
+ denoising_extra="Compute Audio Codes cached",
progress_unit="tokens",
)
if torch.is_tensor(cached):
@@ -1194,44 +1635,44 @@ class ACEStep15Pipeline:
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",
- )
+ with tqdm(enumerate(t_schedule), total=num_steps) as pbar:
+ for i, t in pbar:
+ 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)
+ else:
+ 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
@@ -1245,6 +1686,32 @@ class ACEStep15Pipeline:
audio_guide2=None,
audio_prompt_type="",
temperature: float = 1.0,
+ duration_seconds=None,
+ audio_duration=None,
+ num_inference_steps=None,
+ sampling_steps=None,
+ guidance_scale=7.0,
+ scheduler_type="euler",
+ seed=None,
+ batch_size=1,
+ custom_settings=None,
+ language="en",
+ top_p=0.9,
+ top_k=None,
+ callback=None,
+ audio_codes=None,
+ audio_code_hints=None,
+ lm_negative_prompt="NO USER INPUT",
+ lm_cfg_scale=None,
+ offloadobj=None,
+ audio_scale=1.0,
+ shift=1.0,
+ timesteps=None,
+ infer_method="ode",
+ vae_temporal_tiling=True,
+ vae_temporal_tile_seconds=None,
+ VAE_tile_size=None,
+ set_header_text=None,
**kwargs,
):
self._interrupt = False
@@ -1256,63 +1723,193 @@ class ACEStep15Pipeline:
lyrics = (input_prompt or "").strip()
if not lyrics:
raise ValueError("Lyrics prompt cannot be empty for ACE-Step 1.5.")
+ instrumental_only = lyrics.lower() == "[instrumental]"
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 = audio_duration
+ if duration_seconds is None or duration_seconds <= 0:
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):
+ if num_inference_steps is None:
+ num_inference_steps = sampling_steps
+ if num_inference_steps is None or num_inference_steps <= 0:
num_inference_steps = 60
- guidance_scale = kwargs.get("guidance_scale", 7.0)
- try:
- guidance_scale = float(guidance_scale)
- except (TypeError, ValueError):
+ if guidance_scale is None:
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):
+ _ = scheduler_type
+ model_mode_value = self._parse_model_mode(model_mode)
+ if seed is not None and seed < 0:
seed = None
- batch_size = kwargs.get("batch_size", 1)
- try:
- batch_size = int(batch_size)
- except (TypeError, ValueError):
+ if batch_size is None or batch_size <= 0:
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")
+ if not isinstance(custom_settings, dict):
+ custom_settings = {}
+ set_progress_status = kwargs.get("set_progress_status", None)
- duration_int = int(math.ceil(duration_seconds))
- min_tokens = duration_int * 5
+ def _update_progress_status(status_text):
+ if callable(set_progress_status):
+ try:
+ set_progress_status(status_text)
+ except Exception:
+ pass
+
+ def _phase_callback(
+ step_idx=-1,
+ latent=None,
+ force_refresh=True,
+ read_state=False,
+ override_num_inference_steps=-1,
+ pass_no=-1,
+ preview_meta=None,
+ denoising_extra="",
+ progress_unit=None,
+ ):
+ if callback is None:
+ return
+ callback(
+ step_idx=step_idx,
+ latent=latent,
+ force_refresh=force_refresh,
+ read_state=True,
+ override_num_inference_steps=override_num_inference_steps,
+ pass_no=pass_no,
+ preview_meta=preview_meta,
+ denoising_extra=denoising_extra,
+ progress_unit=progress_unit,
+ )
- top_p = kwargs.get("top_p", 0.9)
- top_k = kwargs.get("top_k", None)
+ user_bpm = self._parse_optional_int_custom_setting(custom_settings.get("bpm", None))
+ user_timesignature = self._parse_optional_int_custom_setting(custom_settings.get("timesignature", None))
+ if user_timesignature is not None and user_timesignature not in _ACE_STEP15_ALLOWED_TIMESIGNATURES:
+ user_timesignature = None
+ user_keyscale = self._normalize_optional_keyscale(custom_settings.get("keyscale", None))
+ if isinstance(user_keyscale, str):
+ user_keyscale = user_keyscale.strip()
+ if len(user_keyscale) == 0:
+ user_keyscale = None
+ user_language = custom_settings.get("language", None)
+ if user_language is not None:
+ user_language = str(user_language).strip().lower()
+ if len(user_language) == 0:
+ user_language = None
+ if user_language is None and instrumental_only:
+ user_language = "unknown"
+
+ phase1_metadata = {
+ "bpm": user_bpm,
+ "keyscale": user_keyscale,
+ "timesignature": user_timesignature,
+ "language": user_language,
+ }
+ tags_for_generation = tags
+ computed_phase1_metadata = {}
+ refined_caption = None
+ if model_mode_value == _ACE_STEP15_MODEL_MODE_DEFAULT:
+ bpm = phase1_metadata["bpm"] if phase1_metadata["bpm"] is not None else _ACE_STEP15_DEFAULT_BPM
+ timesignature = phase1_metadata["timesignature"] if phase1_metadata["timesignature"] is not None else _ACE_STEP15_DEFAULT_TIMESIGNATURE
+ if timesignature not in _ACE_STEP15_ALLOWED_TIMESIGNATURES:
+ timesignature = _ACE_STEP15_DEFAULT_TIMESIGNATURE
+ keyscale = phase1_metadata["keyscale"] if phase1_metadata["keyscale"] is not None else _ACE_STEP15_DEFAULT_KEYSCALE
+ keyscale = str(keyscale).strip()
+ if len(keyscale) == 0:
+ keyscale = _ACE_STEP15_DEFAULT_KEYSCALE
+ language = phase1_metadata["language"] if phase1_metadata["language"] is not None else "en"
+ else:
+ if not self.enable_lm:
+ raise RuntimeError("ACE-Step 1.5 model mode 1/2/3 requires an LM definition (text_encoder_URLs).")
+ missing_fields = [field_name for field_name in ("bpm", "keyscale", "timesignature", "language") if phase1_metadata.get(field_name) is None]
+ infer_language = phase1_metadata.get("language", None) is None
+ run_phase1 = model_mode_value in (_ACE_STEP15_MODEL_MODE_INFER_AND_REFINE, _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION) or (
+ model_mode_value == _ACE_STEP15_MODEL_MODE_INFER_MISSING and len(missing_fields) > 0
+ )
+ if run_phase1:
+ if self.lm_engine == "vllm" and offloadobj is not None:
+ try:
+ offloadobj.unload_all()
+ except Exception:
+ pass
+ phase1_seed = seed if seed is not None else 0
+ _update_progress_status("LM Compute Metadata")
+ phase1_metadata, refined_caption = self._run_phase1_metadata(
+ tags=tags,
+ lyrics=lyrics,
+ metadata=phase1_metadata,
+ refine_caption=model_mode_value in (_ACE_STEP15_MODEL_MODE_INFER_AND_REFINE, _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION),
+ infer_language=infer_language,
+ seed=phase1_seed,
+ cfg_scale=1.0 if lm_cfg_scale is None else float(lm_cfg_scale),
+ negative_prompt=lm_negative_prompt,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ callback=_phase_callback,
+ )
+ for field_name in missing_fields:
+ value = phase1_metadata.get(field_name, None) if phase1_metadata is not None else None
+ if value is not None:
+ computed_phase1_metadata[field_name] = value
+ if phase1_metadata is None:
+ return None
+ if model_mode_value == _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION:
+ duration_value = self._parse_optional_int_custom_setting(phase1_metadata.get("duration", None))
+ if duration_value is None:
+ raise RuntimeError("LM phase1 failed to resolve required metadata 'duration'.")
+ duration_value = max(_ACE_STEP15_DURATION_MIN_SECONDS, min(_ACE_STEP15_DURATION_MAX_SECONDS, int(duration_value)))
+ duration_seconds = float(duration_value)
+ computed_phase1_metadata["duration"] = int(duration_value)
+ if len(computed_phase1_metadata) > 0:
+ print(f"[ace_step15][phase1] computed metadata: {computed_phase1_metadata}")
+ if refined_caption is not None:
+ tags_for_generation = refined_caption
+ if refined_caption.strip() != tags.strip():
+ print(f"[ace_step15][phase1] refined caption: {refined_caption}")
+ if set_header_text is not None:
+ header_parts = []
+ if len(computed_phase1_metadata) > 0:
+ computed_bits = []
+ for field_name in ("bpm", "keyscale", "timesignature", "language", "duration"):
+ if field_name in computed_phase1_metadata:
+ computed_bits.append(f"{field_name}={computed_phase1_metadata[field_name]}")
+ if len(computed_bits) > 0:
+ header_parts.append("LM computed metadata: " + "<BR>- ".join(computed_bits))
+ if refined_caption is not None and refined_caption.strip() != tags.strip():
+ header_parts.append(f"<BR>- LM refined caption: {refined_caption}")
+ if len(header_parts) > 0:
+ try:
+ set_header_text("".join(header_parts))
+ except Exception:
+ pass
+ for field_name in ("bpm", "keyscale", "timesignature", "language"):
+ if phase1_metadata.get(field_name, None) is None:
+ raise RuntimeError(f"LM phase1 failed to resolve required metadata '{field_name}'.")
+ bpm = int(phase1_metadata["bpm"])
+ timesignature = int(phase1_metadata["timesignature"])
+ if timesignature not in _ACE_STEP15_ALLOWED_TIMESIGNATURES:
+ raise RuntimeError("LM phase1 produced an unsupported timesignature.")
+ keyscale = str(phase1_metadata["keyscale"]).strip()
+ if len(keyscale) == 0:
+ raise RuntimeError("LM phase1 produced an empty keyscale.")
+ language = str(phase1_metadata["language"]).strip().lower()
+ if len(language) == 0:
+ raise RuntimeError("LM phase1 produced an empty language.")
+ if language not in _ACE_STEP15_VALID_LANGUAGE_SET:
+ raise RuntimeError(f"LM phase1 produced unsupported language '{language}'.")
- callback = kwargs.get("callback")
+ duration_int = int(math.ceil(duration_seconds))
+ min_tokens = duration_int * 5
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")
+ user_audio_codes = audio_codes if audio_codes is not None else 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
@@ -1330,8 +1927,9 @@ class ACEStep15Pipeline:
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:
+ _update_progress_status("LM Compute Audio Codes")
audio_codes = self._generate_audio_codes(
- tags=tags,
+ tags=tags_for_generation,
lyrics=lyrics,
bpm=bpm,
duration=duration_int,
@@ -1344,27 +1942,42 @@ class ACEStep15Pipeline:
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,
+ negative_prompt=lm_negative_prompt,
+ cfg_scale=lm_cfg_scale,
+ callback=_phase_callback,
+ offloadobj=offloadobj,
)
if audio_codes is None:
return None
if len(audio_codes) == 0:
- raise RuntimeError("Audio code generation aborted or failed.")
+ failure_reason = ""
+ if self._lm_engine_impl is not None:
+ get_reason = getattr(self._lm_engine_impl, "get_last_failure_reason", None)
+ if callable(get_reason):
+ try:
+ failure_reason = str(get_reason() or "")
+ except Exception:
+ failure_reason = ""
+ extra = f" last_failure={failure_reason}" if failure_reason else ""
+ raise RuntimeError(
+ "Audio code generation returned 0 usable codes "
+ f"(engine={self.lm_engine}, tokenizer_dir='{self.lm_tokenizer_dir}', "
+ f"audio_code_vocab={len(getattr(self, '_audio_code_token_ids', []))}).{extra}"
+ )
max_code = getattr(self, "_audio_code_max", None)
- if max_code is not None:
+ if audio_codes is not None and 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]}")
+ _update_progress_status("")
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)
+ text_prompt = self._build_text_prompt(tags_for_generation, 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)
@@ -1383,11 +1996,12 @@ class ACEStep15Pipeline:
default_ref = self._default_timbre_latents(timbre_length)
src_latents = None
+ vae_options = {"vae_temporal_tiling": vae_temporal_tiling, "vae_temporal_tile_seconds": vae_temporal_tile_seconds, "VAE_tile_size": VAE_tile_size}
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)
+ src_latents = self._encode_reference_audio(audio_guide, latent_length, vae_options, 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)
+ timbre_latents = self._encode_reference_audio(audio_guide2, timbre_length, vae_options, pad_to_length=True, use_reference_processing=True)
refer_audio_latents = []
refer_audio_order_mask = []
@@ -1405,19 +2019,13 @@ class ACEStep15Pipeline:
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 = audio_scale
+ if audio_cover_strength is None:
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
@@ -1436,7 +2044,7 @@ class ACEStep15Pipeline:
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_prompt = self._build_text_prompt(tags_for_generation, 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,
@@ -1470,7 +2078,7 @@ class ACEStep15Pipeline:
return None
sampled_latents = sampled_latents.permute(0, 2, 1)
- tile_seconds = self._get_vae_temporal_tile_seconds(kwargs, duration_seconds)
+ tile_seconds = self._get_vae_temporal_tile_seconds(vae_options, duration_seconds)
tiled_audio = self._decode_latents_tiled(sampled_latents, tile_seconds)
if tiled_audio is None:
with torch.no_grad():
@@ -1483,7 +2091,37 @@ class ACEStep15Pipeline:
if audio.shape[-1] > target_samples:
audio = audio[..., :target_samples]
+ final_custom_settings = dict(custom_settings) if isinstance(custom_settings, dict) else {}
+ final_custom_settings["bpm"] = int(bpm)
+ final_custom_settings["keyscale"] = str(keyscale)
+ final_custom_settings["timesignature"] = int(timesignature)
+ final_custom_settings["language"] = str(language)
+ overridden_inputs = {
+ "custom_settings": final_custom_settings,
+ }
+ if tags_for_generation.strip() != tags.strip():
+ overridden_inputs["alt_prompt"] = tags_for_generation
+ original_caption = str(tags).strip()
+ if len(original_caption) > 0:
+ overridden_inputs["extra_info"] = {"Original Caption": original_caption}
+ if model_mode_value == _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION:
+ overridden_inputs["duration_seconds"] = int(duration_int)
+ overridden_inputs["duration"] = int(duration_int)
+ if model_mode_value in (_ACE_STEP15_MODEL_MODE_INFER_AND_REFINE, _ACE_STEP15_MODEL_MODE_INFER_REFINE_AND_DURATION):
+ overridden_inputs["model_mode"] = _ACE_STEP15_MODEL_MODE_INFER_MISSING
+
return {
"x": audio,
"audio_sampling_rate": int(self.audio_sample_rate),
+ "overridden_inputs": overridden_inputs,
}
+
+ def close(self):
+ if self._lm_engine_impl is not None:
+ close_fn = getattr(self._lm_engine_impl, "close", None)
+ if callable(close_fn):
+ try:
+ close_fn()
+ except Exception:
+ pass
+ self._lm_engine_impl = None
diff --git a/models/TTS/ace_step15/qwen3_audio_codes.py b/models/TTS/ace_step15/qwen3_audio_codes.py
new file mode 100644
index 0000000..0ee756a
--- /dev/null
+++ b/models/TTS/ace_step15/qwen3_audio_codes.py
@@ -0,0 +1,1038 @@
+"""Qwen3 LM audio-code decoding engines (legacy/pt/vllm)."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from typing import Any, Callable, Optional
+
+import torch
+
+try:
+ from transformers.generation.logits_process import LogitsProcessor, LogitsProcessorList
+except Exception: # pragma: no cover
+ class LogitsProcessor: # type: ignore
+ pass
+ LogitsProcessorList = list # type: ignore
+
+
+_AUDIO_CODE_RE = re.compile(r"<\|audio_code_(\d+)\|>")
+
+
+def _raise_if_non_finite_logits(logits: torch.Tensor, where: str) -> None:
+ non_finite = ~torch.isfinite(logits)
+ if not bool(non_finite.any()):
+ return
+ idx = torch.nonzero(non_finite, as_tuple=False)
+ first = idx[0].tolist() if idx.numel() > 0 else []
+ nan_count = int(torch.isnan(logits).sum().item())
+ posinf_count = int(torch.isposinf(logits).sum().item())
+ neginf_count = int(torch.isneginf(logits).sum().item())
+ raise RuntimeError(
+ f"[ace_step15] Non-finite logits detected at {where}: "
+ f"nan={nan_count} +inf={posinf_count} -inf={neginf_count} first_index={first}"
+ )
+
+
+def _validate_masked_logits_for_sampling(logits: torch.Tensor, where: str) -> None:
+ nan_count = int(torch.isnan(logits).sum().item())
+ posinf_count = int(torch.isposinf(logits).sum().item())
+ neginf_count = int(torch.isneginf(logits).sum().item())
+ if nan_count > 0 or posinf_count > 0:
+ bad_mask = torch.isnan(logits) | torch.isposinf(logits)
+ idx = torch.nonzero(bad_mask, as_tuple=False)
+ first = idx[0].tolist() if idx.numel() > 0 else []
+ raise RuntimeError(
+ f"[ace_step15] Non-finite logits detected at {where}: "
+ f"nan={nan_count} +inf={posinf_count} -inf={neginf_count} first_index={first}"
+ )
+ check_logits = logits.unsqueeze(0) if logits.dim() == 1 else logits
+ finite_per_row = torch.isfinite(check_logits).any(dim=-1)
+ if not bool(finite_per_row.all()):
+ bad_rows = torch.nonzero(~finite_per_row, as_tuple=False).flatten().tolist()
+ raise RuntimeError(
+ f"[ace_step15] Decoding error at {where}: all candidates are -inf for row(s) {bad_rows}."
+ )
+
+
+def _token_id_to_audio_code(token_id: int, token_map: dict[int, int], tokenizer) -> Optional[int]:
+ if token_map and token_id in token_map:
+ return token_map[token_id]
+ try:
+ token_text = tokenizer.decode([int(token_id)], skip_special_tokens=False)
+ except Exception:
+ return None
+ match = _AUDIO_CODE_RE.search(token_text)
+ if not match:
+ return None
+ try:
+ return int(match.group(1))
+ except ValueError:
+ return None
+
+
+def _postprocess_audio_codes(codes, min_tokens: int, max_tokens: int):
+ if codes is None:
+ return None
+ if len(codes) == 0:
+ return []
+ if len(codes) < min_tokens:
+ pad_val = codes[-1]
+ codes.extend([pad_val] * (min_tokens - len(codes)))
+ return codes[:max_tokens]
+
+
+def _guess_lm_model_size(model_path: str) -> str | None:
+ name = (model_path or "").lower()
+ if "0.6b" in name:
+ return "0.6B"
+ if "1.7b" in name:
+ return "1.7B"
+ if "4b" in name:
+ return "4B"
+ return None
+
+
+def _compute_vllm_gpu_utilization(model_path: str) -> float:
+ try:
+ if not torch.cuda.is_available():
+ return 0.9
+ total_gb = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3)
+ except Exception:
+ return 0.9
+ if total_gb <= 0:
+ return 0.9
+ target_map = {
+ "0.6B": 3.0,
+ "1.7B": 8.0,
+ "4B": 12.0,
+ }
+ model_size = _guess_lm_model_size(model_path)
+ target_gb = target_map.get(model_size, 3.0)
+ ratio = target_gb / total_gb
+ if total_gb >= 24:
+ return min(0.9, max(0.2, ratio))
+ return min(0.9, max(0.1, ratio))
+
+
+class AudioCodeMaskProcessor(LogitsProcessor):
+ def __init__(self, audio_code_mask: Optional[torch.Tensor]):
+ self._mask_cpu = audio_code_mask
+ self._allowed_idx_cpu = None
+ self._allowed_idx_cache = {}
+ if audio_code_mask is not None:
+ try:
+ allowed = torch.isfinite(audio_code_mask) & (audio_code_mask >= 0)
+ self._allowed_idx_cpu = torch.nonzero(allowed, as_tuple=False).flatten().to("cpu", dtype=torch.long)
+ except Exception:
+ self._allowed_idx_cpu = None
+
+ def _get_allowed_idx(self, logits: torch.Tensor) -> Optional[torch.Tensor]:
+ if self._allowed_idx_cpu is None:
+ return None
+ key = logits.device
+ cached = self._allowed_idx_cache.get(key)
+ if cached is not None:
+ return cached
+ allowed_idx = self._allowed_idx_cpu.to(device=logits.device, dtype=torch.long)
+ self._allowed_idx_cache[key] = allowed_idx
+ return allowed_idx
+
+ def __call__(self, input_ids, scores):
+ allowed_idx = self._get_allowed_idx(scores)
+ if allowed_idx is None:
+ return scores
+ if scores.dim() == 1:
+ scores = scores.unsqueeze(0)
+ squeeze_back = True
+ else:
+ squeeze_back = False
+ _raise_if_non_finite_logits(scores, "AudioCodeMaskProcessor")
+ masked_scores = torch.full_like(scores, float("-inf"))
+ masked_scores[:, allowed_idx] = scores[:, allowed_idx]
+ if squeeze_back:
+ masked_scores = masked_scores.squeeze(0)
+ return masked_scores
+
+
+def _prepare_cfg_inputs(tokenizer, prompt: str, prompt_negative: str):
+ if prompt_negative is None:
+ prompt_negative = prompt
+ pos_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
+ neg_ids = tokenizer(prompt_negative, add_special_tokens=False)["input_ids"]
+ pad_id = tokenizer.pad_token_id or tokenizer.eos_token_id or 0
+ 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])
+ return input_ids, pad_id, pos_ids
+
+
+def _apply_top_k_top_p(cfg_logits: torch.Tensor, top_k: Optional[int], top_p: Optional[float]) -> torch.Tensor:
+ 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.clone()
+ 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 = cfg_logits.clone()
+ cfg_logits[indices_to_remove] = float("-inf")
+ return cfg_logits
+
+
+def _sample_token_from_logits(
+ cfg_logits: torch.Tensor,
+ temperature: Optional[float],
+ generator: Optional[torch.Generator],
+) -> int:
+ check_logits = cfg_logits.unsqueeze(0) if cfg_logits.dim() == 1 else cfg_logits
+ nan_count = int(torch.isnan(check_logits).sum().item())
+ posinf_count = int(torch.isposinf(check_logits).sum().item())
+ if nan_count > 0 or posinf_count > 0:
+ raise RuntimeError(
+ f"[ace_step15] Decoding error before sampling: nan={nan_count} +inf={posinf_count}"
+ )
+ finite_per_row = torch.isfinite(check_logits).any(dim=-1)
+ if not bool(finite_per_row.all()):
+ bad_rows = torch.nonzero(~finite_per_row, as_tuple=False).flatten().tolist()
+ raise RuntimeError(
+ f"[ace_step15] Decoding error before sampling: all candidates are -inf for row(s) {bad_rows}."
+ )
+
+ if temperature is not None and temperature > 0:
+ scaled = cfg_logits / float(temperature)
+ next_token = torch.multinomial(torch.softmax(scaled, dim=-1), num_samples=1, generator=generator).squeeze(1)
+ else:
+ next_token = torch.argmax(cfg_logits, dim=-1)
+ return int(next_token.item())
+
+
+def _generate_token_ids_legacy(
+ model,
+ tokenizer,
+ device,
+ prompt: str,
+ prompt_negative: str,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ logits_processor: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
+ logits_processor_update_state: Optional[Callable[[int], None]] = None,
+ stop_checker: Optional[Callable[[list[int], int], bool]] = None,
+ progress_label: str = "LM tokens",
+ ignore_eos: bool = False,
+):
+ input_ids, pad_id, pos_ids = _prepare_cfg_inputs(tokenizer, prompt, prompt_negative)
+ input_ids = input_ids.to(device)
+ attention_mask = (input_ids != pad_id).to(torch.long)
+ cond_token_ids = list(pos_ids)
+
+ generator = None
+ if seed is not None and seed >= 0:
+ generator = torch.Generator(device=device)
+ generator.manual_seed(seed)
+
+ with torch.no_grad():
+ outputs = model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ use_cache=True,
+ )
+ past_key_values = outputs.past_key_values
+ next_logits = outputs.logits[:, -1]
+
+ token_ids = []
+ eos_token_id = tokenizer.eos_token_id
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"{progress_label} 0/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ for step in range(max_tokens):
+ if abort_fn is not None and abort_fn():
+ return None
+
+ cond_logits = next_logits[0:1]
+ uncond_logits = next_logits[1:2]
+ cfg_logits = uncond_logits + cfg_scale * (cond_logits - uncond_logits)
+ _raise_if_non_finite_logits(cfg_logits, "legacy_cfg_logits_pre_mask")
+
+ if logits_processor is not None:
+ seq_input_ids = torch.tensor([cond_token_ids], device=device)
+ cfg_logits = logits_processor(seq_input_ids, cfg_logits)
+ _validate_masked_logits_for_sampling(cfg_logits, "legacy_cfg_logits_post_processor")
+
+ cfg_logits = _apply_top_k_top_p(cfg_logits, top_k, top_p)
+ token_id = _sample_token_from_logits(cfg_logits, temperature, generator)
+
+ if eos_token_id is not None and token_id == int(eos_token_id) and not ignore_eos:
+ if callback is not None:
+ callback(
+ step_idx=int(step),
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"{progress_label} {step+1}/{max_tokens}",
+ progress_unit="tokens",
+ )
+ break
+
+ token_ids.append(token_id)
+ cond_token_ids.append(token_id)
+
+ if logits_processor_update_state is not None:
+ logits_processor_update_state(token_id)
+
+ if callback is not None:
+ callback(
+ step_idx=int(step),
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"{progress_label} {step+1}/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ if stop_checker is not None and stop_checker(token_ids, token_id):
+ break
+
+ next_input = torch.tensor([[token_id], [token_id]], device=device)
+ attention_mask = torch.cat(
+ [attention_mask, torch.ones((2, 1), device=device, dtype=attention_mask.dtype)],
+ dim=1,
+ )
+ with torch.no_grad():
+ outputs = 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]
+
+ return token_ids
+
+
+def generate_text_legacy(
+ model,
+ tokenizer,
+ device,
+ prompt: str,
+ prompt_negative: str,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ logits_processor: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
+ logits_processor_update_state: Optional[Callable[[int], None]] = None,
+ stop_checker: Optional[Callable[[list[int], int], bool]] = None,
+ progress_label: str = "LM text",
+ ignore_eos: bool = False,
+):
+ token_ids = _generate_token_ids_legacy(
+ model=model,
+ tokenizer=tokenizer,
+ device=device,
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=abort_fn,
+ logits_processor=logits_processor,
+ logits_processor_update_state=logits_processor_update_state,
+ stop_checker=stop_checker,
+ progress_label=progress_label,
+ ignore_eos=ignore_eos,
+ )
+ if token_ids is None:
+ return None
+ text = tokenizer.decode(token_ids, skip_special_tokens=False)
+ return {"token_ids": token_ids, "text": text}
+
+
+def generate_audio_codes_legacy(
+ model,
+ tokenizer,
+ device,
+ prompt: str,
+ prompt_negative: str,
+ audio_code_mask: Optional[torch.Tensor],
+ audio_code_token_map: dict[int, int],
+ min_tokens: int,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+):
+ mask_processor = AudioCodeMaskProcessor(audio_code_mask)
+ text_out = generate_text_legacy(
+ model=model,
+ tokenizer=tokenizer,
+ device=device,
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=abort_fn,
+ logits_processor=mask_processor,
+ progress_label="Compute Audio Codes",
+ ignore_eos=True,
+ )
+ if text_out is None:
+ return None
+
+ token_ids = text_out.get("token_ids", [])
+ audio_codes = []
+ for token_id in token_ids:
+ code_val = _token_id_to_audio_code(token_id, audio_code_token_map, tokenizer)
+ if code_val is not None:
+ audio_codes.append(code_val)
+ if len(audio_codes) >= max_tokens:
+ break
+
+ return _postprocess_audio_codes(audio_codes, min_tokens, max_tokens)
+
+
+class Qwen3PtEngine:
+ def __init__(
+ self,
+ model,
+ tokenizer,
+ device,
+ audio_code_mask: Optional[torch.Tensor],
+ audio_code_token_map: dict[int, int],
+ ):
+ self.model = model
+ self.tokenizer = tokenizer
+ self.device = device
+ self.audio_code_mask = audio_code_mask
+ self.audio_code_token_map = audio_code_token_map
+ self._mask_processor = AudioCodeMaskProcessor(audio_code_mask)
+
+ def generate_audio_codes(
+ self,
+ prompt: str,
+ prompt_negative: str,
+ min_tokens: int,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ ):
+ if cfg_scale > 1.0:
+ return generate_audio_codes_legacy(
+ self.model,
+ self.tokenizer,
+ self.device,
+ prompt,
+ prompt_negative,
+ self.audio_code_mask,
+ self.audio_code_token_map,
+ min_tokens,
+ max_tokens,
+ temperature,
+ top_p,
+ top_k,
+ cfg_scale,
+ seed,
+ callback=callback,
+ abort_fn=abort_fn,
+ )
+
+ if abort_fn is not None and abort_fn():
+ return None
+
+ inputs = self.tokenizer(prompt, return_tensors="pt", add_special_tokens=False)
+ input_ids = inputs["input_ids"].to(self.device)
+ attention_mask = inputs.get("attention_mask")
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(self.device)
+
+ generator = None
+ if seed is not None and seed >= 0:
+ generator = torch.Generator(device=self.device)
+ generator.manual_seed(seed)
+
+ logits_processors = LogitsProcessorList([self._mask_processor])
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"Compute Audio Codes 0/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ do_sample = temperature is not None and temperature > 0
+ with torch.no_grad():
+ outputs = self.model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ max_new_tokens=max_tokens,
+ do_sample=do_sample,
+ temperature=temperature if do_sample else 1.0,
+ top_k=top_k if top_k is not None and top_k > 0 else None,
+ top_p=top_p if top_p is not None and 0.0 < top_p < 1.0 else None,
+ logits_processor=logits_processors,
+ pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id,
+ generator=generator,
+ )
+
+ generated_ids = outputs[0][input_ids.shape[1]:]
+ if generated_ids.is_cuda:
+ generated_ids = generated_ids.cpu()
+
+ audio_codes = []
+ for token_id in generated_ids.tolist():
+ code_val = _token_id_to_audio_code(int(token_id), self.audio_code_token_map, self.tokenizer)
+ if code_val is not None:
+ audio_codes.append(code_val)
+ if len(audio_codes) >= max_tokens:
+ break
+
+ if callback is not None:
+ callback(
+ step_idx=max(0, max_tokens - 1),
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"Compute Audio Codes {max_tokens}/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ return _postprocess_audio_codes(audio_codes, min_tokens, max_tokens)
+
+ def generate_text(
+ self,
+ prompt: str,
+ prompt_negative: str,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ logits_processor: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None,
+ logits_processor_update_state: Optional[Callable[[int], None]] = None,
+ stop_checker: Optional[Callable[[list[int], int], bool]] = None,
+ progress_label: str = "LM text",
+ ):
+ return generate_text_legacy(
+ model=self.model,
+ tokenizer=self.tokenizer,
+ device=self.device,
+ prompt=prompt,
+ prompt_negative=prompt_negative,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ top_p=top_p,
+ top_k=top_k,
+ cfg_scale=cfg_scale,
+ seed=seed,
+ callback=callback,
+ abort_fn=abort_fn,
+ logits_processor=logits_processor,
+ logits_processor_update_state=logits_processor_update_state,
+ stop_checker=stop_checker,
+ progress_label=progress_label,
+ ignore_eos=False,
+ )
+
+
+class Qwen3VllmEngine:
+ def __init__(
+ self,
+ lm_weights_path: str,
+ tokenizer,
+ audio_code_mask: Optional[torch.Tensor],
+ audio_code_token_map: dict[int, int],
+ weight_load_mode: str = "lazy",
+ ):
+ self.lm_weights_path = lm_weights_path
+ self.tokenizer = tokenizer
+ self.audio_code_mask = audio_code_mask
+ self.audio_code_token_map = audio_code_token_map
+ self.weight_load_mode = (weight_load_mode or "lazy").lower()
+ self._llm = None
+ self._sampling_params_cls = None
+ self._model_dir = None
+ self._max_model_len_hint = None
+ self._max_num_seqs_hint = None
+ self._max_num_batched_tokens_hint = None
+ self._last_zero_code_diagnostic = None
+
+ @staticmethod
+ def _compute_runtime_hints(prompt_len: int, max_tokens: int, cfg_scale: float):
+ max_model_len = max(8, int(prompt_len) + int(max_tokens))
+ max_num_seqs = 2 if cfg_scale and cfg_scale > 1.0 else 1
+ max_num_batched_tokens = max_model_len * max_num_seqs
+ return max_model_len, max_num_seqs, max_num_batched_tokens
+
+ def _ensure_runtime_capacity(self, max_model_len: int, max_num_seqs: int, max_num_batched_tokens: int):
+ if self._max_model_len_hint is None:
+ self._max_model_len_hint = max_model_len
+ self._max_num_seqs_hint = max_num_seqs
+ self._max_num_batched_tokens_hint = max_num_batched_tokens
+ return
+
+ need_grow = (
+ max_model_len > int(self._max_model_len_hint)
+ or max_num_seqs > int(self._max_num_seqs_hint)
+ or max_num_batched_tokens > int(self._max_num_batched_tokens_hint)
+ )
+ if not need_grow:
+ return
+
+ self._max_model_len_hint = max_model_len
+ self._max_num_seqs_hint = max_num_seqs
+ self._max_num_batched_tokens_hint = max_num_batched_tokens
+ # Existing LLM was built with smaller runtime limits; rebuild safely.
+ self.close()
+
+ def _ensure_nanovllm_on_path(self):
+ llm_engines_root = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "shared", "llm_engines"))
+ if llm_engines_root not in sys.path:
+ sys.path.insert(0, llm_engines_root)
+
+ def _prepare_model_dir(self):
+ if self._model_dir is not None:
+ return self._model_dir
+
+ if not self.lm_weights_path:
+ raise RuntimeError("vllm engine requires lm_weights_path")
+
+ # For vLLM/nano-vllm, we can point directly at the weight file.
+ # nanovllm.config will derive model_dir from the file path to find config/tokenizer.
+ self._model_dir = self.lm_weights_path
+ return self._model_dir
+
+ def _ensure_llm(self):
+ if self._llm is not None:
+ return
+ # Keep online-softmax path enabled for compiled LM sampling kernels.
+ # Without this, Inductor may split reductions and emit a warning while
+ # falling back to a slower softmax lowering.
+ try:
+ import torch._inductor.config as inductor_config
+
+ if bool(getattr(inductor_config, "split_reductions", False)):
+ inductor_config.split_reductions = False
+ except Exception:
+ pass
+ self._ensure_nanovllm_on_path()
+ try:
+ from nanovllm import LLM, SamplingParams
+ except Exception as exc: # pragma: no cover
+ raise RuntimeError(f"nano-vllm is not available for vllm engine: {exc}") from exc
+
+ model_dir = self._prepare_model_dir()
+ gpu_memory_utilization = _compute_vllm_gpu_utilization(self.lm_weights_path)
+ max_model_len = self._max_model_len_hint or 4096
+ max_num_seqs = self._max_num_seqs_hint or 1
+ max_num_batched_tokens = self._max_num_batched_tokens_hint or (max_model_len * max_num_seqs)
+ self._llm = LLM(
+ model=model_dir,
+ enforce_eager=False,
+ tensor_parallel_size=1,
+ max_model_len=max_model_len,
+ max_num_seqs=max_num_seqs,
+ max_num_batched_tokens=max_num_batched_tokens,
+ gpu_memory_utilization=gpu_memory_utilization,
+ tokenizer=self.tokenizer,
+ weight_load_mode=self.weight_load_mode,
+ )
+ self._sampling_params_cls = SamplingParams
+
+ def close(self):
+ if self._llm is None:
+ return
+ try:
+ self._llm.unload_weights()
+ except Exception:
+ pass
+ try:
+ self._llm.clear_graph_cache()
+ except Exception:
+ pass
+ self._llm = None
+
+ def get_last_failure_reason(self) -> str:
+ diag = self._last_zero_code_diagnostic
+ if not diag:
+ return ""
+ return (
+ f"attempt={diag.get('attempt')} token_ids={diag.get('token_ids')} "
+ f"unmapped={diag.get('unmapped')} out_of_vocab={diag.get('out_of_vocab')} "
+ f"regex_hits={diag.get('regex_hits')} first_token_ids={diag.get('first_token_ids')} "
+ f"text_preview='{diag.get('text_preview')}'"
+ )
+
+ def __del__(self):
+ self.close()
+
+ @staticmethod
+ def _extract_text_and_tokens(output_obj) -> tuple[str, list[int]]:
+ if output_obj is None:
+ return "", []
+ if isinstance(output_obj, dict):
+ text = str(output_obj.get("text", "") or "")
+ token_ids = output_obj.get("token_ids", []) or []
+ return text, [int(x) for x in token_ids]
+ if hasattr(output_obj, "outputs"):
+ outputs = getattr(output_obj, "outputs", None)
+ if outputs and len(outputs) > 0:
+ text = str(getattr(outputs[0], "text", "") or "")
+ token_ids = getattr(outputs[0], "token_ids", None)
+ if token_ids is None:
+ token_ids = getattr(outputs[0], "token_ids_list", []) or []
+ return text, [int(x) for x in token_ids] if token_ids else []
+ text = str(getattr(output_obj, "text", "") or "")
+ token_ids = getattr(output_obj, "token_ids", None)
+ if token_ids is None:
+ token_ids = []
+ return text, [int(x) for x in token_ids]
+
+ def generate_audio_codes(
+ self,
+ prompt: str,
+ prompt_negative: str,
+ min_tokens: int,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ ):
+ if abort_fn is not None and abort_fn():
+ return None
+
+ try:
+ prompt_len = len(self.tokenizer.encode(prompt))
+ except Exception:
+ prompt_len = 0
+ # CFG runs conditional + unconditional sequences; runtime capacity must fit
+ # the longest prompt between both or decode can enter invalid states.
+ if cfg_scale > 1.0 and prompt_negative:
+ try:
+ prompt_len = max(prompt_len, len(self.tokenizer.encode(prompt_negative)))
+ except Exception:
+ pass
+ req_model_len, req_num_seqs, req_num_batched = self._compute_runtime_hints(
+ prompt_len=prompt_len,
+ max_tokens=max_tokens,
+ cfg_scale=cfg_scale,
+ )
+ self._ensure_runtime_capacity(req_model_len, req_num_seqs, req_num_batched)
+ self._ensure_llm()
+ if self._llm is None:
+ return None
+ try:
+ self._llm.reset()
+ except Exception:
+ pass
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"Compute Audio Codes 0/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ seed_value = None
+ if seed is not None:
+ try:
+ seed_value = int(seed)
+ except Exception:
+ seed_value = None
+ if seed_value is not None and seed_value < 0:
+ seed_value = None
+
+ temp = temperature if temperature is not None and temperature > 0 else 1e-5
+ sampling_params = self._sampling_params_cls(
+ temperature=temp,
+ max_tokens=max_tokens,
+ cfg_scale=max(cfg_scale, 1.0),
+ top_k=top_k if top_k is not None and top_k > 0 else None,
+ top_p=top_p if top_p is not None and 0.0 < top_p < 1.0 else None,
+ ignore_eos=True,
+ logits_processor=AudioCodeMaskProcessor(self.audio_code_mask),
+ seed=seed_value,
+ )
+
+ audio_codes = []
+ self._last_zero_code_diagnostic = None
+ for attempt in range(2):
+ outputs = self._llm.generate(
+ prompts=[prompt],
+ sampling_params=sampling_params,
+ use_tqdm=True,
+ unconditional_prompts=[prompt_negative] if cfg_scale > 1.0 else None,
+ )
+
+ token_ids = outputs[0].get("token_ids", []) if outputs else []
+ parsed_codes = []
+ unmapped_count = 0
+ out_of_vocab_count = 0
+ vocab_size = None
+ try:
+ vocab_size = len(self.tokenizer.get_vocab())
+ except Exception:
+ vocab_size = None
+ for token_id in token_ids:
+ code_val = _token_id_to_audio_code(int(token_id), self.audio_code_token_map, self.tokenizer)
+ if code_val is not None:
+ parsed_codes.append(code_val)
+ if len(parsed_codes) >= max_tokens:
+ break
+ else:
+ unmapped_count += 1
+ if vocab_size is not None and (token_id < 0 or token_id >= vocab_size):
+ out_of_vocab_count += 1
+
+ # Fallback parser: extract <|audio_code_x|> from decoded text if token_ids couldn't be mapped.
+ if len(parsed_codes) == 0 and outputs:
+ try:
+ decoded_text = str(outputs[0].get("text", ""))
+ parsed_codes = [int(x) for x in _AUDIO_CODE_RE.findall(decoded_text)]
+ if len(parsed_codes) > max_tokens:
+ parsed_codes = parsed_codes[:max_tokens]
+ except Exception:
+ parsed_codes = []
+
+ if parsed_codes:
+ audio_codes = parsed_codes
+ self._last_zero_code_diagnostic = None
+ break
+
+ decoded_text = ""
+ regex_hits = 0
+ if outputs:
+ try:
+ decoded_text = str(outputs[0].get("text", ""))
+ except Exception:
+ decoded_text = ""
+ if decoded_text:
+ try:
+ regex_hits = len(_AUDIO_CODE_RE.findall(decoded_text))
+ except Exception:
+ regex_hits = 0
+ text_preview = decoded_text[:280].replace("\n", "\\n")
+ self._last_zero_code_diagnostic = {
+ "attempt": attempt + 1,
+ "token_ids": len(token_ids),
+ "unmapped": unmapped_count,
+ "out_of_vocab": out_of_vocab_count,
+ "regex_hits": regex_hits,
+ "first_token_ids": token_ids[:24],
+ "text_preview": text_preview,
+ }
+ print(
+ f"[ace_step15][vllm][diagnostic] attempt={attempt+1} "
+ f"token_ids={len(token_ids)} parsed_codes=0 "
+ f"unmapped={unmapped_count} out_of_vocab={out_of_vocab_count} "
+ f"first_token_ids={token_ids[:24]} text_preview='{text_preview}'"
+ )
+
+ if attempt == 0:
+ print("[ace_step15] Warning: vllm LM returned 0 audio codes; rebuilding LM runtime and retrying once.")
+ self.close()
+ self._ensure_llm()
+ if self._llm is None:
+ break
+
+ if callback is not None:
+ callback(
+ step_idx=max(0, max_tokens - 1),
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"Compute Audio Codes {max_tokens}/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ if self.weight_load_mode in ("lazy", "pinned"):
+ try:
+ self._llm.unload_weights()
+ except Exception:
+ pass
+
+ return _postprocess_audio_codes(audio_codes, min_tokens, max_tokens)
+
+ def generate_text(
+ self,
+ prompt: str,
+ prompt_negative: str,
+ max_tokens: int,
+ temperature: Optional[float],
+ top_p: Optional[float],
+ top_k: Optional[int],
+ cfg_scale: float,
+ seed: Optional[int],
+ callback=None,
+ abort_fn: Optional[Callable[[], bool]] = None,
+ logits_processor: Optional[Any] = None,
+ logits_processor_update_state: Optional[Callable[[int], None]] = None,
+ stop_checker: Optional[Callable[[list[int], int], bool]] = None,
+ progress_label: str = "LM text",
+ ):
+ del stop_checker # nanovllm does not support external stop callbacks yet.
+ if abort_fn is not None and abort_fn():
+ return None
+
+ try:
+ prompt_len = len(self.tokenizer.encode(prompt))
+ except Exception:
+ prompt_len = 0
+ if cfg_scale > 1.0 and prompt_negative:
+ try:
+ prompt_len = max(prompt_len, len(self.tokenizer.encode(prompt_negative)))
+ except Exception:
+ pass
+
+ req_model_len, req_num_seqs, req_num_batched = self._compute_runtime_hints(
+ prompt_len=prompt_len,
+ max_tokens=max_tokens,
+ cfg_scale=cfg_scale,
+ )
+ self._ensure_runtime_capacity(req_model_len, req_num_seqs, req_num_batched)
+ self._ensure_llm()
+ if self._llm is None:
+ return None
+ try:
+ self._llm.reset()
+ except Exception:
+ pass
+
+ if callback is not None:
+ callback(
+ step_idx=-1,
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"{progress_label} 0/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ seed_value = None
+ if seed is not None:
+ try:
+ seed_value = int(seed)
+ except Exception:
+ seed_value = None
+ if seed_value is not None and seed_value < 0:
+ seed_value = None
+
+ temp = temperature if temperature is not None and temperature > 0 else 1e-5
+ sampling_params = self._sampling_params_cls(
+ temperature=temp,
+ max_tokens=max_tokens,
+ cfg_scale=max(cfg_scale, 1.0),
+ top_k=top_k if top_k is not None and top_k > 0 else None,
+ top_p=top_p if top_p is not None and 0.0 < top_p < 1.0 else None,
+ ignore_eos=False,
+ logits_processor=logits_processor,
+ logits_processor_update_state=logits_processor_update_state,
+ seed=seed_value,
+ )
+
+ outputs = self._llm.generate(
+ prompts=[prompt],
+ sampling_params=sampling_params,
+ use_tqdm=True,
+ unconditional_prompts=[prompt_negative] if cfg_scale > 1.0 else None,
+ )
+ text = ""
+ token_ids: list[int] = []
+ if outputs:
+ text, token_ids = self._extract_text_and_tokens(outputs[0])
+ if (not text) and token_ids:
+ try:
+ text = self.tokenizer.decode(token_ids, skip_special_tokens=False)
+ except Exception:
+ text = ""
+
+ if callback is not None:
+ callback(
+ step_idx=max(0, max_tokens - 1),
+ override_num_inference_steps=max_tokens,
+ denoising_extra=f"{progress_label} {max_tokens}/{max_tokens}",
+ progress_unit="tokens",
+ )
+
+ if self.weight_load_mode in ("lazy", "pinned"):
+ try:
+ self._llm.unload_weights()
+ except Exception:
+ pass
+
+ return {"token_ids": token_ids, "text": text}
+
+
+def create_qwen3_lm_engine(
+ engine_name: str,
+ model,
+ tokenizer,
+ device,
+ lm_weights_path: str,
+ audio_code_mask: Optional[torch.Tensor],
+ audio_code_token_map: dict[int, int],
+ weight_load_mode: str = "lazy",
+):
+ engine = (engine_name or "legacy").strip().lower()
+ if engine == "vllm":
+ if not lm_weights_path or tokenizer is None:
+ return None
+ return Qwen3VllmEngine(
+ lm_weights_path=lm_weights_path,
+ tokenizer=tokenizer,
+ audio_code_mask=audio_code_mask,
+ audio_code_token_map=audio_code_token_map,
+ weight_load_mode=weight_load_mode,
+ )
+ if engine == "pt":
+ if model is None or tokenizer is None:
+ return None
+ return Qwen3PtEngine(
+ model=model,
+ tokenizer=tokenizer,
+ device=device,
+ audio_code_mask=audio_code_mask,
+ audio_code_token_map=audio_code_token_map,
+ )
+ return None
diff --git a/models/TTS/ace_step_handler.py b/models/TTS/ace_step_handler.py
index 9a5c1ac..c4c7ddb 100644
--- a/models/TTS/ace_step_handler.py
+++ b/models/TTS/ace_step_handler.py
@@ -1,4 +1,5 @@
import os
+import re
import torch
@@ -56,6 +57,128 @@ ACE_STEP_DURATION_SLIDER = {
"default": 20,
}
+ACE_STEP15_DURATION_SLIDER = {
+ "label": "Duration (seconds)",
+ "min": 5,
+ "max": 360,
+ "increment": 1,
+ "default": 20,
+}
+
+ACE_STEP_BPM_MIN = 30
+ACE_STEP_BPM_MAX = 300
+ACE_STEP_BPM_HINT = f"Use an integer from {ACE_STEP_BPM_MIN} to {ACE_STEP_BPM_MAX} (leave empty for N/A)."
+ACE_STEP_TIME_SIGNATURE_VALUES = {2, 3, 4, 6}
+ACE_STEP_TIME_SIGNATURE_HINT = "Use a single digit supported by ACE: 2, 3, 4, or 6 (leave empty for N/A)."
+ACE_STEP_KEYSCALE_HINT = (
+ "Use <NOTE><ACCIDENTAL> <MODE> where NOTE is A/B/C/D/E/F/G, "
+ "ACCIDENTAL is optional (# or b, Unicode ♯/♭ also accepted), "
+ "and MODE is major or minor. "
+ "Short form <NOTE><ACCIDENTAL>m is also accepted. Leave empty for N/A."
+)
+ACE_STEP15_VALID_LANGUAGES = [
+ "ar", "az", "bg", "bn", "ca", "cs", "da", "de", "el", "en",
+ "es", "fa", "fi", "fr", "he", "hi", "hr", "ht", "hu", "id",
+ "is", "it", "ja", "ko", "la", "lt", "ms", "ne", "nl", "no",
+ "pa", "pl", "pt", "ro", "ru", "sa", "sk", "sr", "sv", "sw",
+ "ta", "te", "th", "tl", "tr", "uk", "ur", "vi", "yue", "zh",
+ "unknown",
+]
+ACE_STEP15_VALID_LANGUAGE_SET = set(ACE_STEP15_VALID_LANGUAGES)
+ACE_STEP15_LANGUAGE_CODES_TEXT = ", ".join(ACE_STEP15_VALID_LANGUAGES)
+ACE_STEP15_CUSTOM_SETTINGS = [
+ {
+ "id": "bpm",
+ "label": f"BPM ({ACE_STEP_BPM_MIN}-{ACE_STEP_BPM_MAX})",
+ "name": "BPM",
+ "type": "int",
+ },
+ {
+ "id": "keyscale",
+ "label": "KeyScale (C major, F# minor, ...)",
+ "name": "KeyScale",
+ "type": "text",
+ },
+ {
+ "id": "timesignature",
+ "label": "Time Signature (2,3,4,6)",
+ "name": "Time Signature",
+ "type": "int",
+ },
+ {
+ "id": "language",
+ "label": "Language (ISO code, empty = auto/en)",
+ "name": "Language",
+ "type": "text",
+ "default": "",
+ },
+]
+ACE_STEP15_MODEL_MODES = {
+ "choices": [
+ ("Generate Audio Codes based on Lyrics for better Semantic Understanding", 0),
+ ("+ Compute empty Bpm, Keyscale, Time Signature, Language using Lyrics & Music Caption", 1),
+ ("++ Refine Caption", 2),
+ ("+++ Determine Best Song Duration based on Lyrics & Music Caption", 3),
+ ],
+ "default": 0,
+ "label": "LM Chain Of Thought Preprocessing",
+}
+ACE_STEP15_SETTING_ALIASES = {
+ "bpm": "bpm",
+ "keyscale": "keyscale",
+ "key_scale": "keyscale",
+ "timesignature": "timesignature",
+ "time_signature": "timesignature",
+ "language": "language",
+ "lang": "language",
+ "language_code": "language",
+}
+ACE_STEP_V1_SAMPLE_SOLVERS = [
+ ("Euler", "euler"),
+ ("Heun", "heun"),
+ ("PingPong", "pingpong"),
+]
+
+
+def _normalize_ace_setting_name(name):
+ return re.sub(r"[^a-z0-9]+", "_", str(name or "").strip().lower()).strip("_")
+
+
+def _resolve_ace_setting_id(setting_def):
+ raw_name = setting_def.get("id") or setting_def.get("param") or setting_def.get("name") or ""
+ normalized_name = _normalize_ace_setting_name(raw_name)
+ return ACE_STEP15_SETTING_ALIASES.get(normalized_name, normalized_name)
+
+
+def _normalize_keyscale_value(value):
+ if value is None:
+ return None, None
+ keyscale = str(value).strip()
+ if len(keyscale) == 0:
+ return None, None
+ lowered = keyscale.lower()
+ if lowered in {"n/a", "na", "none"}:
+ return None, None
+ keyscale = keyscale.replace("\u266f", "#").replace("\u266d", "b")
+
+ short_minor = re.fullmatch(r"([A-Ga-g])\s*([#b]?)\s*[mM]", keyscale)
+ if short_minor:
+ note = short_minor.group(1).upper()
+ accidental = short_minor.group(2)
+ return f"{note}{accidental} minor", None
+
+ full = re.fullmatch(r"([A-Ga-g])\s*([#b]?)\s*(major|minor|maj|min)", keyscale, flags=re.IGNORECASE)
+ if not full:
+ return None, ACE_STEP_KEYSCALE_HINT
+ note = full.group(1).upper()
+ accidental = full.group(2)
+ mode = full.group(3).lower()
+ if mode == "maj":
+ mode = "major"
+ elif mode == "min":
+ mode = "minor"
+ return f"{note}{accidental} {mode}", None
+
def _get_model_path(model_def, key, default):
if not model_def:
@@ -106,6 +229,15 @@ def _is_ace_step15(base_model_type):
return base_model_type == "ace_step_v1_5"
+def _ace_step15_has_lm_definition(model_def):
+ text_encoder_urls = _get_model_path(model_def, "text_encoder_URLs", None)
+ if isinstance(text_encoder_urls, str):
+ return len(text_encoder_urls.strip()) > 0
+ if isinstance(text_encoder_urls, (list, tuple)):
+ return any(isinstance(one, str) and len(one.strip()) > 0 for one in text_encoder_urls)
+ return False
+
+
class family_handler:
@staticmethod
def query_supported_types():
@@ -148,11 +280,12 @@ class family_handler:
@staticmethod
def query_model_def(base_model_type, model_def):
if _is_ace_step15(base_model_type):
- return {
+ extra_model_def = {
"audio_only": True,
"image_outputs": False,
"sliding_window": False,
- "guidance_max_phases": 1,
+ "guidance_max_phases": 0,
+ "lock_inference_steps": True,
"no_negative_prompt": True,
"image_prompt_types_allowed": "",
"profiles_dir": ["ace_step_v1_5"],
@@ -160,31 +293,40 @@ class family_handler:
"inference_steps": True,
"temperature": True,
"any_audio_prompt": True,
- "audio_guide_label": "Reference Audio",
+ "audio_guide_label": "Source Audio",
"audio_guide2_label": "Reference Timbre",
- "audio_scale_name": "Reference Audio Strength",
+ "audio_scale_name": "Source Audio Strength",
"audio_prompt_choices": True,
"enabled_audio_lora": False,
+ "prompt_class": "Lyrics",
+ "prompt_description": "Lyrics / Prompt (Write [Instrumental] for Instrumental Generation only)",
"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",
+ "": "Text (Lyrics) 2 Audio",
+ "A": "Cover Mode of Source Audio (need to provide original Lyrics and set a Source Audio Strength)",
+ "B": "Apply Reference Timbre",
+ "AB": "Cover Mode of Source Audio + Apply Reference Timbre",
},
"default": "",
- "label": "Reference Sources",
+ "label": "Audio Task",
"letters_filter": "AB",
},
"alt_prompt": {
- "label": "Genres / Tags",
+ "label": "Music Caption (Describe the style, genre, instruments, and mood)",
+ "name": "Music Caption",
"placeholder": "disco",
"lines": 2,
},
- "duration_slider": dict(ACE_STEP_DURATION_SLIDER),
+ "duration_slider": dict(ACE_STEP15_DURATION_SLIDER),
+ "custom_settings": [one.copy() for one in ACE_STEP15_CUSTOM_SETTINGS],
"text_prompt_enhancer_instructions": HEARTMULA_LYRIC_PROMPT,
+ "text_prompt_enhancer_max_tokens": 512,
+ "prompt_enhancer_button_label": "Compose Lyrics",
}
+ if _ace_step15_has_lm_definition(model_def):
+ extra_model_def["model_modes"] = ACE_STEP15_MODEL_MODES.copy()
+ return extra_model_def
return {
"audio_only": True,
"image_outputs": False,
@@ -196,6 +338,7 @@ class family_handler:
"text_encoder_URLs": [ACE_STEP_TEXT_ENCODER_URL],
"text_encoder_folder": ACE_STEP_TEXT_ENCODER_FOLDER,
"inference_steps": True,
+ "sample_solvers": ACE_STEP_V1_SAMPLE_SOLVERS,
"temperature": False,
"any_audio_prompt": True,
"audio_guide_label": "Source Audio",
@@ -219,12 +362,13 @@ class family_handler:
},
"duration_slider": dict(ACE_STEP_DURATION_SLIDER),
"text_prompt_enhancer_instructions": HEARTMULA_LYRIC_PROMPT,
+ "prompt_enhancer_button_label": "Compose Lyrics",
}
@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))
+ enable_lm = _ace_step15_has_lm_definition(model_def)
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,
@@ -306,6 +450,7 @@ class family_handler:
submodel_no_list=None,
text_encoder_filename=None,
profile=0,
+ lm_decoder_engine="legacy",
**kwargs,
):
transformer_weights = None
@@ -337,12 +482,16 @@ class family_handler:
)
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))
- ignore_lm_cache_seed = bool(_get_model_path(model_def, "ace_step15_lm_cache_ignore_seed", True))
+ enable_lm = bool(text_encoder_filename)
+ ignore_lm_cache_seed = bool(_get_model_path(model_def, "ace_step15_lm_cache_ignore_seed", 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))
+ lm_vllm_weight_mode = _get_model_path(model_def, "ace_step15_vllm_weight_mode", "lazy")
+ if enable_lm:
+ lm_weight_name = os.path.basename(str(lm_weights)) if lm_weights else ""
+ print(f"[ace_step15] LM engine='{lm_decoder_engine}' | LM weights='{lm_weight_name}'")
pipeline = ACEStep15Pipeline(
transformer_weights_path=transformer_weights,
@@ -356,6 +505,8 @@ class family_handler:
silence_latent_path=silence_latent,
enable_lm=enable_lm,
ignore_lm_cache_seed=ignore_lm_cache_seed,
+ lm_decoder_engine=lm_decoder_engine,
+ lm_vllm_weight_mode=lm_vllm_weight_mode,
dtype=dtype or torch.bfloat16,
)
@@ -364,7 +515,7 @@ class family_handler:
"text_encoder_2": pipeline.text_encoder_2,
"codec": pipeline.audio_vae,
}
- if text_encoder_filename and pipeline.lm_model is not None:
+ if lm_decoder_engine != "vllm" and text_encoder_filename and pipeline.lm_model is not None:
pipe["text_encoder"] = pipeline.lm_model
if save_quantized and transformer_weights:
@@ -431,7 +582,6 @@ class family_handler:
"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,
@@ -443,6 +593,16 @@ class family_handler:
"audio_scale": 0.5,
}
)
+ # default_custom_settings = {}
+ # for setting_def in model_def.get("custom_settings", []):
+ # setting_id = _resolve_ace_setting_id(setting_def)
+ # default_value = setting_def.get("default", None)
+ # if default_value is None:
+ # continue
+ # if isinstance(default_value, str) and len(default_value.strip()) == 0:
+ # continue
+ # default_custom_settings[setting_id] = default_value
+ # ui_defaults["custom_settings"] = default_custom_settings if len(default_custom_settings) > 0 else None
return
ui_defaults.update(
{
@@ -451,7 +611,7 @@ class family_handler:
"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",
+ "sample_solver": ui_defaults.get("sample_solver", ui_defaults.get("scheduler_type", "euler")),
"duration_seconds": duration_def.get("default", 60),
"repeat_generation": 1,
"video_length": 0,
@@ -464,6 +624,15 @@ class family_handler:
}
)
+ @staticmethod
+ def fix_settings(base_model_type, settings_version, model_def, ui_defaults):
+ if _is_ace_step15(base_model_type):
+ return
+ if ui_defaults.get("sample_solver", "") in ("", None):
+ legacy_scheduler = ui_defaults.get("scheduler_type", "")
+ if legacy_scheduler in {"euler", "heun", "pingpong"}:
+ ui_defaults["sample_solver"] = legacy_scheduler
+
@staticmethod
def validate_generative_prompt(base_model_type, model_def, inputs, one_prompt):
if one_prompt is None or len(str(one_prompt).strip()) == 0:
@@ -472,3 +641,114 @@ class family_handler:
if "A" in audio_prompt_type and inputs.get("audio_guide") is None:
return "Reference audio is required for Only Lyrics or Remix modes."
return None
+
+ @staticmethod
+ def validate_generative_settings(base_model_type, model_def, inputs):
+ if not _is_ace_step15(base_model_type):
+ return None
+
+ raw_custom_settings = inputs.get("custom_settings", None)
+ if raw_custom_settings is None:
+ return None
+ if not isinstance(raw_custom_settings, dict):
+ return "Custom settings must be a dictionary."
+
+ canonical_custom_settings = {}
+ for raw_key, raw_value in raw_custom_settings.items():
+ canonical_key = ACE_STEP15_SETTING_ALIASES.get(_normalize_ace_setting_name(raw_key), _normalize_ace_setting_name(raw_key))
+ if len(canonical_key) == 0:
+ continue
+ canonical_custom_settings[canonical_key] = raw_value
+
+ validated_custom_settings = {}
+ for setting_def in model_def.get("custom_settings", []):
+ setting_id = _resolve_ace_setting_id(setting_def)
+ raw_value = canonical_custom_settings.get(setting_id, None)
+ if raw_value is None:
+ continue
+ if isinstance(raw_value, str):
+ raw_value = raw_value.strip()
+ if len(raw_value) == 0:
+ continue
+
+ if setting_id == "bpm":
+ try:
+ if isinstance(raw_value, bool):
+ raise ValueError()
+ if isinstance(raw_value, int):
+ bpm_value = raw_value
+ elif isinstance(raw_value, float):
+ if not raw_value.is_integer():
+ raise ValueError()
+ bpm_value = int(raw_value)
+ else:
+ bpm_as_float = float(str(raw_value).strip())
+ if not bpm_as_float.is_integer():
+ raise ValueError()
+ bpm_value = int(bpm_as_float)
+ except Exception:
+ return f"Invalid BPM. {ACE_STEP_BPM_HINT}"
+ if bpm_value < ACE_STEP_BPM_MIN or bpm_value > ACE_STEP_BPM_MAX:
+ return f"Invalid BPM. {ACE_STEP_BPM_HINT}"
+ validated_custom_settings["bpm"] = bpm_value
+ continue
+
+ if setting_id == "timesignature":
+ timesig_value = None
+ if isinstance(raw_value, bool):
+ return f"Invalid Time Signature. {ACE_STEP_TIME_SIGNATURE_HINT}"
+ if isinstance(raw_value, int):
+ timesig_value = raw_value
+ elif isinstance(raw_value, float):
+ if not raw_value.is_integer():
+ return f"Invalid Time Signature. {ACE_STEP_TIME_SIGNATURE_HINT}"
+ timesig_value = int(raw_value)
+ else:
+ time_text = str(raw_value).strip()
+ if len(time_text) == 0 or time_text.lower() in {"n/a", "na", "none"}:
+ timesig_value = None
+ else:
+ compact = time_text.replace(" ", "")
+ compact_lower = compact.lower()
+ if compact_lower in {"2/4", "3/4", "4/4", "6/8"}:
+ timesig_value = int(compact_lower.split("/", 1)[0])
+ elif compact in {"2", "3", "4", "6"}:
+ timesig_value = int(compact)
+ else:
+ return f"Invalid Time Signature. {ACE_STEP_TIME_SIGNATURE_HINT}"
+ if timesig_value is not None and timesig_value not in ACE_STEP_TIME_SIGNATURE_VALUES:
+ return f"Invalid Time Signature. {ACE_STEP_TIME_SIGNATURE_HINT}"
+ if timesig_value is not None:
+ validated_custom_settings["timesignature"] = timesig_value
+ continue
+
+ if setting_id == "keyscale":
+ normalized_keyscale, keyscale_error = _normalize_keyscale_value(raw_value)
+ if keyscale_error is not None:
+ return f"Invalid KeyScale. {keyscale_error}"
+ if normalized_keyscale is not None:
+ validated_custom_settings["keyscale"] = normalized_keyscale
+ continue
+
+ if setting_id == "language":
+ language_value = str(raw_value).strip().lower()
+ if len(language_value) == 0:
+ continue
+ if language_value not in ACE_STEP15_VALID_LANGUAGE_SET:
+ return f"Invalid Language code '{raw_value}'. Available codes: {ACE_STEP15_LANGUAGE_CODES_TEXT}"
+ validated_custom_settings["language"] = language_value
+ continue
+
+ for key, value in canonical_custom_settings.items():
+ if key in validated_custom_settings:
+ continue
+ if value is None:
+ continue
+ if isinstance(value, str):
+ value = value.strip()
+ if len(value) == 0:
+ continue
+ validated_custom_settings[key] = value
+
+ inputs["custom_settings"] = validated_custom_settings if len(validated_custom_settings) > 0 else None
+ return None
diff --git a/models/TTS/chatterbox/pipeline.py b/models/TTS/chatterbox/pipeline.py
index eaa9176..d35709c 100644
--- a/models/TTS/chatterbox/pipeline.py
+++ b/models/TTS/chatterbox/pipeline.py
@@ -51,9 +51,7 @@ class ChatterboxPipeline:
model_mode: Optional[str],
audio_guide: Optional[str],
*,
- exaggeration: float,
- pace: float,
- temperature: float,
+ temperature: float = 0.8,
repetition_penalty: float = 2.0,
min_p: float = 0.05,
top_p: float = 1.0,
@@ -64,7 +62,22 @@ class ChatterboxPipeline:
raise ValueError("Prompt text cannot be empty for Chatterbox generation.")
language_id = model_mode
- cfg_weight = pace
+ custom_settings = bkwargs.get("custom_settings", None)
+ if not isinstance(custom_settings, dict):
+ custom_settings = {}
+ raw_exaggeration = custom_settings.get("exaggeration", bkwargs.get("exaggeration", 0.5))
+ raw_pace = custom_settings.get("pace", bkwargs.get("pace", 0.5))
+ try:
+ exaggeration = float(raw_exaggeration)
+ except (TypeError, ValueError):
+ exaggeration = 0.5
+ try:
+ cfg_weight = float(raw_pace)
+ except (TypeError, ValueError):
+ cfg_weight = 0.5
+ exaggeration = min(2.0, max(0.25, exaggeration))
+ cfg_weight = min(1.0, max(0.2, cfg_weight))
+
cfg_override = bkwargs.get("cfg_scale", None)
if cfg_override is not None:
try:
diff --git a/models/TTS/chatterbox_handler.py b/models/TTS/chatterbox_handler.py
index 175a872..1afb1ae 100644
--- a/models/TTS/chatterbox_handler.py
+++ b/models/TTS/chatterbox_handler.py
@@ -48,6 +48,28 @@ def _get_language_choices() -> list[tuple[str, str]]:
for code, name in sorted(languages.items(), key=lambda item: item[1])
]
+CHATTERBOX_CUSTOM_SETTINGS_MIGRATION_VERSION = 2.50
+CHATTERBOX_DEFAULT_CUSTOM_SETTINGS = {
+ "exaggeration": 0.5,
+ "pace": 0.5,
+}
+CHATTERBOX_CUSTOM_SETTINGS = [
+ {
+ "id": "exaggeration",
+ "label": "Emotion Exaggeration (0.25-2.0, 0.5 = neutral)",
+ "name": "Exaggeration",
+ "type": "float",
+ "default": CHATTERBOX_DEFAULT_CUSTOM_SETTINGS["exaggeration"],
+ },
+ {
+ "id": "pace",
+ "label": "Pace (0.2-1.0)",
+ "name": "Pace",
+ "type": "float",
+ "default": CHATTERBOX_DEFAULT_CUSTOM_SETTINGS["pace"],
+ },
+]
+
def _get_chatterbox_model_def():
return {
@@ -67,8 +89,9 @@ def _get_chatterbox_model_def():
"label": "Language",
},
"any_audio_prompt": True,
- "chatterbox_controls": True,
+ "custom_settings": [one.copy() for one in CHATTERBOX_CUSTOM_SETTINGS],
"text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,
+ "prompt_enhancer_button_label": "Write Speech",
}
@@ -171,6 +194,29 @@ class family_handler:
if settings_version < 2.44:
ui_defaults["guidance_scale"] = 1.0
+ legacy_exaggeration = ui_defaults.pop("exaggeration", None)
+ legacy_pace = ui_defaults.pop("pace", None)
+ custom_settings = ui_defaults.get("custom_settings", None)
+ if not isinstance(custom_settings, dict):
+ custom_settings = {}
+ else:
+ custom_settings = custom_settings.copy()
+
+ if settings_version < CHATTERBOX_CUSTOM_SETTINGS_MIGRATION_VERSION:
+ if legacy_exaggeration is not None:
+ custom_settings.setdefault("exaggeration", legacy_exaggeration)
+ if legacy_pace is not None:
+ custom_settings.setdefault("pace", legacy_pace)
+
+ if legacy_exaggeration is not None and "exaggeration" not in custom_settings:
+ custom_settings["exaggeration"] = legacy_exaggeration
+ if legacy_pace is not None and "pace" not in custom_settings:
+ custom_settings["pace"] = legacy_pace
+
+ for key, value in CHATTERBOX_DEFAULT_CUSTOM_SETTINGS.items():
+ custom_settings.setdefault(key, value)
+ ui_defaults["custom_settings"] = custom_settings
+
@staticmethod
def update_default_settings(base_model_type, model_def, ui_defaults):
ui_defaults.update(
@@ -181,9 +227,8 @@ class family_handler:
"video_length": 0,
"num_inference_steps": 0,
"negative_prompt": "",
- "exaggeration": 0.5,
+ "custom_settings": dict(CHATTERBOX_DEFAULT_CUSTOM_SETTINGS),
"temperature": 0.8,
- "pace": 0.5,
"guidance_scale": 1.0,
"multi_prompts_gen_type": 2,
}
diff --git a/models/TTS/heartmula_handler.py b/models/TTS/heartmula_handler.py
index 2d74786..2961ffc 100644
--- a/models/TTS/heartmula_handler.py
+++ b/models/TTS/heartmula_handler.py
@@ -27,6 +27,7 @@ def _get_heartmula_model_def():
"lines": 2,
},
"text_prompt_enhancer_instructions": HEARTMULA_LYRIC_PROMPT,
+ "prompt_enhancer_button_label": "Compose Lyrics",
"duration_slider": {
"label": "Duration of the Song (in seconds)",
"min": 30,
diff --git a/models/TTS/kugelaudio_handler.py b/models/TTS/kugelaudio_handler.py
index bf98990..9eddf34 100644
--- a/models/TTS/kugelaudio_handler.py
+++ b/models/TTS/kugelaudio_handler.py
@@ -58,6 +58,7 @@ def _get_kugelaudio_model_def():
"default": "",
},
"text_prompt_enhancer_instructions": TTS_MONOLOGUE_OR_DIALOGUE_PROMPT,
+ "prompt_enhancer_button_label": "Write Speech",
"compile": False,
}
diff --git a/models/TTS/prompt_enhancers.py b/models/TTS/prompt_enhancers.py
index 44da743..586de57 100644
--- a/models/TTS/prompt_enhancers.py
+++ b/models/TTS/prompt_enhancers.py
@@ -46,15 +46,26 @@ TTS_MONOLOGUE_OR_DIALOGUE_PROMPT = (
HEARTMULA_LYRIC_PROMPT = (
"You are a lyric-writing assistant. Generate a clean song lyric prompt "
- "for a text-to-song model. Output only the lyric text with optional "
- "section headers in square brackets (e.g., [Verse], [Chorus], [Bridge], "
- "[Intro], [Outro]). Do not include explanations, bullet lists, or tags. "
- "Keep a consistent theme, POV, and rhyme or rhythm where natural. Use "
+ "for a text-to-song model. Output only the lyric text with section "
+ "headers in square brackets. Supported headers include [Intro], [Verse], "
+ "[Pre-Chorus], [Chorus], [Bridge], and [Outro]. Include [Intro] and/or "
+ "[Outro] when they fit the request. Keep intro and outro sections short "
+ "(1-4 lines each). Do not include explanations, bullet lists, tags, or "
+ "markdown fences. Keep a consistent theme, POV, and singable rhythm. Use "
"short lines that are easy to sing.\n\n"
"Example:\n"
+ "[Intro]\n"
+ "Streetlights fade while the dawn turns gold\n"
+ "I hear your name in the morning cold\n"
"[Verse]\n"
"Morning light through the window pane\n"
"I hum a tune to chase the rain\n"
"Steady steps on a quiet street\n"
"Heart and rhythm, gentle beat\n"
+ "[Chorus]\n"
+ "Stay with me through every mile\n"
+ "Hold this fire, hold this smile\n"
+ "[Outro]\n"
+ "Let it ring, let it fall\n"
+ "Your echo is the last call\n"
)
diff --git a/models/TTS/qwen3_handler.py b/models/TTS/qwen3_handler.py
index 34cafd8..b617387 100644
--- a/models/TTS/qwen3_handler.py
+++ b/models/TTS/qwen3_handler.py
@@ -200,6 +200,7 @@ def get_qwen3_model_def(base_model_type: str) -> dict:
"duration_slider": dict(QWEN3_TTS_DURATION_SLIDER),
"top_k_slider": True,
"text_prompt_enhancer_instructions": TTS_MONOLOGUE_PROMPT,
+ "prompt_enhancer_button_label": "Write Speech",
"compile": False,
"parent_model_type": "qwen3_tts_base",
}
diff --git a/models/_settings.json b/models/_settings.json
index 08bea2b..935d923 100644
--- a/models/_settings.json
+++ b/models/_settings.json
@@ -18,8 +18,7 @@
"audio_prompt_type": "",
"speakers_locations": "0:45 55:100",
"prompt_enhancer": "",
- "exaggeration": 0.5,
- "pace": 0.5,
+ "custom_settings": null,
"resolution": "832x480",
"batch_size": 1,
"video_length": 81,
diff --git a/models/ltx2/ltx_pipelines/distilled.py b/models/ltx2/ltx_pipelines/distilled.py
index b0ee66c..75fb0fd 100644
--- a/models/ltx2/ltx_pipelines/distilled.py
+++ b/models/ltx2/ltx_pipelines/distilled.py
@@ -1,4 +1,6 @@
import logging
+import os
+import time
from collections.abc import Callable, Iterator
import torch
@@ -42,6 +44,62 @@ from shared.utils.self_refiner import create_self_refiner_handler, normalize_sel
from shared.utils.text_encoder_cache import TextEncoderCache
device = get_device()
+_BENCH_TRANSFORMER_ENV = "WAN2GP_LTX2_BENCH_TRANSFORMER"
+
+
+def _env_flag(name: str, default: str = "0") -> bool:
+ val = os.environ.get(name, default)
+ return str(val).strip().lower() in ("1", "true", "yes", "on")
+
+
+class _TransformerBenchWrapper:
+ def __init__(self, module, enabled: bool = False) -> None:
+ self._module = module
+ self._enabled = bool(enabled)
+ self._cuda_events: list[tuple[torch.cuda.Event, torch.cuda.Event]] = []
+ self._cpu_total_ms = 0.0
+ self._cpu_calls = 0
+
+ def __getattr__(self, name):
+ return getattr(self._module, name)
+
+ def __call__(self, *args, **kwargs):
+ if not self._enabled:
+ return self._module(*args, **kwargs)
+ if torch.cuda.is_available():
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ out = self._module(*args, **kwargs)
+ end.record()
+ self._cuda_events.append((start, end))
+ return out
+
+ t0 = time.perf_counter()
+ out = self._module(*args, **kwargs)
+ self._cpu_total_ms += (time.perf_counter() - t0) * 1000.0
+ self._cpu_calls += 1
+ return out
+
+ def consume(self) -> tuple[float, int]:
+ if not self._enabled:
+ return 0.0, 0
+ if torch.cuda.is_available():
+ if not self._cuda_events:
+ return 0.0, 0
+ torch.cuda.synchronize()
+ total_ms = 0.0
+ for start, end in self._cuda_events:
+ total_ms += float(start.elapsed_time(end))
+ calls = len(self._cuda_events)
+ self._cuda_events.clear()
+ return total_ms, calls
+
+ total_ms = self._cpu_total_ms
+ calls = self._cpu_calls
+ self._cpu_total_ms = 0.0
+ self._cpu_calls = 0
+ return total_ms, calls
class DistilledPipeline:
@@ -188,8 +246,9 @@ class DistilledPipeline:
video_context, audio_context = contexts[0]
# Stage 1: Initial low resolution video generation.
+ bench_transformer = _env_flag(_BENCH_TRANSFORMER_ENV, "0")
video_encoder = self._get_model("video_encoder")
- transformer = self._get_model("transformer")
+ transformer = _TransformerBenchWrapper(self._get_model("transformer"), enabled=bench_transformer)
bind_interrupt_check(transformer, interrupt_check)
# DISTILLED_SIGMA_VALUES = [0.421875, 0]
stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device)
@@ -290,6 +349,14 @@ class DistilledPipeline:
device=self.device,
mask_context=mask_context,
)
+ stage1_transformer_ms = 0.0
+ stage1_transformer_calls = 0
+ if bench_transformer:
+ stage1_transformer_ms, stage1_transformer_calls = transformer.consume()
+ print(
+ "[WAN2GP][LTX2][bench] transformer stage1: "
+ f"{stage1_transformer_ms / 1000.0:.3f}s ({stage1_transformer_calls} calls)"
+ )
if video_state is None or audio_state is None:
return None, None
if interrupt_check is not None and interrupt_check():
@@ -392,6 +459,18 @@ class DistilledPipeline:
initial_audio_latent=audio_state.latent,
mask_context=mask_context,
)
+ if bench_transformer:
+ stage2_transformer_ms, stage2_transformer_calls = transformer.consume()
+ total_transformer_ms = stage1_transformer_ms + stage2_transformer_ms
+ total_transformer_calls = stage1_transformer_calls + stage2_transformer_calls
+ print(
+ "[WAN2GP][LTX2][bench] transformer stage2: "
+ f"{stage2_transformer_ms / 1000.0:.3f}s ({stage2_transformer_calls} calls)"
+ )
+ print(
+ "[WAN2GP][LTX2][bench] transformer total: "
+ f"{total_transformer_ms / 1000.0:.3f}s ({total_transformer_calls} calls)"
+ )
if video_state is None or audio_state is None:
return None, None
if interrupt_check is not None and interrupt_check():
diff --git a/models/wan/any2video.py b/models/wan/any2video.py
index 37bc288..38d5613 100644
--- a/models/wan/any2video.py
+++ b/models/wan/any2video.py
@@ -4,6 +4,7 @@ import logging
import math
import os
import random
+import time
import sys
import types
import math
diff --git a/plugins/wan2gp-configuration/plugin.py b/plugins/wan2gp-configuration/plugin.py
index d00b11c..1258e06 100644
--- a/plugins/wan2gp-configuration/plugin.py
+++ b/plugins/wan2gp-configuration/plugin.py
@@ -20,6 +20,7 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.request_global("default_profile_audio")
self.request_global("vae_config")
self.request_global("boost")
+ self.request_global("enable_int8_kernels")
self.request_global("preload_model_policy")
self.request_global("transformer_quantization")
self.request_global("transformer_dtype_policy")
@@ -43,6 +44,8 @@ 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")
self.request_component("model_family")
@@ -144,11 +147,21 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.transformer_dtype_policy_choice = gr.Dropdown(choices=[("Auto (Best for Hardware)", ""), ("FP16", "fp16"), ("BF16", "bf16")], value=self.transformer_dtype_policy, label="Transformer Data Type (if available)")
self.mixed_precision_choice = gr.Dropdown(choices=[("16-bit only (less VRAM)", "0"), ("Mixed 16/32-bit (better quality)", "1")], value=self.server_config.get("mixed_precision", "0"), label="Transformer Engine Precision")
self.text_encoder_quantization_choice = gr.Dropdown(choices=[("16-bit (more RAM, better quality)", "bf16"), ("8-bit (less RAM, slightly lower quality)", "int8")], value=self.text_encoder_quantization, label="Text Encoder Precision")
+ 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"),
+ ],
+ value=self.server_config.get("lm_decoder_engine", ""),
+ label="Language Models Decoder Engine",
+ )
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)
self.depth_anything_v2_variant_choice = gr.Dropdown(choices=[("Large (more precise, slower)", "vitl"), ("Big (less precise, faster)", "vitb")], value=self.server_config.get("depth_anything_v2_variant", "vitl"), label="Depth Anything v2 VACE Preprocessor")
self.vae_config_choice = gr.Dropdown(choices=[("Auto", 0), ("Disabled (fastest, high VRAM)", 1), ("256x256 Tiles (for >=8GB VRAM)", 2), ("128x128 Tiles (for >=6GB VRAM)", 3)], value=self.vae_config, label="VAE Tiling (to reduce VRAM usage)")
self.boost_choice = gr.Dropdown(choices=[("ON", 1), ("OFF", 2)], value=self.boost, label="Boost (~10% speedup for ~1GB VRAM)")
+ self.enable_int8_kernels_choice = gr.Dropdown(choices=[("Disabled", 0), ("Enabled", 1)], value=self.server_config.get("enable_int8_kernels", 0), label="Int8 Kernels (Experimental, 10% faster with INT8 quantized checkpoints, requires Triton)")
self.video_profile_choice = gr.Dropdown(
choices=self.memory_profile_choices,
value=self.default_profile_video,
@@ -177,7 +190,7 @@ class ConfigTabPlugin(WAN2GPPlugin):
with gr.Tab("Extensions"):
with gr.Group():
self.enhancer_enabled_choice = gr.Dropdown(choices=[("Off", 0), ("Florence 2 (image captioning) + LLama 3.2 3B (text generation)", 1), ("Florence 2 (image captioning) + Llama Joy 8B (uncensored, richer)", 2)], value=self.server_config.get("enhancer_enabled", 0), label="Prompt Enhancer (requires 8-14GB extra download)")
- self.enhancer_mode_choice = gr.Dropdown(choices=[("Automatic on Generation", 0), ("On-Demand Button Only", 1)], value=self.server_config.get("enhancer_mode", 0), label="Prompt Enhancer Usage")
+ self.enhancer_mode_choice = gr.Dropdown(choices=[("On-Demand Button Only", 1),("Automatic on Generation", 0)], value=self.server_config.get("enhancer_mode", 1), label="Prompt Enhancer Usage")
with gr.Row():
self.prompt_enhancer_temperature_choice = gr.Slider(
0.1,
@@ -272,8 +285,8 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.display_stats_choice, self.max_frames_multiplier_choice, self.enable_4k_resolutions_choice, self.checkpoints_paths_choice, self.loras_root_choice,
self.UI_theme_choice, self.queue_color_scheme_choice,
self.quantization_choice, self.transformer_dtype_policy_choice, self.mixed_precision_choice,
- self.text_encoder_quantization_choice, self.VAE_precision_choice, self.compile_choice,
- self.depth_anything_v2_variant_choice, self.vae_config_choice, self.boost_choice,
+ self.text_encoder_quantization_choice, self.lm_decoder_engine_choice, self.VAE_precision_choice, self.compile_choice,
+ self.depth_anything_v2_variant_choice, self.vae_config_choice, self.boost_choice, self.enable_int8_kernels_choice,
self.video_profile_choice, self.image_profile_choice, self.audio_profile_choice,
self.preload_in_VRAM_choice, self.max_reserved_loras_choice,
self.enhancer_enabled_choice, self.enhancer_mode_choice,
@@ -324,8 +337,8 @@ class ConfigTabPlugin(WAN2GPPlugin):
display_stats_choice, max_frames_multiplier_choice, enable_4k_resolutions_choice, checkpoints_paths_choice, loras_root_choice,
UI_theme_choice, queue_color_scheme_choice,
quantization_choice, transformer_dtype_policy_choice, mixed_precision_choice,
- text_encoder_quantization_choice, VAE_precision_choice, compile_choice,
- depth_anything_v2_variant_choice, vae_config_choice, boost_choice,
+ text_encoder_quantization_choice, lm_decoder_engine_choice, VAE_precision_choice, compile_choice,
+ depth_anything_v2_variant_choice, vae_config_choice, boost_choice, enable_int8_kernels_choice,
video_profile_choice, image_profile_choice, audio_profile_choice,
preload_in_VRAM_choice, max_reserved_loras_choice,
enhancer_enabled_choice, enhancer_mode_choice,
@@ -351,12 +364,13 @@ class ConfigTabPlugin(WAN2GPPlugin):
"attention_mode": attention_choice, "transformer_types": transformer_types_choices,
"text_encoder_quantization": text_encoder_quantization_choice, "save_path": save_path_choice,
"image_save_path": image_save_path_choice, "audio_save_path": audio_save_path_choice,
+ "lm_decoder_engine": lm_decoder_engine_choice,
"compile": compile_choice, "profile": video_profile_choice,
"video_profile": video_profile_choice, "image_profile": image_profile_choice, "audio_profile": audio_profile_choice,
"vae_config": vae_config_choice, "vae_precision": VAE_precision_choice,
"mixed_precision": mixed_precision_choice, "metadata_type": metadata_choice,
"transformer_quantization": quantization_choice, "transformer_dtype_policy": transformer_dtype_policy_choice,
- "boost": boost_choice, "clear_file_list": clear_file_list_choice,
+ "boost": boost_choice, "enable_int8_kernels": enable_int8_kernels_choice, "clear_file_list": clear_file_list_choice,
"preload_model_policy": preload_model_policy_choice, "UI_theme": UI_theme_choice,
"fit_canvas": fit_canvas_choice, "enhancer_enabled": enhancer_enabled_choice,
"enhancer_mode": enhancer_mode_choice, "mmaudio_mode": mmaudio_mode_choice,
@@ -400,7 +414,7 @@ class ConfigTabPlugin(WAN2GPPlugin):
changes = [k for k, v in new_server_config.items() if v != old_server_config.get(k)]
no_reload_keys = [
- "attention_mode", "vae_config", "boost", "save_path", "image_save_path", "audio_save_path",
+ "attention_mode", "vae_config", "boost", "enable_int8_kernels", "save_path", "image_save_path", "audio_save_path",
"metadata_type", "clear_file_list", "fit_canvas", "depth_anything_v2_variant",
"notification_sound_enabled", "notification_sound_volume", "mmaudio_mode",
"mmaudio_persistence", "mmaudio_enabled", "rife_version",
@@ -421,8 +435,11 @@ class ConfigTabPlugin(WAN2GPPlugin):
self.set_global("default_profile_audio", new_server_config["audio_profile"])
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"])
self.set_global("save_path", new_server_config["save_path"])
self.set_global("image_save_path", new_server_config["image_save_path"])
self.set_global("audio_save_path", new_server_config["audio_save_path"])
@@ -435,6 +452,8 @@ class ConfigTabPlugin(WAN2GPPlugin):
if "enhancer_enabled" in changes or "enhancer_mode" in changes:
self.reset_prompt_enhancer()
+ if "enable_int8_kernels" in changes:
+ self.apply_int8_kernel_setting(new_server_config["enable_int8_kernels"], True)
model_type = state["model_type"]
diff --git a/plugins/wan2gp-plugin-manager/plugin.py b/plugins/wan2gp-plugin-manager/plugin.py
index ee23a70..2d9c6d7 100644
--- a/plugins/wan2gp-plugin-manager/plugin.py
+++ b/plugins/wan2gp-plugin-manager/plugin.py
@@ -1,7 +1,6 @@
import gradio as gr
import json
import traceback
-from wgp import quit_application, WanGP_version
from shared.utils.plugins import WAN2GPPlugin, compare_release_metadata, is_wangp_compatible, plugin_id_from_url
class PluginManagerUIPlugin(WAN2GPPlugin):
@@ -10,11 +9,15 @@ class PluginManagerUIPlugin(WAN2GPPlugin):
self.name = "Plugin Manager UI"
self.version = "1.8.0"
self.description = "A built-in UI for managing, installing, and updating Wan2GP plugins"
+ self.WanGP_version = ""
+ self.quit_application = None
def setup_ui(self):
self.request_global("app")
self.request_global("server_config")
self.request_global("server_config_filename")
+ self.request_global("quit_application")
+ self.request_global("WanGP_version")
self.request_component("main")
self.request_component("main_tabs")
@@ -216,7 +219,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):
name = plugin_id_from_url(url) or "Unknown Plugin"
safe_url = url.replace("'", "\\'")
- incompatible = not is_wangp_compatible(wan2gp_version, WanGP_version)
+ incompatible = not is_wangp_compatible(wan2gp_version, self.WanGP_version)
incompat_html = ""
if incompatible and wan2gp_version:
incompat_html = (
@@ -347,7 +350,7 @@ class PluginManagerUIPlugin(WAN2GPPlugin):
bundled_badge_html = '<span class="plugin-bundled-badge" title="Bundled plugin, cannot be uninstalled">Bundled</span>'
wan2gp_version = plugin.get('wan2gp_version') or plugin.get('wangp_version', '')
- incompatible = not is_wangp_compatible(wan2gp_version, WanGP_version)
+ incompatible = not is_wangp_compatible(wan2gp_version, self.WanGP_version)
incompat_html = ''
if incompatible and wan2gp_version:
incompat_html = (
@@ -523,7 +526,10 @@ class PluginManagerUIPlugin(WAN2GPPlugin):
with open(self.server_config_filename, "w", encoding="utf-8") as writer:
writer.write(json.dumps(self.server_config, indent=4))
gr.Info("Settings saved. Restarting application...")
- quit_application()
+ if callable(getattr(self, "quit_application", None)):
+ self.quit_application()
+ return
+ gr.Warning("Restart hook is unavailable. Please restart WanGP manually.")
def _handle_save_action(self, payload_str: str):
if not payload_str:
diff --git a/requirements.txt b/requirements.txt
index f37df8c..e223030 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -64,7 +64,7 @@ pydantic==2.10.6
# Math & modeling
torchdiffeq>=0.2.5
tensordict>=0.6.1
-mmgp==3.7.3
+mmgp==3.7.4
peft==0.17.0 # 0.15.0
vector-quantize-pytorch
matplotlib
@@ -78,6 +78,7 @@ misaki
gitdb==4.0.12
gitpython==3.1.45
stringzilla==4.0.14
+xxhash
# Optional / commented out
# transformers==4.46.3 # for llamallava pre-patch
diff --git a/shared/kernels/__init__.py b/shared/kernels/__init__.py
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/shared/kernels/__init__.py
@@ -0,0 +1 @@
+
diff --git a/shared/kernels/quanto_int8_inject.py b/shared/kernels/quanto_int8_inject.py
new file mode 100644
index 0000000..94395fb
--- /dev/null
+++ b/shared/kernels/quanto_int8_inject.py
@@ -0,0 +1,720 @@
+from __future__ import annotations
+
+import importlib
+import os
+import atexit
+from types import SimpleNamespace
+from typing import Optional, Tuple
+
+import torch
+
+try:
+ from torch._subclasses.fake_tensor import is_fake as _torch_is_fake_tensor
+except Exception: # pragma: no cover
+ _torch_is_fake_tensor = None
+
+# Env toggles
+_ENV_ENABLE = "WAN2GP_QUANTO_INT8_KERNEL"
+_ENV_DEBUG = "WAN2GP_QUANTO_INT8_DEBUG"
+_ENV_ALLOW_RUNTIME_FALLBACK = "WAN2GP_QUANTO_INT8_ALLOW_RUNTIME_FALLBACK"
+_ENV_NATIVE_FALLBACK_MAX_M = "WAN2GP_QUANTO_INT8_NATIVE_FALLBACK_MAX_M"
+_ENV_PROFILE_SHAPES = "WAN2GP_QUANTO_INT8_PROFILE_SHAPES"
+_ENV_PROFILE_TIME = "WAN2GP_QUANTO_INT8_PROFILE_TIME"
+
+_STARTUP_PRINTED = False
+_RUNTIME_DISABLED = False
+_RUNTIME_DISABLE_REASON = ""
+_RUNTIME_DISABLE_PRINTED = False
+_TRITON_MODULE = None
+_TRITON_DIRECT_FUSED_READY = False
+_TRITON_DIRECT_SCALED_READY = False
+_KERNEL_USED_PRINTED = False
+_SHAPE_PROFILE_ON = False
+_SHAPE_COUNTS_FUSED = {}
+_SHAPE_COUNTS_SCALED = {}
+_TIME_PROFILE_ON = False
+_TIME_PROFILE_EVENTS = []
+_TIME_PROFILE_CPU_MS = 0.0
+_TIME_PROFILE_CALLS = 0
+
+_PATCH_STATE = SimpleNamespace(enabled=False, orig_forward=None)
+_OPS_REGISTERED = False
+_OPS_NAMESPACE = "wan2gp_int8"
+_OPS_LIBS = []
+_FUSED_LAUNCH_CACHE_MAX = 4096
+_FUSED_LAUNCH_CACHE = {}
+_FUSED_LAUNCH_CACHE_FIFO = []
+_SCALED_LAUNCH_CACHE_MAX = 4096
+_SCALED_LAUNCH_CACHE = {}
+_SCALED_LAUNCH_CACHE_FIFO = []
+_QBYTES_TENSOR_CLS = None
+_WEIGHT_QBYTES_CLS = None
+_NATIVE_FALLBACK_MAX_M = 0
+
+
+def _encode_dtype(dtype: torch.dtype) -> int:
+ if dtype == torch.float16:
+ return 1
+ if dtype == torch.float32:
+ return 2
+ return 0
+
+
+def _decode_dtype(code: int, fallback: torch.dtype = torch.bfloat16) -> torch.dtype:
+ if int(code) == 1:
+ return torch.float16
+ if int(code) == 2:
+ return torch.float32
+ return torch.bfloat16 if fallback not in (torch.bfloat16, torch.float16, torch.float32) else fallback
+
+
+def _env_flag(name: str, default: str = "1") -> bool:
+ val = os.environ.get(name, default)
+ return str(val).strip().lower() in ("1", "true", "yes", "on")
+
+
+def _env_int(name: str, default: int) -> int:
+ try:
+ return int(os.environ.get(name, str(default)))
+ except Exception:
+ return default
+
+
+def _log(msg: str) -> None:
+ print(f"[WAN2GP][INT8][quanto] {msg}")
+
+
+def _debug(msg: str) -> None:
+ if _env_flag(_ENV_DEBUG, "0"):
+ _log(msg)
+
+
+def _allow_runtime_fallback() -> bool:
+ return _env_flag(_ENV_ALLOW_RUNTIME_FALLBACK, "0")
+
+
+def _startup_status(enabled: bool, detail: str) -> None:
+ global _STARTUP_PRINTED
+ if _STARTUP_PRINTED:
+ return
+ _STARTUP_PRINTED = True
+ if enabled:
+ _log(f"Injected int8 kernels ACTIVE (backend=triton).")
+ else:
+ _log(f"Injected int8 kernels INACTIVE. {detail}")
+
+
+def _disable_runtime(reason: str) -> None:
+ global _RUNTIME_DISABLED, _RUNTIME_DISABLE_REASON, _RUNTIME_DISABLE_PRINTED
+ _RUNTIME_DISABLED = True
+ _RUNTIME_DISABLE_REASON = str(reason)
+ if not _RUNTIME_DISABLE_PRINTED:
+ _RUNTIME_DISABLE_PRINTED = True
+ _log(
+ "Runtime fallback to non-injected Quanto path after Triton failure: "
+ f"{_RUNTIME_DISABLE_REASON}"
+ )
+
+
+def _init_quanto_tensor_types() -> bool:
+ global _QBYTES_TENSOR_CLS, _WEIGHT_QBYTES_CLS
+ if _QBYTES_TENSOR_CLS is not None and _WEIGHT_QBYTES_CLS is not None:
+ return True
+ try:
+ from optimum.quanto.tensor.qbytes import QBytesTensor
+ from optimum.quanto.tensor.weights.qbytes import WeightQBytesTensor
+ except Exception:
+ return False
+ _QBYTES_TENSOR_CLS = QBytesTensor
+ _WEIGHT_QBYTES_CLS = WeightQBytesTensor
+ return True
+
+
+def _refresh_triton_direct_kernel_flags() -> None:
+ global _TRITON_DIRECT_FUSED_READY, _TRITON_DIRECT_SCALED_READY
+ mod = _TRITON_MODULE
+ triton_ns = getattr(mod, "triton", None) if mod is not None else None
+ has_common = bool(mod is not None and triton_ns is not None and hasattr(triton_ns, "cdiv") and hasattr(mod, "_select_triton_int8_config"))
+ _TRITON_DIRECT_FUSED_READY = bool(has_common and hasattr(mod, "_fused_dynamic_int8_blockscale_gemm_kernel"))
+ _TRITON_DIRECT_SCALED_READY = bool(has_common and hasattr(mod, "_scaled_int8_gemm_kernel"))
+
+
+def _is_qbytes_tensor(t: torch.Tensor) -> bool:
+ if not _init_quanto_tensor_types():
+ return False
+ return isinstance(t, _QBYTES_TENSOR_CLS)
+
+
+def _is_weight_qbytes(t: torch.Tensor) -> bool:
+ if not _init_quanto_tensor_types():
+ return False
+ return isinstance(t, _WEIGHT_QBYTES_CLS)
+
+
+def _flatten_scale(scale: torch.Tensor) -> torch.Tensor:
+ if scale.ndim == 2 and scale.shape[1] == 1:
+ return scale.view(-1)
+ if scale.ndim == 1:
+ return scale
+ return scale.reshape(-1)
+
+
+def _expand_scale_to_rows(scale: torch.Tensor, rows: int, dtype: torch.dtype, device: Optional[torch.device] = None) -> torch.Tensor:
+ scale = _flatten_scale(scale)
+ if scale.numel() == 1:
+ scale = scale.reshape(1).expand(rows)
+ elif scale.numel() != rows:
+ raise RuntimeError(f"Activation scale length mismatch: expected {rows}, got {scale.numel()}")
+ if device is None:
+ return scale.contiguous().to(dtype=dtype)
+ return scale.contiguous().to(device=device, dtype=dtype, non_blocking=True)
+
+
+def _prepare_weight_scale(scale: torch.Tensor, out_features: int, device: torch.device) -> torch.Tensor:
+ flat_scale = _flatten_scale(scale)
+ if flat_scale.numel() != out_features:
+ raise RuntimeError("Weight scale length does not match output features")
+ if flat_scale.device != device:
+ flat_scale = flat_scale.to(device=device, non_blocking=True)
+ if flat_scale.dtype != torch.float32:
+ flat_scale = flat_scale.to(torch.float32)
+ if not flat_scale.is_contiguous():
+ flat_scale = flat_scale.contiguous()
+ return flat_scale
+
+
+def _cache_launch_params(cache: dict, fifo: list, max_size: int, key: tuple[int, int, int, int], params: tuple[int, int, int, int, int, int, int]) -> tuple[int, int, int, int, int, int, int]:
+ if key in cache:
+ return cache[key]
+ cache[key] = params
+ fifo.append(key)
+ if len(fifo) > max_size:
+ stale_key = fifo.pop(0)
+ cache.pop(stale_key, None)
+ return params
+
+
+def _fused_launch_params(m: int, k: int, n: int, device: torch.device) -> tuple[int, int, int, int, int, int, int]:
+ device_index = int(device.index if device.type == "cuda" else -1)
+ key = (device_index, m, k, n)
+ cached = _FUSED_LAUNCH_CACHE.get(key)
+ if cached is not None:
+ return cached
+ mod = _TRITON_MODULE
+ if mod is None:
+ raise RuntimeError("Triton backend not initialized")
+ block_m, block_n, block_k, num_warps, num_stages = mod._select_triton_int8_config(m, k, n, device=device, kernel_kind="fused")
+ grid_m = mod.triton.cdiv(m, block_m)
+ grid_n = mod.triton.cdiv(n, block_n)
+ params = (block_m, block_n, block_k, num_warps, num_stages, grid_m, grid_n)
+ return _cache_launch_params(_FUSED_LAUNCH_CACHE, _FUSED_LAUNCH_CACHE_FIFO, _FUSED_LAUNCH_CACHE_MAX, key, params)
+
+
+def _scaled_launch_params(m: int, k: int, n: int, device: torch.device) -> tuple[int, int, int, int, int, int, int]:
+ device_index = int(device.index if device.type == "cuda" else -1)
+ key = (device_index, m, k, n)
+ cached = _SCALED_LAUNCH_CACHE.get(key)
+ if cached is not None:
+ return cached
+ mod = _TRITON_MODULE
+ if mod is None:
+ raise RuntimeError("Triton backend not initialized")
+ block_m, block_n, block_k, num_warps, num_stages = mod._select_triton_int8_config(m, k, n, device=device, kernel_kind="scaled")
+ grid_m = mod.triton.cdiv(m, block_m)
+ grid_n = mod.triton.cdiv(n, block_n)
+ params = (block_m, block_n, block_k, num_warps, num_stages, grid_m, grid_n)
+ return _cache_launch_params(_SCALED_LAUNCH_CACHE, _SCALED_LAUNCH_CACHE_FIFO, _SCALED_LAUNCH_CACHE_MAX, key, params)
+
+
+def _is_compiling_graph() -> bool:
+ try:
+ if bool(torch.compiler.is_compiling()):
+ return True
+ except Exception:
+ pass
+ try:
+ import torch._dynamo as _dynamo
+
+ if bool(_dynamo.is_compiling()):
+ return True
+ except Exception:
+ pass
+ return False
+
+
+def _is_fake_tensor(t: object) -> bool:
+ if not torch.is_tensor(t):
+ return False
+ if _torch_is_fake_tensor is not None:
+ return bool(_torch_is_fake_tensor(t))
+ return False
+
+
+def _resolve_output_dtype(input: torch.Tensor, other: torch.Tensor) -> torch.dtype:
+ other_scale = getattr(other, "_scale", None)
+ if torch.is_tensor(other_scale) and other_scale.dtype in (torch.bfloat16, torch.float16, torch.float32):
+ return other_scale.dtype
+ if _is_qbytes_tensor(input):
+ input_scale = getattr(input, "_scale", None)
+ if torch.is_tensor(input_scale) and input_scale.dtype in (torch.bfloat16, torch.float16, torch.float32):
+ return input_scale.dtype
+ if isinstance(input, torch.Tensor) and input.dtype in (torch.bfloat16, torch.float16, torch.float32):
+ return input.dtype
+ return torch.bfloat16
+
+
+def _probe_triton_backend() -> Tuple[Optional[object], str]:
+ try:
+ mod = importlib.import_module("shared.kernels.quanto_int8_triton")
+ except Exception as exc:
+ return None, f"failed to import shared.kernels.quanto_int8_triton ({exc})"
+
+ if not hasattr(mod, "is_available"):
+ return None, "shared.kernels.quanto_int8_triton.is_available() missing"
+ try:
+ if not bool(mod.is_available()):
+ return None, "Triton backend unavailable on this runtime/GPU"
+ except Exception as exc:
+ return None, f"Triton availability check failed ({exc})"
+ return mod, "ok"
+
+
+def _register_int8_ops_for_namespace(ns: str, lib: torch.library.Library) -> None:
+ lib.define("fused_quant_scaled_mm(Tensor x2d, Tensor qweight, Tensor qweight_scale, int out_dtype_code=0) -> Tensor")
+ lib.define("scaled_int8_mm(Tensor a_int8, Tensor b_int8, Tensor a_scale, Tensor b_scale, int out_dtype_code=0) -> Tensor")
+
+ @torch.library.impl(f"{ns}::fused_quant_scaled_mm", "CUDA")
+ def _fused_quant_scaled_mm_cuda(x2d: torch.Tensor, qweight: torch.Tensor, qweight_scale: torch.Tensor, out_dtype_code: int = 0):
+ if _TRITON_MODULE is None:
+ raise RuntimeError("Triton backend not initialized")
+ out_dtype = _decode_dtype(out_dtype_code, x2d.dtype)
+ return _TRITON_MODULE.fused_quant_scaled_mm(x2d, qweight, qweight_scale, out_dtype=out_dtype)
+
+ @torch.library.impl(f"{ns}::scaled_int8_mm", "CUDA")
+ def _scaled_int8_mm_cuda(a_int8: torch.Tensor, b_int8: torch.Tensor, a_scale: torch.Tensor, b_scale: torch.Tensor, out_dtype_code: int = 0):
+ if _TRITON_MODULE is None:
+ raise RuntimeError("Triton backend not initialized")
+ out_dtype = _decode_dtype(out_dtype_code, torch.bfloat16)
+ return _TRITON_MODULE.scaled_int8_mm(a_int8, b_int8, a_scale, b_scale, out_dtype=out_dtype)
+
+ @torch.library.register_fake(f"{ns}::fused_quant_scaled_mm")
+ def _fused_quant_scaled_mm_fake(x2d: torch.Tensor, qweight: torch.Tensor, qweight_scale: torch.Tensor, out_dtype_code: int = 0):
+ if x2d.ndim != 2 or qweight.ndim != 2:
+ raise RuntimeError("fused_quant_scaled_mm expects 2D tensors")
+ out_dtype = _decode_dtype(out_dtype_code, x2d.dtype)
+ return x2d.new_empty((x2d.shape[0], qweight.shape[0]), dtype=out_dtype)
+
+ @torch.library.register_fake(f"{ns}::scaled_int8_mm")
+ def _scaled_int8_mm_fake(a_int8: torch.Tensor, b_int8: torch.Tensor, a_scale: torch.Tensor, b_scale: torch.Tensor, out_dtype_code: int = 0):
+ if a_int8.ndim != 2 or b_int8.ndim != 2:
+ raise RuntimeError("scaled_int8_mm expects 2D tensors")
+ out_dtype = _decode_dtype(out_dtype_code, torch.bfloat16)
+ return a_int8.new_empty((a_int8.shape[0], b_int8.shape[0]), dtype=out_dtype)
+
+
+def _ensure_compile_safe_ops() -> None:
+ global _OPS_REGISTERED, _OPS_LIBS
+ if _OPS_REGISTERED:
+ return
+
+ libs = []
+ try:
+ lib = torch.library.Library(_OPS_NAMESPACE, "DEF")
+ libs.append(lib)
+ _register_int8_ops_for_namespace(_OPS_NAMESPACE, lib)
+ except Exception:
+ # Namespace/op may already exist in long-lived processes.
+ op_ns = getattr(torch.ops, _OPS_NAMESPACE, None)
+ has_ops = bool(
+ op_ns is not None
+ and hasattr(op_ns, "fused_quant_scaled_mm")
+ and hasattr(op_ns, "scaled_int8_mm")
+ )
+ if not has_ops:
+ raise
+ _OPS_LIBS = libs
+
+ _OPS_REGISTERED = True
+
+
+def _fused_quant_scaled_mm_direct_call(x2d: torch.Tensor, qweight: torch.Tensor, qweight_scale: torch.Tensor, output_dtype: torch.dtype) -> torch.Tensor:
+ mod = _TRITON_MODULE
+ if mod is None:
+ raise RuntimeError("Triton backend not initialized")
+ if not _TRITON_DIRECT_FUSED_READY:
+ return mod.fused_quant_scaled_mm(x2d, qweight, qweight_scale, out_dtype=output_dtype)
+
+ m, k = x2d.shape
+ n, k2 = qweight.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: x={x2d.shape}, w={qweight.shape}")
+
+ block_m, block_n, block_k, num_warps, num_stages, grid_m, grid_n = _fused_launch_params(m, k, n, x2d.device)
+ out = torch.empty((m, n), device=x2d.device, dtype=output_dtype)
+ mod._fused_dynamic_int8_blockscale_gemm_kernel[(grid_m, grid_n)](
+ x2d,
+ qweight,
+ qweight_scale,
+ out,
+ m,
+ n,
+ k,
+ x2d.stride(0),
+ x2d.stride(1),
+ qweight.stride(0),
+ qweight.stride(1),
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+ return out
+
+
+def _scaled_int8_mm_direct_call(
+ a_int8: torch.Tensor,
+ b_int8: torch.Tensor,
+ a_scale: torch.Tensor,
+ b_scale: torch.Tensor,
+ output_dtype: torch.dtype,
+) -> torch.Tensor:
+ mod = _TRITON_MODULE
+ if mod is None:
+ raise RuntimeError("Triton backend not initialized")
+ if not _TRITON_DIRECT_SCALED_READY:
+ return mod.scaled_int8_mm(a_int8, b_int8, a_scale, b_scale, out_dtype=output_dtype)
+
+ m, k = a_int8.shape
+ n, k2 = b_int8.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: a={a_int8.shape}, w={b_int8.shape}")
+
+ block_m, block_n, block_k, num_warps, num_stages, grid_m, grid_n = _scaled_launch_params(m, k, n, a_int8.device)
+ out = torch.empty((m, n), device=a_int8.device, dtype=output_dtype)
+ mod._scaled_int8_gemm_kernel[(grid_m, grid_n)](
+ a_int8,
+ b_int8,
+ a_scale,
+ b_scale,
+ out,
+ m,
+ n,
+ k,
+ a_int8.stride(0),
+ a_int8.stride(1),
+ b_int8.stride(0),
+ b_int8.stride(1),
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+ return out
+
+
+def _fused_quant_scaled_mm_call(x2d: torch.Tensor, qweight: torch.Tensor, qweight_scale: torch.Tensor, output_dtype: torch.dtype) -> torch.Tensor:
+ if _TRITON_MODULE is not None and not _is_compiling_graph() and not (_is_fake_tensor(x2d) or _is_fake_tensor(qweight) or _is_fake_tensor(qweight_scale)):
+ return _fused_quant_scaled_mm_direct_call(x2d, qweight, qweight_scale, output_dtype)
+ return torch.ops.wan2gp_int8.fused_quant_scaled_mm(x2d, qweight, qweight_scale, _encode_dtype(output_dtype))
+
+
+def _scaled_int8_mm_call(
+ a_int8: torch.Tensor,
+ b_int8: torch.Tensor,
+ a_scale: torch.Tensor,
+ b_scale: torch.Tensor,
+ output_dtype: torch.dtype,
+) -> torch.Tensor:
+ if _TRITON_MODULE is not None and not _is_compiling_graph() and not ( _is_fake_tensor(a_int8) or _is_fake_tensor(b_int8) or _is_fake_tensor(a_scale) or _is_fake_tensor(b_scale)):
+ return _scaled_int8_mm_direct_call(a_int8, b_int8, a_scale, b_scale, output_dtype)
+ return torch.ops.wan2gp_int8.scaled_int8_mm(a_int8, b_int8, a_scale, b_scale, _encode_dtype(output_dtype))
+
+
+def _use_int8_kernel(input: torch.Tensor, other: torch.Tensor) -> bool:
+ if _RUNTIME_DISABLED:
+ return False
+ if _TRITON_MODULE is None:
+ return False
+ if not _is_weight_qbytes(other):
+ return False
+ if other._data.dtype != torch.int8:
+ return False
+ if not other._data.is_cuda:
+ return False
+
+ if _is_qbytes_tensor(input):
+ return input._data.dtype == torch.int8 and input._data.is_cuda
+ return input.is_cuda and input.dtype in (torch.bfloat16, torch.float16, torch.float32)
+
+
+def _activation_rows(input_shape: torch.Size) -> int:
+ rows = 1
+ for dim in input_shape[:-1]:
+ rows *= int(dim)
+ return rows
+
+
+def _prefer_native_quanto_path(input: torch.Tensor) -> bool:
+ if _NATIVE_FALLBACK_MAX_M < 0:
+ return False
+ return _activation_rows(input.shape) <= _NATIVE_FALLBACK_MAX_M
+
+
+def _mark_kernel_used() -> None:
+ global _KERNEL_USED_PRINTED
+ if _KERNEL_USED_PRINTED:
+ return
+ _KERNEL_USED_PRINTED = True
+ _log("Injected Triton int8 kernels are being used.")
+
+
+def _int8_linear_forward_triton_dense_fast(ctx, input: torch.Tensor, other: torch.Tensor, bias: Optional[torch.Tensor]):
+ ctx.save_for_backward(input, other)
+ if _TRITON_MODULE is None:
+ raise RuntimeError("Triton backend not initialized")
+ _mark_kernel_used()
+
+ input_shape = input.shape
+ in_features = int(input_shape[-1])
+ out_features = int(other.shape[0])
+ a_2d = input.reshape(-1, in_features)
+ if not a_2d.is_contiguous():
+ a_2d = a_2d.contiguous()
+ b_int8 = other._data
+ if not b_int8.is_contiguous():
+ b_int8 = b_int8.contiguous()
+ b_scale = _prepare_weight_scale(other._scale, out_features, b_int8.device)
+
+ if _SHAPE_PROFILE_ON:
+ key = (int(a_2d.shape[0]), int(in_features), int(out_features))
+ _SHAPE_COUNTS_FUSED[key] = _SHAPE_COUNTS_FUSED.get(key, 0) + 1
+ if _TIME_PROFILE_ON and torch.cuda.is_available():
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ out_2d = _fused_quant_scaled_mm_call(a_2d, b_int8, b_scale, input.dtype)
+ end.record()
+ _TIME_PROFILE_EVENTS.append((start, end))
+ else:
+ out_2d = _fused_quant_scaled_mm_call(a_2d, b_int8, b_scale, input.dtype)
+
+ out = out_2d.reshape(input_shape[:-1] + (out_features,))
+ if bias is not None:
+ out = out + bias
+ return out
+
+
+def _int8_linear_forward_triton(ctx, input: torch.Tensor, other: torch.Tensor, bias: Optional[torch.Tensor]):
+ ctx.save_for_backward(input, other)
+ if _TRITON_MODULE is None:
+ raise RuntimeError("Triton backend not initialized")
+ _mark_kernel_used()
+
+ input_shape = input.shape
+ in_features = int(input_shape[-1])
+ out_features = int(other.shape[0])
+ b_int8 = other._data
+ if not b_int8.is_contiguous():
+ b_int8 = b_int8.contiguous()
+ b_scale = _prepare_weight_scale(other._scale, out_features, b_int8.device)
+ output_dtype = _resolve_output_dtype(input, other)
+ input_is_qbytes = _is_qbytes_tensor(input)
+
+ if input_is_qbytes:
+ a_int8 = input._data.reshape(-1, in_features)
+ if a_int8.dtype != torch.int8:
+ raise RuntimeError("QBytes input must be int8 for injected path")
+ if not a_int8.is_contiguous():
+ a_int8 = a_int8.contiguous()
+ a_scale = _expand_scale_to_rows(input._scale, a_int8.shape[0], torch.float32, device=a_int8.device)
+ if _SHAPE_PROFILE_ON:
+ key = (int(a_int8.shape[0]), int(in_features), int(out_features))
+ _SHAPE_COUNTS_SCALED[key] = _SHAPE_COUNTS_SCALED.get(key, 0) + 1
+ if _TIME_PROFILE_ON and torch.cuda.is_available():
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ out_2d = _scaled_int8_mm_call(a_int8, b_int8, a_scale, b_scale, output_dtype)
+ end.record()
+ _TIME_PROFILE_EVENTS.append((start, end))
+ else:
+ out_2d = _scaled_int8_mm_call(a_int8, b_int8, a_scale, b_scale, output_dtype)
+ else:
+ a_2d = input.reshape(-1, in_features)
+ if not a_2d.is_contiguous():
+ a_2d = a_2d.contiguous()
+ if _SHAPE_PROFILE_ON:
+ key = (int(a_2d.shape[0]), int(in_features), int(out_features))
+ _SHAPE_COUNTS_FUSED[key] = _SHAPE_COUNTS_FUSED.get(key, 0) + 1
+ if _TIME_PROFILE_ON and torch.cuda.is_available():
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ out_2d = _fused_quant_scaled_mm_call(a_2d, b_int8, b_scale, output_dtype)
+ end.record()
+ _TIME_PROFILE_EVENTS.append((start, end))
+ else:
+ out_2d = _fused_quant_scaled_mm_call(a_2d, b_int8, b_scale, output_dtype)
+
+ out = out_2d.reshape(input_shape[:-1] + (out_features,))
+ if bias is not None:
+ out = out + bias
+ return out
+
+
+def enable_quanto_int8_kernel(triton_mod=None) -> bool:
+ global _TRITON_MODULE, _NATIVE_FALLBACK_MAX_M
+ if _PATCH_STATE.enabled:
+ return True
+
+ try:
+ from optimum.quanto.tensor.weights import qbytes as _qbytes
+ except Exception as exc:
+ _debug(f"cannot import optimum.quanto qbytes ({exc})")
+ return False
+
+ if triton_mod is None:
+ triton_mod, _ = _probe_triton_backend()
+ if triton_mod is None:
+ return False
+ _TRITON_MODULE = triton_mod
+ _refresh_triton_direct_kernel_flags()
+ _NATIVE_FALLBACK_MAX_M = _env_int(_ENV_NATIVE_FALLBACK_MAX_M, 0)
+ _init_quanto_tensor_types()
+ _ensure_compile_safe_ops()
+
+ orig_forward = _qbytes.WeightQBytesLinearFunction.forward
+
+ def forward(ctx, input, other, bias=None):
+ dense_hot_path = (
+ not _RUNTIME_DISABLED
+ and type(input) is torch.Tensor
+ and input.is_cuda
+ and input.dtype in (torch.bfloat16, torch.float16, torch.float32)
+ and _WEIGHT_QBYTES_CLS is not None
+ and isinstance(other, _WEIGHT_QBYTES_CLS)
+ and other._data.dtype == torch.int8
+ and other._data.is_cuda
+ )
+ if dense_hot_path:
+ if _prefer_native_quanto_path(input):
+ return orig_forward(ctx, input, other, bias)
+ try:
+ return _int8_linear_forward_triton_dense_fast(ctx, input, other, bias)
+ except Exception as exc:
+ if _allow_runtime_fallback():
+ _disable_runtime(str(exc))
+ return orig_forward(ctx, input, other, bias)
+ raise RuntimeError(
+ "Injected Triton int8 kernel failed. "
+ f"Set {_ENV_ALLOW_RUNTIME_FALLBACK}=1 to force fallback to non-injected Quanto path. "
+ f"Original error: {exc}"
+ ) from exc
+
+ if not _use_int8_kernel(input, other):
+ return orig_forward(ctx, input, other, bias)
+ if _prefer_native_quanto_path(input):
+ return orig_forward(ctx, input, other, bias)
+ try:
+ return _int8_linear_forward_triton(ctx, input, other, bias)
+ except Exception as exc:
+ if _allow_runtime_fallback():
+ _disable_runtime(str(exc))
+ return orig_forward(ctx, input, other, bias)
+ raise RuntimeError(
+ "Injected Triton int8 kernel failed. "
+ f"Set {_ENV_ALLOW_RUNTIME_FALLBACK}=1 to force fallback to non-injected Quanto path. "
+ f"Original error: {exc}"
+ ) from exc
+
+ _qbytes.WeightQBytesLinearFunction.forward = staticmethod(forward)
+ _PATCH_STATE.enabled = True
+ _PATCH_STATE.orig_forward = orig_forward
+ return True
+
+
+def disable_quanto_int8_kernel(notify_disabled = False) -> bool:
+ global _FUSED_LAUNCH_CACHE, _FUSED_LAUNCH_CACHE_FIFO, _SCALED_LAUNCH_CACHE, _SCALED_LAUNCH_CACHE_FIFO
+ global _TRITON_DIRECT_FUSED_READY, _TRITON_DIRECT_SCALED_READY, _STARTUP_PRINTED
+
+ if not _PATCH_STATE.enabled:
+ return False
+ from optimum.quanto.tensor.weights import qbytes as _qbytes
+
+ _qbytes.WeightQBytesLinearFunction.forward = staticmethod(_PATCH_STATE.orig_forward)
+ _PATCH_STATE.enabled = False
+ _PATCH_STATE.orig_forward = None
+ _FUSED_LAUNCH_CACHE = {}
+ _FUSED_LAUNCH_CACHE_FIFO = []
+ _SCALED_LAUNCH_CACHE = {}
+ _SCALED_LAUNCH_CACHE_FIFO = []
+ _TRITON_DIRECT_FUSED_READY = False
+ _TRITON_DIRECT_SCALED_READY = False
+ _STARTUP_PRINTED = False
+ if notify_disabled:
+ _startup_status(False, f"disabled by User.")
+ return True
+
+
+def maybe_enable_quanto_int8_kernel() -> bool:
+ global _SHAPE_PROFILE_ON, _TIME_PROFILE_ON, _STARTUP_PRINTED
+
+ _STARTUP_PRINTED = False
+ if not _env_flag(_ENV_ENABLE, "1"):
+ # _startup_status(False, f"disabled by {_ENV_ENABLE}=0; using non-injected Quanto path.")
+ return False
+
+ triton_mod, reason = _probe_triton_backend()
+ if triton_mod is None:
+ # _startup_status(False, f"{reason}; using non-injected Quanto path.")
+ return False
+
+ if not enable_quanto_int8_kernel(triton_mod=triton_mod):
+ _startup_status(False, "failed to patch Quanto linear forward; using non-injected Quanto path.")
+ return False
+
+ _SHAPE_PROFILE_ON = _env_flag(_ENV_PROFILE_SHAPES, "0")
+ _TIME_PROFILE_ON = _env_flag(_ENV_PROFILE_TIME, "0")
+ _startup_status(
+ True,
+ (
+ "Triton int8 kernels will be used for Quanto qint8 linear layers "
+ "(QBytes int8 activations + fused dynamic int8 activation quantization)."
+ ),
+ )
+ return True
+
+
+
+def _print_shape_profile() -> None:
+ if not _SHAPE_PROFILE_ON and not _TIME_PROFILE_ON:
+ return
+ if _SHAPE_PROFILE_ON and _SHAPE_COUNTS_FUSED:
+ top_fused = sorted(_SHAPE_COUNTS_FUSED.items(), key=lambda kv: kv[1], reverse=True)[:10]
+ _log(f"Fused shape profile (top {len(top_fused)}): {top_fused}")
+ if _SHAPE_PROFILE_ON and _SHAPE_COUNTS_SCALED:
+ top_scaled = sorted(_SHAPE_COUNTS_SCALED.items(), key=lambda kv: kv[1], reverse=True)[:10]
+ _log(f"Scaled shape profile (top {len(top_scaled)}): {top_scaled}")
+
+ if _TIME_PROFILE_ON:
+ total_ms = 0.0
+ calls = 0
+ if _TIME_PROFILE_EVENTS:
+ if torch.cuda.is_available():
+ torch.cuda.synchronize()
+ for start, end in _TIME_PROFILE_EVENTS:
+ total_ms += float(start.elapsed_time(end))
+ calls = len(_TIME_PROFILE_EVENTS)
+ else:
+ total_ms = _TIME_PROFILE_CPU_MS
+ calls = _TIME_PROFILE_CALLS
+ _log(f"Triton kernel time profile: {total_ms / 1000.0:.3f}s over {calls} calls")
+
+
+atexit.register(_print_shape_profile)
diff --git a/shared/kernels/quanto_int8_triton.py b/shared/kernels/quanto_int8_triton.py
new file mode 100644
index 0000000..b203d12
--- /dev/null
+++ b/shared/kernels/quanto_int8_triton.py
@@ -0,0 +1,1090 @@
+from __future__ import annotations
+
+import atexit
+import json
+import os
+from pathlib import Path
+from typing import Optional
+
+import torch
+
+try:
+ import triton
+ import triton.language as tl
+ from triton.language.extra.cuda import libdevice as tl_libdevice
+
+ _TRITON_AVAILABLE = True
+except Exception: # pragma: no cover
+ triton = None # type: ignore
+ tl = None # type: ignore
+ tl_libdevice = None # type: ignore
+ _TRITON_AVAILABLE = False
+
+
+_ENV_ENABLE = "WAN2GP_QUANTO_INT8_TRITON"
+_ENV_AUTOTUNE_ENABLE = "WAN2GP_QUANTO_INT8_AUTOTUNE"
+_ENV_AUTOTUNE_DEBUG = "WAN2GP_QUANTO_INT8_AUTOTUNE_DEBUG"
+_ENV_AUTOTUNE_MAX_M = "WAN2GP_QUANTO_INT8_AUTOTUNE_MAX_M"
+_ENV_AUTOTUNE_MAX_SHAPES = "WAN2GP_QUANTO_INT8_AUTOTUNE_MAX_SHAPES"
+_ENV_AUTOTUNE_WARMUP = "WAN2GP_QUANTO_INT8_AUTOTUNE_WARMUP"
+_ENV_AUTOTUNE_ITERS = "WAN2GP_QUANTO_INT8_AUTOTUNE_ITERS"
+_ENV_AUTOTUNE_MIN_SPEEDUP = "WAN2GP_QUANTO_INT8_AUTOTUNE_MIN_SPEEDUP"
+_ENV_AUTOTUNE_CACHE = "WAN2GP_QUANTO_INT8_AUTOTUNE_CACHE"
+_ENV_AUTOTUNE_VALIDATE = "WAN2GP_QUANTO_INT8_AUTOTUNE_VALIDATE"
+_ENV_AUTOTUNE_MAX_ABS_ERR = "WAN2GP_QUANTO_INT8_AUTOTUNE_MAX_ABS_ERR"
+_ENV_AUTOTUNE_MAX_REL_ERR = "WAN2GP_QUANTO_INT8_AUTOTUNE_MAX_REL_ERR"
+_ENV_AUTOTUNE_LOCK_FUSED_BLOCK_K = "WAN2GP_QUANTO_INT8_AUTOTUNE_LOCK_FUSED_BLOCK_K"
+_IS_AVAILABLE = None
+_CONFIG_LEN = 5
+_AUTOTUNE_CACHE_LOADED = False
+_AUTOTUNE_CACHE_DIRTY = False
+_AUTOTUNE_CONFIG_CACHE: dict[str, tuple[int, int, int, int, int]] = {}
+_AUTOTUNE_SESSION_CACHE: dict[tuple[int, str, str], tuple[int, int, int, int, int]] = {}
+_AUTOTUNE_SEEN_SLOTS: set[tuple[int, str, str]] = set()
+_AUTOTUNE_SLOTS_TUNED = 0
+
+# Tuned decode-time configs reused from nanovllm int8 kernels.
+_TRITON_SMALL_M_CONFIGS = {
+ (2048, 4096): (2, 32, 256, 8, 5),
+ (2048, 2048): (1, 32, 64, 2, 4),
+ (2048, 12288): (8, 64, 256, 8, 4),
+ (6144, 2048): (1, 32, 512, 4, 5),
+}
+_TRITON_TINY_M_SHAPE_CONFIGS = {
+ (2, 3072, 3072): (2, 128, 64, 8, 4),
+ (4, 3072, 3072): (4, 256, 64, 4, 4),
+ (2, 3072, 1024): (2, 256, 128, 8, 4),
+ (4, 3072, 1024): (2, 256, 128, 8, 4),
+ (2, 3072, 1536): (2, 64, 64, 4, 4),
+ (4, 3072, 1536): (2, 256, 128, 8, 4),
+ (2, 3072, 8192): (2, 128, 64, 8, 4),
+ (4, 3072, 8192): (2, 128, 64, 8, 4),
+ (2, 8192, 3072): (4, 128, 64, 4, 4),
+ (4, 8192, 3072): (2, 128, 128, 8, 4),
+}
+_TRITON_TINY_M_PAIR_CONFIGS = {
+ (3072, 3072): (2, 128, 64, 8, 4),
+ (3072, 1024): (2, 256, 128, 8, 4),
+ (3072, 1536): (2, 64, 64, 4, 4),
+ (3072, 8192): (2, 128, 64, 8, 4),
+ (8192, 3072): (4, 128, 64, 4, 4),
+}
+_TRITON_SMALL_M_DEFAULT = (4, 256, 64, 4, 4)
+_TRITON_SMALL_M_K3072_DEFAULT = (2, 64, 64, 4, 4)
+_TRITON_MID_M_DEFAULT = (32, 128, 64, 8, 4)
+_TRITON_LARGE_M_DEFAULT = (64, 128, 64, 8, 4)
+_TRITON_LARGE_M_SHAPE_CONFIGS = {
+ # Hot LTX2 distilled fused-int8 shapes profiled on RTX 50xx.
+ (3840, 2048): (64, 256, 64, 8, 4),
+ (3840, 15360): (64, 256, 64, 8, 4),
+ (3840, 4096): (64, 256, 64, 8, 4),
+ (4096, 3840): (64, 256, 64, 8, 4),
+ (15360, 3840): (64, 256, 64, 8, 4),
+ # Hot WAN2 I2V enhanced-lightning fused-int8 shapes (M ~= 512).
+ (4096, 4096): (64, 256, 64, 8, 4),
+ (4096, 10240): (64, 256, 64, 8, 4),
+ (10240, 4096): (64, 256, 64, 8, 4),
+}
+
+_AUTOTUNE_SLOT_REPS = {
+ "tiny_k3072_default": ((2, 3072, 2048), (4, 3072, 4096)),
+ "tiny_default": ((2, 4096, 1536), (4, 4096, 1536)),
+ "mid_default": ((32, 2048, 4096), (32, 3072, 3072), (32, 4096, 4096)),
+ "large_n_ge_2048": ((512, 4096, 4096), (3840, 3840, 4096)),
+ "large_default": ((128, 4096, 1024), (192, 3072, 1536)),
+}
+
+
+def _env_flag(name: str, default: str = "1") -> bool:
+ val = os.environ.get(name, default)
+ return str(val).strip().lower() in ("1", "true", "yes", "on")
+
+
+def _parse_version(ver: str) -> tuple[int, int]:
+ try:
+ parts = ver.split(".")
+ return int(parts[0]), int(parts[1])
+ except Exception:
+ return (0, 0)
+
+
+def _env_int(name: str, default: int) -> int:
+ try:
+ return int(os.environ.get(name, str(default)))
+ except Exception:
+ return default
+
+
+def _env_float(name: str, default: float) -> float:
+ try:
+ return float(os.environ.get(name, str(default)))
+ except Exception:
+ return default
+
+
+def _autotune_debug(msg: str) -> None:
+ if _env_flag(_ENV_AUTOTUNE_DEBUG, "0"):
+ print(f"[WAN2GP][INT8][autotune] {msg}")
+
+
+def _runtime_compatible() -> bool:
+ if not (_TRITON_AVAILABLE and torch.cuda.is_available()):
+ return False
+ try:
+ cc_major, _ = torch.cuda.get_device_capability()
+ except Exception:
+ return False
+
+ # Triton int8 dot kernels require tensor-core generation GPUs.
+ if cc_major < 8:
+ return False
+
+ # Keep SM120 safe on older Triton builds that abort at compile time.
+ triton_ver = _parse_version(getattr(triton, "__version__", "0.0"))
+ if cc_major >= 12 and triton_ver < (3, 6):
+ return False
+
+ return True
+
+
+def is_available() -> bool:
+ global _IS_AVAILABLE
+ if _IS_AVAILABLE is None:
+ _IS_AVAILABLE = bool(_runtime_compatible() and _env_flag(_ENV_ENABLE, "1"))
+ return _IS_AVAILABLE
+
+
+def _select_static_triton_int8_config(m: int, k: int, n: int) -> tuple[int, int, int, int, int]:
+ if m <= 4:
+ cfg = _TRITON_TINY_M_SHAPE_CONFIGS.get((m, k, n))
+ if cfg is not None:
+ return cfg
+ cfg = _TRITON_TINY_M_PAIR_CONFIGS.get((k, n))
+ if cfg is not None:
+ return cfg
+ cfg = _TRITON_SMALL_M_CONFIGS.get((k, n))
+ if cfg is not None:
+ return cfg
+ if k == 3072:
+ return _TRITON_SMALL_M_K3072_DEFAULT
+ return _TRITON_SMALL_M_DEFAULT
+ if m < 64:
+ return _TRITON_MID_M_DEFAULT
+ if m >= 256:
+ cfg = _TRITON_LARGE_M_SHAPE_CONFIGS.get((k, n))
+ if cfg is not None:
+ return cfg
+ if n >= 2048:
+ return (64, 256, 64, 8, 4)
+ return _TRITON_LARGE_M_DEFAULT
+
+
+def _dedup_shapes(shapes: tuple[tuple[int, int, int], ...]) -> tuple[tuple[int, int, int], ...]:
+ out: list[tuple[int, int, int]] = []
+ seen: set[tuple[int, int, int]] = set()
+ for shape in shapes:
+ if not isinstance(shape, (list, tuple)) or len(shape) != 3:
+ continue
+ try:
+ m, k, n = (int(shape[0]), int(shape[1]), int(shape[2]))
+ except Exception:
+ continue
+ if m <= 0 or k <= 0 or n <= 0:
+ continue
+ key = (m, k, n)
+ if key in seen:
+ continue
+ seen.add(key)
+ out.append(key)
+ return tuple(out)
+
+
+def _resolve_autotune_slot(m: int, k: int, n: int) -> tuple[str, tuple[tuple[int, int, int], ...]]:
+ baseline = _select_static_triton_int8_config(m, k, n)
+ if m <= 4:
+ if (m, k, n) in _TRITON_TINY_M_SHAPE_CONFIGS:
+ slot_id = f"tiny_shape|m={m}|k={k}|n={n}"
+ reps = ((m, k, n),)
+ elif (k, n) in _TRITON_TINY_M_PAIR_CONFIGS:
+ slot_id = f"tiny_pair|k={k}|n={n}"
+ reps = ((2, k, n), (4, k, n))
+ elif (k, n) in _TRITON_SMALL_M_CONFIGS:
+ slot_id = f"tiny_small_pair|k={k}|n={n}"
+ reps = ((2, k, n), (4, k, n))
+ elif k == 3072:
+ slot_id = "tiny_k3072_default"
+ reps = _AUTOTUNE_SLOT_REPS[slot_id]
+ else:
+ slot_id = "tiny_default"
+ reps = _AUTOTUNE_SLOT_REPS[slot_id]
+ elif m < 64:
+ slot_id = "mid_default"
+ reps = _AUTOTUNE_SLOT_REPS[slot_id]
+ elif m >= 256 and (k, n) in _TRITON_LARGE_M_SHAPE_CONFIGS:
+ slot_id = f"large_hot_pair|k={k}|n={n}"
+ reps = ((512, k, n), (3840, k, n))
+ elif m >= 256 and n >= 2048:
+ slot_id = "large_n_ge_2048"
+ reps = _AUTOTUNE_SLOT_REPS[slot_id]
+ else:
+ slot_id = "large_default"
+ reps = _AUTOTUNE_SLOT_REPS[slot_id]
+
+ filtered = [shape for shape in _dedup_shapes(reps) if _select_static_triton_int8_config(shape[0], shape[1], shape[2]) == baseline]
+ if len(filtered) == 0:
+ filtered = [(m, k, n)]
+ return slot_id, tuple(filtered)
+
+
+def _normalize_config(cfg) -> Optional[tuple[int, int, int, int, int]]:
+ if not isinstance(cfg, (list, tuple)) or len(cfg) != _CONFIG_LEN:
+ return None
+ try:
+ c0, c1, c2, c3, c4 = (int(v) for v in cfg)
+ except Exception:
+ return None
+ if c0 <= 0 or c1 <= 0 or c2 <= 0 or c3 <= 0 or c4 <= 0:
+ return None
+ return (c0, c1, c2, c3, c4)
+
+
+def _autotune_cache_path() -> Path:
+ default_path = os.path.join("_tmp", "quanto_int8_autotune_cache.json")
+ return Path(os.environ.get(_ENV_AUTOTUNE_CACHE, default_path)).expanduser()
+
+
+def _load_autotune_cache() -> None:
+ global _AUTOTUNE_CACHE_LOADED, _AUTOTUNE_CONFIG_CACHE
+ if _AUTOTUNE_CACHE_LOADED:
+ return
+ _AUTOTUNE_CACHE_LOADED = True
+ cache_path = _autotune_cache_path()
+ try:
+ payload = json.loads(cache_path.read_text(encoding="utf-8"))
+ except Exception:
+ return
+ entries = payload.get("entries", {})
+ if not isinstance(entries, dict):
+ return
+ parsed = {}
+ for key, raw_cfg in entries.items():
+ if not isinstance(key, str):
+ continue
+ cfg = _normalize_config(raw_cfg)
+ if cfg is not None:
+ parsed[key] = cfg
+ _AUTOTUNE_CONFIG_CACHE = parsed
+
+
+def _save_autotune_cache() -> None:
+ global _AUTOTUNE_CACHE_DIRTY
+ if not _AUTOTUNE_CACHE_DIRTY:
+ return
+ cache_path = _autotune_cache_path()
+ try:
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = Path(f"{cache_path}.tmp")
+ payload = {"version": 1, "entries": {key: list(cfg) for key, cfg in _AUTOTUNE_CONFIG_CACHE.items()}}
+ tmp_path.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")
+ tmp_path.replace(cache_path)
+ _AUTOTUNE_CACHE_DIRTY = False
+ except Exception as exc:
+ _autotune_debug(f"cache write failed: {exc}")
+
+
+def _device_index(device: Optional[torch.device]) -> int:
+ if device is not None and device.type == "cuda" and device.index is not None:
+ return int(device.index)
+ return int(torch.cuda.current_device())
+
+
+def _device_fingerprint(device_index: int) -> str:
+ props = torch.cuda.get_device_properties(device_index)
+ triton_ver = getattr(triton, "__version__", "0.0")
+ return (
+ f"{props.name}|cc={props.major}.{props.minor}|sm={props.multi_processor_count}|"
+ f"torch={torch.__version__}|triton={triton_ver}"
+ )
+
+
+def _autotune_slot_cache_key(device_index: int, kernel_kind: str, slot_id: str) -> str:
+ return f"{_device_fingerprint(device_index)}|{kernel_kind}|slot={slot_id}"
+
+
+def _autotune_legacy_shape_cache_key(device_index: int, kernel_kind: str, m: int, k: int, n: int) -> str:
+ return f"{_device_fingerprint(device_index)}|{kernel_kind}|{m}|{k}|{n}"
+
+
+def _get_cached_config(device_index: int, kernel_kind: str, slot_id: str, m: int, k: int, n: int) -> Optional[tuple[int, int, int, int, int]]:
+ global _AUTOTUNE_CACHE_DIRTY
+ _load_autotune_cache()
+ slot_key = _autotune_slot_cache_key(device_index, kernel_kind, slot_id)
+ cfg = _AUTOTUNE_CONFIG_CACHE.get(slot_key)
+ if cfg is not None:
+ return cfg
+ legacy_key = _autotune_legacy_shape_cache_key(device_index, kernel_kind, m, k, n)
+ legacy_cfg = _AUTOTUNE_CONFIG_CACHE.get(legacy_key)
+ if legacy_cfg is None:
+ return None
+ _AUTOTUNE_CONFIG_CACHE[slot_key] = legacy_cfg
+ _AUTOTUNE_CACHE_DIRTY = True
+ return legacy_cfg
+
+
+def _set_cached_config(device_index: int, kernel_kind: str, slot_id: str, cfg: tuple[int, int, int, int, int]) -> None:
+ global _AUTOTUNE_CACHE_DIRTY
+ _load_autotune_cache()
+ key = _autotune_slot_cache_key(device_index, kernel_kind, slot_id)
+ if _AUTOTUNE_CONFIG_CACHE.get(key) == cfg:
+ return
+ _AUTOTUNE_CONFIG_CACHE[key] = cfg
+ _AUTOTUNE_CACHE_DIRTY = True
+
+
+def _drop_cached_config(device_index: int, kernel_kind: str, slot_id: str, m: int, k: int, n: int) -> None:
+ global _AUTOTUNE_CACHE_DIRTY
+ _load_autotune_cache()
+ keys = (
+ _autotune_slot_cache_key(device_index, kernel_kind, slot_id),
+ _autotune_legacy_shape_cache_key(device_index, kernel_kind, m, k, n),
+ )
+ removed = False
+ for key in keys:
+ if key in _AUTOTUNE_CONFIG_CACHE:
+ del _AUTOTUNE_CONFIG_CACHE[key]
+ removed = True
+ if removed:
+ _AUTOTUNE_CACHE_DIRTY = True
+
+
+def _config_compatible_with_baseline(
+ kind: str,
+ baseline: tuple[int, int, int, int, int],
+ cfg: tuple[int, int, int, int, int],
+) -> bool:
+ if kind == "fused" and _env_flag(_ENV_AUTOTUNE_LOCK_FUSED_BLOCK_K, "1"):
+ # Fused blockscale kernel computes row scales per K-chunk; changing block_k changes numerics.
+ return int(cfg[2]) == int(baseline[2])
+ return True
+
+
+def _candidate_configs(
+ baseline: tuple[int, int, int, int, int],
+ m: int,
+ k: int,
+ n: int,
+ *,
+ kind: str,
+) -> list[tuple[int, int, int, int, int]]:
+ out = [baseline]
+ if m <= 4:
+ out.extend(
+ [
+ (1, 64, 64, 2, 4),
+ (1, 128, 64, 4, 4),
+ (2, 64, 64, 4, 4),
+ (2, 128, 64, 4, 4),
+ (2, 128, 128, 8, 4),
+ (2, 256, 64, 8, 4),
+ (4, 128, 64, 4, 4),
+ (4, 256, 64, 4, 4),
+ (8, 128, 64, 4, 4),
+ ]
+ )
+ shape_cfg = _TRITON_TINY_M_SHAPE_CONFIGS.get((m, k, n))
+ if shape_cfg is not None:
+ out.append(shape_cfg)
+ pair_cfg = _TRITON_TINY_M_PAIR_CONFIGS.get((k, n))
+ if pair_cfg is not None:
+ out.append(pair_cfg)
+ elif m <= 16:
+ out.extend([(8, 128, 64, 4, 4), (8, 256, 64, 8, 4), (16, 128, 64, 8, 4), (16, 256, 64, 8, 4), (32, 128, 64, 8, 4)])
+ dedup: list[tuple[int, int, int, int, int]] = []
+ seen = set()
+ for cfg in out:
+ norm = _normalize_config(cfg)
+ if norm is None or norm in seen:
+ continue
+ if not _config_compatible_with_baseline(kind, baseline, norm):
+ continue
+ seen.add(norm)
+ dedup.append(norm)
+ return dedup
+
+
+def _launch_candidate(kind: str, cfg: tuple[int, int, int, int, int], tensors: tuple[torch.Tensor, ...], m: int, n: int, k: int) -> None:
+ block_m, block_n, block_k, num_warps, num_stages = cfg
+ grid = (triton.cdiv(m, block_m), triton.cdiv(n, block_n))
+ if kind == "fused":
+ x_mm_c, qweight_c, b_scale_c, out = tensors
+ _fused_dynamic_int8_blockscale_gemm_kernel[grid](
+ x_mm_c,
+ qweight_c,
+ b_scale_c,
+ out,
+ m,
+ n,
+ k,
+ x_mm_c.stride(0),
+ x_mm_c.stride(1),
+ qweight_c.stride(0),
+ qweight_c.stride(1),
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+ return
+ a_int8_c, b_int8_c, a_scale_c, b_scale_c, out = tensors
+ _scaled_int8_gemm_kernel[grid](
+ a_int8_c,
+ b_int8_c,
+ a_scale_c,
+ b_scale_c,
+ out,
+ m,
+ n,
+ k,
+ a_int8_c.stride(0),
+ a_int8_c.stride(1),
+ b_int8_c.stride(0),
+ b_int8_c.stride(1),
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+
+
+def _create_bench_tensors(kind: str, device: torch.device, m: int, k: int, n: int) -> tuple[torch.Tensor, ...]:
+ if kind == "fused":
+ x_mm_c = torch.randn((m, k), device=device, dtype=torch.bfloat16)
+ qweight_c = torch.randint(-128, 128, (n, k), device=device, dtype=torch.int8)
+ b_scale_c = torch.rand((n,), device=device, dtype=torch.float32).add_(1e-4)
+ out = torch.empty((m, n), device=device, dtype=torch.bfloat16)
+ return (x_mm_c, qweight_c, b_scale_c, out)
+ a_int8_c = torch.randint(-128, 128, (m, k), device=device, dtype=torch.int8)
+ b_int8_c = torch.randint(-128, 128, (n, k), device=device, dtype=torch.int8)
+ a_scale_c = torch.rand((m,), device=device, dtype=torch.float32).add_(1e-4)
+ b_scale_c = torch.rand((n,), device=device, dtype=torch.float32).add_(1e-4)
+ out = torch.empty((m, n), device=device, dtype=torch.bfloat16)
+ return (a_int8_c, b_int8_c, a_scale_c, b_scale_c, out)
+
+
+def _run_candidate_once(kind: str, cfg: tuple[int, int, int, int, int], tensors: tuple[torch.Tensor, ...], m: int, k: int, n: int) -> Optional[torch.Tensor]:
+ try:
+ if kind == "fused":
+ x_mm_c, qweight_c, b_scale_c, _ = tensors
+ out = torch.empty((m, n), device=x_mm_c.device, dtype=torch.bfloat16)
+ _launch_candidate(kind, cfg, (x_mm_c, qweight_c, b_scale_c, out), m, n, k)
+ return out
+ a_int8_c, b_int8_c, a_scale_c, b_scale_c, _ = tensors
+ out = torch.empty((m, n), device=a_int8_c.device, dtype=torch.bfloat16)
+ _launch_candidate(kind, cfg, (a_int8_c, b_int8_c, a_scale_c, b_scale_c, out), m, n, k)
+ return out
+ except Exception as exc:
+ _autotune_debug(f"single-run failed for {kind} shape=({m},{k},{n}) cfg={cfg}: {exc}")
+ return None
+
+
+def _candidate_matches_baseline(
+ baseline_out: torch.Tensor,
+ candidate_out: torch.Tensor,
+ *,
+ max_abs_limit: float,
+ rel_limit: float,
+) -> tuple[bool, float, float]:
+ if not torch.isfinite(candidate_out).all().item():
+ return False, float("inf"), float("inf")
+ base_f = baseline_out.float()
+ cand_f = candidate_out.float()
+ diff = (base_f - cand_f).abs()
+ max_abs = float(diff.max().item())
+ denom = base_f.abs().mean().clamp_min(1e-6)
+ rel = float((diff.mean() / denom).item())
+ return (max_abs <= max_abs_limit and rel <= rel_limit), max_abs, rel
+
+
+def _validate_config(
+ kind: str,
+ device: torch.device,
+ m: int,
+ k: int,
+ n: int,
+ baseline: tuple[int, int, int, int, int],
+ cfg: tuple[int, int, int, int, int],
+) -> bool:
+ if not _config_compatible_with_baseline(kind, baseline, cfg):
+ return False
+ if cfg == baseline:
+ return True
+ if not _env_flag(_ENV_AUTOTUNE_VALIDATE, "1"):
+ return True
+ max_abs_limit = max(0.0, _env_float(_ENV_AUTOTUNE_MAX_ABS_ERR, 0.25))
+ rel_limit = max(0.0, _env_float(_ENV_AUTOTUNE_MAX_REL_ERR, 0.001))
+ tensors = _create_bench_tensors(kind, device, m, k, n)
+ baseline_out = _run_candidate_once(kind, baseline, tensors, m, k, n)
+ candidate_out = _run_candidate_once(kind, cfg, tensors, m, k, n)
+ if baseline_out is None or candidate_out is None:
+ return False
+ ok, max_abs, rel = _candidate_matches_baseline(
+ baseline_out,
+ candidate_out,
+ max_abs_limit=max_abs_limit,
+ rel_limit=rel_limit,
+ )
+ if not ok:
+ _autotune_debug(
+ f"rejecting config {cfg} for {kind} shape=({m},{k},{n}) "
+ f"vs baseline {baseline}: max_abs={max_abs:.6f}, rel={rel:.6f}"
+ )
+ return ok
+
+
+def _benchmark_config_ms(kind: str, cfg: tuple[int, int, int, int, int], tensors: tuple[torch.Tensor, ...], device: torch.device, m: int, k: int, n: int) -> Optional[float]:
+ warmup = max(1, _env_int(_ENV_AUTOTUNE_WARMUP, 2))
+ iters = max(1, _env_int(_ENV_AUTOTUNE_ITERS, 5))
+ try:
+ for _ in range(warmup):
+ _launch_candidate(kind, cfg, tensors, m, n, k)
+ torch.cuda.synchronize(device)
+ start = torch.cuda.Event(enable_timing=True)
+ end = torch.cuda.Event(enable_timing=True)
+ start.record()
+ for _ in range(iters):
+ _launch_candidate(kind, cfg, tensors, m, n, k)
+ end.record()
+ end.synchronize()
+ return float(start.elapsed_time(end)) / float(iters)
+ except Exception as exc:
+ _autotune_debug(f"benchmark failed for {kind} shape=({m},{k},{n}) cfg={cfg}: {exc}")
+ return None
+
+
+def _can_tune_slot(slot_key: tuple[int, str, str]) -> bool:
+ global _AUTOTUNE_SLOTS_TUNED
+ if slot_key in _AUTOTUNE_SEEN_SLOTS:
+ return True
+ max_shapes = max(0, _env_int(_ENV_AUTOTUNE_MAX_SHAPES, 32))
+ if _AUTOTUNE_SLOTS_TUNED >= max_shapes:
+ return False
+ _AUTOTUNE_SEEN_SLOTS.add(slot_key)
+ _AUTOTUNE_SLOTS_TUNED += 1
+ return True
+
+
+def _benchmark_slot_config_ms(
+ kind: str,
+ cfg: tuple[int, int, int, int, int],
+ device: torch.device,
+ rep_shapes: tuple[tuple[int, int, int], ...],
+) -> Optional[float]:
+ total = 0.0
+ count = 0
+ for rep_m, rep_k, rep_n in rep_shapes:
+ rep_baseline = _select_static_triton_int8_config(rep_m, rep_k, rep_n)
+ if not _validate_config(kind, device, rep_m, rep_k, rep_n, rep_baseline, cfg):
+ return None
+ tensors = _create_bench_tensors(kind, device, rep_m, rep_k, rep_n)
+ ms = _benchmark_config_ms(kind, cfg, tensors, device, rep_m, rep_k, rep_n)
+ if ms is None:
+ return None
+ total += ms
+ count += 1
+ if count == 0:
+ return None
+ return total / float(count)
+
+
+def _autotune_config(
+ kind: str,
+ device_index: int,
+ m: int,
+ k: int,
+ n: int,
+ baseline: tuple[int, int, int, int, int],
+ slot_id: str,
+ rep_shapes: tuple[tuple[int, int, int], ...],
+) -> tuple[int, int, int, int, int]:
+ device = torch.device("cuda", device_index)
+ cached = _get_cached_config(device_index, kind, slot_id, m, k, n)
+ if cached is not None:
+ if _validate_config(kind, device, m, k, n, baseline, cached):
+ return cached
+ _drop_cached_config(device_index, kind, slot_id, m, k, n)
+ slot_key = (device_index, kind, slot_id)
+ if not _can_tune_slot(slot_key):
+ _autotune_debug(f"slot budget reached; keeping baseline for {kind} slot={slot_id} shape=({m},{k},{n})")
+ return baseline
+
+ rep_m, rep_k, rep_n = rep_shapes[0]
+ rep_baseline = _select_static_triton_int8_config(rep_m, rep_k, rep_n)
+ candidate_seed = rep_baseline if _config_compatible_with_baseline(kind, baseline, rep_baseline) else baseline
+ candidates = _candidate_configs(candidate_seed, rep_m, rep_k, rep_n, kind=kind)
+ if baseline not in candidates:
+ candidates = [baseline, *candidates]
+
+ results: dict[tuple[int, int, int, int, int], float] = {}
+ for cfg in candidates:
+ ms = _benchmark_slot_config_ms(kind, cfg, device, rep_shapes)
+ if ms is not None:
+ results[cfg] = ms
+ baseline_ms = results.get(baseline)
+ if baseline_ms is None:
+ _set_cached_config(device_index, kind, slot_id, baseline)
+ return baseline
+ best_cfg, best_ms = min(results.items(), key=lambda item: item[1])
+ min_speedup = max(1.0, _env_float(_ENV_AUTOTUNE_MIN_SPEEDUP, 1.02))
+ use_best = best_cfg != baseline and best_ms > 0.0 and (baseline_ms / best_ms) >= min_speedup
+ picked = best_cfg if use_best else baseline
+ if not _validate_config(kind, device, m, k, n, baseline, picked):
+ picked = baseline
+ _set_cached_config(device_index, kind, slot_id, picked)
+ if use_best:
+ _autotune_debug(
+ f"picked {picked} over baseline {baseline} for {kind} slot={slot_id} shape=({m},{k},{n}), "
+ f"baseline_ms={baseline_ms:.4f}, tuned_ms={best_ms:.4f}, speedup={baseline_ms / best_ms:.3f}x"
+ )
+ else:
+ _autotune_debug(
+ f"kept baseline {baseline} for {kind} slot={slot_id} shape=({m},{k},{n}), "
+ f"baseline_ms={baseline_ms:.4f}, best_cfg={best_cfg}, best_ms={best_ms:.4f}"
+ )
+ return picked
+
+
+def _select_triton_int8_config(
+ m: int,
+ k: int,
+ n: int,
+ *,
+ device: Optional[torch.device] = None,
+ kernel_kind: str = "fused",
+) -> tuple[int, int, int, int, int]:
+ baseline = _select_static_triton_int8_config(m, k, n)
+ if not _env_flag(_ENV_AUTOTUNE_ENABLE, "1"):
+ return baseline
+ if not is_available() or not torch.cuda.is_available():
+ return baseline
+ max_m = _env_int(_ENV_AUTOTUNE_MAX_M, -1)
+ if max_m >= 0 and m > max_m:
+ return baseline
+ try:
+ device_index = _device_index(device)
+ except Exception:
+ return baseline
+ slot_id, rep_shapes = _resolve_autotune_slot(m, k, n)
+ session_key = (device_index, kernel_kind, slot_id)
+ cached = _AUTOTUNE_SESSION_CACHE.get(session_key)
+ if cached is not None:
+ return cached
+ tuned = _autotune_config(kernel_kind, device_index, m, k, n, baseline, slot_id, rep_shapes)
+ _AUTOTUNE_SESSION_CACHE[session_key] = tuned
+ return tuned
+
+
+atexit.register(_save_autotune_cache)
+
+
+if _TRITON_AVAILABLE:
+
+ @triton.jit
+ def _fused_dynamic_int8_gemm_kernel(
+ a_ptr,
+ b_ptr,
+ s_ptr,
+ c_ptr,
+ m,
+ n,
+ k,
+ stride_am,
+ stride_ak,
+ stride_bn,
+ stride_bk,
+ stride_cm,
+ stride_cn,
+ block_m: tl.constexpr,
+ block_n: tl.constexpr,
+ block_k: tl.constexpr,
+ ):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * block_m + tl.arange(0, block_m)
+ offs_n = pid_n * block_n + tl.arange(0, block_n)
+ offs_k = tl.arange(0, block_k)
+
+ # Pass 1: rowwise absmax for dynamic symmetric int8 activation quantization.
+ row_amax = tl.zeros((block_m,), dtype=tl.float32)
+ for k0 in range(0, k, block_k):
+ kk = k0 + offs_k
+ a = tl.load(
+ a_ptr + offs_m[:, None] * stride_am + kk[None, :] * stride_ak,
+ mask=(offs_m[:, None] < m) & (kk[None, :] < k),
+ other=0,
+ ).to(tl.float32)
+ row_amax = tl.maximum(row_amax, tl.max(tl.abs(a), axis=1))
+
+ row_scale = row_amax / 127.0
+ row_scale = tl.where(row_scale > 0.0, row_scale, 1.0)
+ row_inv_scale = 1.0 / row_scale
+
+ # Pass 2: quantize activations on the fly + int8 dot.
+ acc = tl.zeros((block_m, block_n), dtype=tl.int32)
+ for k0 in range(0, k, block_k):
+ kk = k0 + offs_k
+ a = tl.load(
+ a_ptr + offs_m[:, None] * stride_am + kk[None, :] * stride_ak,
+ mask=(offs_m[:, None] < m) & (kk[None, :] < k),
+ other=0,
+ ).to(tl.float32)
+ a = a * row_inv_scale[:, None]
+ # Match torch.round behavior (ties-to-even) used by quanto::quantize_symmetric.
+ a = tl_libdevice.rint(a)
+ a = tl.maximum(tl.minimum(a, 127.0), -128.0).to(tl.int8)
+
+ # Weight is [N, K]; load as [K, N] tile for dot.
+ b = tl.load(
+ b_ptr + offs_n[None, :] * stride_bn + kk[:, None] * stride_bk,
+ mask=(offs_n[None, :] < n) & (kk[:, None] < k),
+ other=0,
+ ).to(tl.int8)
+ acc += tl.dot(a, b)
+
+ scales = tl.load(s_ptr + offs_n, mask=offs_n < n, other=0).to(tl.float32)
+ out = acc.to(tl.float32) * row_scale[:, None] * scales[None, :]
+ tl.store(
+ c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
+ out,
+ mask=(offs_m[:, None] < m) & (offs_n[None, :] < n),
+ )
+
+ @triton.jit
+ def _fused_dynamic_int8_blockscale_gemm_kernel(
+ a_ptr,
+ b_ptr,
+ s_ptr,
+ c_ptr,
+ m,
+ n,
+ k,
+ stride_am,
+ stride_ak,
+ stride_bn,
+ stride_bk,
+ stride_cm,
+ stride_cn,
+ block_m: tl.constexpr,
+ block_n: tl.constexpr,
+ block_k: tl.constexpr,
+ ):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * block_m + tl.arange(0, block_m)
+ offs_n = pid_n * block_n + tl.arange(0, block_n)
+ offs_k = tl.arange(0, block_k)
+
+ acc = tl.zeros((block_m, block_n), dtype=tl.float32)
+ for k0 in range(0, k, block_k):
+ kk = k0 + offs_k
+ a = tl.load(
+ a_ptr + offs_m[:, None] * stride_am + kk[None, :] * stride_ak,
+ mask=(offs_m[:, None] < m) & (kk[None, :] < k),
+ other=0,
+ ).to(tl.float32)
+ row_amax = tl.max(tl.abs(a), axis=1)
+ row_scale = row_amax / 127.0
+ row_scale = tl.where(row_scale > 0.0, row_scale, 1.0)
+ a = a / row_scale[:, None]
+ a = tl_libdevice.rint(a)
+ a = tl.maximum(tl.minimum(a, 127.0), -128.0).to(tl.int8)
+
+ b = tl.load(
+ b_ptr + offs_n[None, :] * stride_bn + kk[:, None] * stride_bk,
+ mask=(offs_n[None, :] < n) & (kk[:, None] < k),
+ other=0,
+ ).to(tl.int8)
+
+ dot_i32 = tl.dot(a, b)
+ acc += dot_i32.to(tl.float32) * row_scale[:, None]
+
+ scales = tl.load(s_ptr + offs_n, mask=offs_n < n, other=0).to(tl.float32)
+ out = acc * scales[None, :]
+ tl.store(
+ c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
+ out,
+ mask=(offs_m[:, None] < m) & (offs_n[None, :] < n),
+ )
+
+ @triton.jit
+ def _scaled_int8_gemm_kernel(
+ a_ptr,
+ b_ptr,
+ a_scales_ptr,
+ b_scales_ptr,
+ c_ptr,
+ m,
+ n,
+ k,
+ stride_am,
+ stride_ak,
+ stride_bn,
+ stride_bk,
+ stride_cm,
+ stride_cn,
+ block_m: tl.constexpr,
+ block_n: tl.constexpr,
+ block_k: tl.constexpr,
+ ):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * block_m + tl.arange(0, block_m)
+ offs_n = pid_n * block_n + tl.arange(0, block_n)
+ offs_k = tl.arange(0, block_k)
+
+ acc = tl.zeros((block_m, block_n), dtype=tl.int32)
+ for k0 in range(0, k, block_k):
+ kk = k0 + offs_k
+ a = tl.load(
+ a_ptr + offs_m[:, None] * stride_am + kk[None, :] * stride_ak,
+ mask=(offs_m[:, None] < m) & (kk[None, :] < k),
+ other=0,
+ ).to(tl.int8)
+ # Weight is [N, K]; load as [K, N] tile for dot.
+ b = tl.load(
+ b_ptr + offs_n[None, :] * stride_bn + kk[:, None] * stride_bk,
+ mask=(offs_n[None, :] < n) & (kk[:, None] < k),
+ other=0,
+ ).to(tl.int8)
+ acc += tl.dot(a, b)
+
+ a_scales = tl.load(a_scales_ptr + offs_m, mask=offs_m < m, other=1).to(tl.float32)
+ b_scales = tl.load(b_scales_ptr + offs_n, mask=offs_n < n, other=1).to(tl.float32)
+ out = acc.to(tl.float32) * a_scales[:, None] * b_scales[None, :]
+ tl.store(
+ c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn,
+ out,
+ mask=(offs_m[:, None] < m) & (offs_n[None, :] < n),
+ )
+
+
+def _flatten_scale(scale: torch.Tensor) -> torch.Tensor:
+ if scale.ndim == 2 and scale.shape[1] == 1:
+ return scale.view(-1)
+ if scale.ndim == 1:
+ return scale
+ return scale.reshape(-1)
+
+
+def _expand_or_validate_scale(scale: torch.Tensor, expected: int) -> torch.Tensor:
+ scale = _flatten_scale(scale)
+ if scale.numel() == 1:
+ return scale.reshape(1).expand(expected)
+ if scale.numel() != expected:
+ raise RuntimeError(f"Scale length mismatch: expected {expected}, got {scale.numel()}")
+ return scale
+
+
+def _fused_quant_scaled_mm_common(
+ x2d: torch.Tensor,
+ qweight: torch.Tensor,
+ b_scale: torch.Tensor,
+ *,
+ k: int,
+ n: int,
+ stride_bn: int,
+ stride_bk: int,
+ out_dtype: torch.dtype,
+) -> torch.Tensor:
+ m = x2d.shape[0]
+ out = torch.empty((m, n), device=x2d.device, dtype=out_dtype)
+ x_mm_c = x2d if x2d.is_contiguous() else x2d.contiguous()
+ b_scale_c = b_scale if b_scale.is_contiguous() else b_scale.contiguous()
+
+ block_m, block_n, block_k, num_warps, num_stages = _select_triton_int8_config(m, k, n, device=x2d.device, kernel_kind="fused")
+ grid = (triton.cdiv(m, block_m), triton.cdiv(n, block_n))
+ _fused_dynamic_int8_blockscale_gemm_kernel[grid](
+ x_mm_c,
+ qweight,
+ b_scale_c,
+ out,
+ m,
+ n,
+ k,
+ x_mm_c.stride(0),
+ x_mm_c.stride(1),
+ stride_bn,
+ stride_bk,
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+ return out
+
+
+def fused_quant_scaled_mm(
+ x2d: torch.Tensor,
+ qweight: torch.Tensor,
+ qweight_scale: torch.Tensor,
+ out_dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
+ if not is_available():
+ raise RuntimeError("Triton backend not available")
+ if x2d.ndim != 2:
+ raise RuntimeError("x2d must be 2D")
+ if qweight.ndim != 2:
+ raise RuntimeError("qweight must be 2D [N, K]")
+ if x2d.dtype not in (torch.bfloat16, torch.float16, torch.float32):
+ raise RuntimeError("x2d must be bf16/fp16/fp32")
+ if qweight.dtype != torch.int8:
+ raise RuntimeError("qweight must be int8")
+ if not x2d.is_cuda or not qweight.is_cuda:
+ raise RuntimeError("fused_quant_scaled_mm requires CUDA tensors")
+
+ m, k = x2d.shape
+ n, k2 = qweight.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: x={x2d.shape}, w={qweight.shape}")
+
+ b_scale = _expand_or_validate_scale(qweight_scale, n)
+ if b_scale.device != x2d.device or b_scale.dtype != torch.float32:
+ b_scale = b_scale.to(device=x2d.device, dtype=torch.float32)
+ elif not b_scale.is_contiguous():
+ b_scale = b_scale.contiguous()
+ if x2d.dtype not in (torch.bfloat16, torch.float16, torch.float32):
+ raise RuntimeError(f"Unsupported activation dtype for fused path: {x2d.dtype}")
+
+ out_dtype = out_dtype or x2d.dtype
+ qweight_c = qweight if qweight.is_contiguous() else qweight.contiguous()
+ return _fused_quant_scaled_mm_common(
+ x2d,
+ qweight_c,
+ b_scale,
+ k=k,
+ n=n,
+ stride_bn=qweight_c.stride(0),
+ stride_bk=qweight_c.stride(1),
+ out_dtype=out_dtype,
+ )
+
+
+def fused_quant_scaled_mm_transposed(
+ x2d: torch.Tensor,
+ qweight_t: torch.Tensor,
+ qweight_scale: torch.Tensor,
+ out_dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
+ if not is_available():
+ raise RuntimeError("Triton backend not available")
+ if x2d.ndim != 2:
+ raise RuntimeError("x2d must be 2D")
+ if qweight_t.ndim != 2:
+ raise RuntimeError("qweight_t must be 2D [K, N]")
+ if x2d.dtype not in (torch.bfloat16, torch.float16, torch.float32):
+ raise RuntimeError("x2d must be bf16/fp16/fp32")
+ if qweight_t.dtype != torch.int8:
+ raise RuntimeError("qweight_t must be int8")
+ if not x2d.is_cuda or not qweight_t.is_cuda:
+ raise RuntimeError("fused_quant_scaled_mm_transposed requires CUDA tensors")
+
+ m, k = x2d.shape
+ k2, n = qweight_t.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: x={x2d.shape}, w_t={qweight_t.shape}")
+
+ b_scale = _expand_or_validate_scale(qweight_scale, n)
+ if b_scale.device != x2d.device or b_scale.dtype != torch.float32:
+ b_scale = b_scale.to(device=x2d.device, dtype=torch.float32)
+ elif not b_scale.is_contiguous():
+ b_scale = b_scale.contiguous()
+ if x2d.dtype not in (torch.bfloat16, torch.float16, torch.float32):
+ raise RuntimeError(f"Unsupported activation dtype for fused path: {x2d.dtype}")
+
+ out_dtype = out_dtype or x2d.dtype
+ qweight_t_c = qweight_t if qweight_t.is_contiguous() else qweight_t.contiguous()
+ return _fused_quant_scaled_mm_common(
+ x2d,
+ qweight_t_c,
+ b_scale,
+ k=k,
+ n=n,
+ stride_bn=qweight_t_c.stride(1),
+ stride_bk=qweight_t_c.stride(0),
+ out_dtype=out_dtype,
+ )
+
+
+def scaled_int8_mm(
+ a_int8: torch.Tensor,
+ b_int8: torch.Tensor,
+ a_scale: torch.Tensor,
+ b_scale: torch.Tensor,
+ out_dtype: Optional[torch.dtype] = None,
+) -> torch.Tensor:
+ if not is_available():
+ raise RuntimeError("Triton backend not available")
+ if a_int8.ndim != 2:
+ raise RuntimeError("a_int8 must be 2D")
+ if b_int8.ndim != 2:
+ raise RuntimeError("b_int8 must be 2D [N, K]")
+ if a_int8.dtype != torch.int8 or b_int8.dtype != torch.int8:
+ raise RuntimeError("scaled_int8_mm requires int8 activations and int8 weights")
+ if not a_int8.is_cuda or not b_int8.is_cuda:
+ raise RuntimeError("scaled_int8_mm requires CUDA tensors")
+
+ m, k = a_int8.shape
+ n, k2 = b_int8.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: a={a_int8.shape}, w={b_int8.shape}")
+
+ a_scale = _expand_or_validate_scale(a_scale, m)
+ b_scale = _expand_or_validate_scale(b_scale, n)
+ if a_scale.device != a_int8.device or a_scale.dtype != torch.float32:
+ a_scale = a_scale.to(device=a_int8.device, dtype=torch.float32)
+ elif not a_scale.is_contiguous():
+ a_scale = a_scale.contiguous()
+ if b_scale.device != a_int8.device or b_scale.dtype != torch.float32:
+ b_scale = b_scale.to(device=a_int8.device, dtype=torch.float32)
+ elif not b_scale.is_contiguous():
+ b_scale = b_scale.contiguous()
+
+ out_dtype = out_dtype or torch.bfloat16
+ out = torch.empty((m, n), device=a_int8.device, dtype=out_dtype)
+ a_int8_c = a_int8 if a_int8.is_contiguous() else a_int8.contiguous()
+ b_int8_c = b_int8 if b_int8.is_contiguous() else b_int8.contiguous()
+ a_scale_c = a_scale if a_scale.is_contiguous() else a_scale.contiguous()
+ b_scale_c = b_scale if b_scale.is_contiguous() else b_scale.contiguous()
+
+ block_m, block_n, block_k, num_warps, num_stages = _select_triton_int8_config(m, k, n, device=a_int8.device, kernel_kind="scaled")
+ grid = (triton.cdiv(m, block_m), triton.cdiv(n, block_n))
+ _scaled_int8_gemm_kernel[grid](
+ a_int8_c,
+ b_int8_c,
+ a_scale_c,
+ b_scale_c,
+ out,
+ m,
+ n,
+ k,
+ a_int8_c.stride(0),
+ a_int8_c.stride(1),
+ b_int8_c.stride(0),
+ b_int8_c.stride(1),
+ out.stride(0),
+ out.stride(1),
+ block_m=block_m,
+ block_n=block_n,
+ block_k=block_k,
+ num_warps=num_warps,
+ num_stages=num_stages,
+ )
+ return out
diff --git a/shared/llm_engines/__init__.py b/shared/llm_engines/__init__.py
new file mode 100644
index 0000000..da404f0
--- /dev/null
+++ b/shared/llm_engines/__init__.py
@@ -0,0 +1 @@
+"""Shared LLM engine helpers."""
diff --git a/shared/llm_engines/nanovllm/__init__.py b/shared/llm_engines/nanovllm/__init__.py
new file mode 100644
index 0000000..8ef7526
--- /dev/null
+++ b/shared/llm_engines/nanovllm/__init__.py
@@ -0,0 +1,11 @@
+__all__ = ["LLM", "SamplingParams"]
+
+
+def __getattr__(name):
+ if name == "LLM":
+ from .llm import LLM
+ return LLM
+ if name == "SamplingParams":
+ from .sampling_params import SamplingParams
+ return SamplingParams
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
diff --git a/shared/llm_engines/nanovllm/config.py b/shared/llm_engines/nanovllm/config.py
new file mode 100644
index 0000000..69513e2
--- /dev/null
+++ b/shared/llm_engines/nanovllm/config.py
@@ -0,0 +1,34 @@
+import os
+from dataclasses import dataclass
+from transformers import AutoConfig
+
+
+@dataclass
+class Config:
+ model: str
+ max_num_batched_tokens: int = 16384
+ max_num_seqs: int = 512
+ max_model_len: int = 4096
+ gpu_memory_utilization: float = 0.9
+ tensor_parallel_size: int = 1
+ enforce_eager: bool = False
+ weight_load_mode: str = "eager" # eager | lazy | pinned
+ hf_config: AutoConfig | None = None
+ eos: int = -1
+ kvcache_block_size: int = 256
+ num_kvcache_blocks: int = -1
+ model_dir: str | None = None
+ model_file: str | None = None
+
+ def __post_init__(self):
+ if os.path.isfile(self.model) and self.model.endswith(".safetensors"):
+ self.model_file = self.model
+ self.model_dir = os.path.dirname(self.model)
+ else:
+ assert os.path.isdir(self.model)
+ self.model_dir = self.model
+ assert self.kvcache_block_size % 256 == 0
+ assert 1 <= self.tensor_parallel_size <= 8
+ self.hf_config = AutoConfig.from_pretrained(self.model_dir)
+ self.max_model_len = min(self.max_model_len, self.hf_config.max_position_embeddings)
+ assert self.max_num_batched_tokens >= self.max_model_len
diff --git a/shared/llm_engines/nanovllm/engine/block_manager.py b/shared/llm_engines/nanovllm/engine/block_manager.py
new file mode 100644
index 0000000..4954044
--- /dev/null
+++ b/shared/llm_engines/nanovllm/engine/block_manager.py
@@ -0,0 +1,119 @@
+from collections import deque
+import xxhash
+import numpy as np
+
+from nanovllm.engine.sequence import Sequence
+
+
+class Block:
+
+ def __init__(self, block_id):
+ self.block_id = block_id
+ self.ref_count = 0
+ self.hash = -1
+ self.token_ids = []
+
+ def update(self, hash: int, token_ids: list[int]):
+ self.hash = hash
+ self.token_ids = token_ids
+
+ def reset(self):
+ self.ref_count = 1
+ self.hash = -1
+ self.token_ids = []
+
+
+class BlockManager:
+
+ def __init__(self, num_blocks: int, block_size: int):
+ self.block_size = block_size
+ self.blocks: list[Block] = [Block(i) for i in range(num_blocks)]
+ self.hash_to_block_id: dict[int, int] = dict()
+ self.free_block_ids: deque[int] = deque(range(num_blocks))
+ self.used_block_ids: set[int] = set()
+
+ @classmethod
+ def compute_hash(cls, token_ids: list[int], prefix: int = -1):
+ h = xxhash.xxh64()
+ if prefix != -1:
+ h.update(prefix.to_bytes(8, "little"))
+ h.update(np.array(token_ids).tobytes())
+ return h.intdigest()
+
+ def _allocate_block(self, block_id: int) -> Block:
+ block = self.blocks[block_id]
+ assert block.ref_count == 0
+ block.reset()
+ self.free_block_ids.remove(block_id)
+ self.used_block_ids.add(block_id)
+ return self.blocks[block_id]
+
+ def _deallocate_block(self, block_id: int) -> Block:
+ assert self.blocks[block_id].ref_count == 0
+ self.used_block_ids.remove(block_id)
+ self.free_block_ids.append(block_id)
+
+ def can_allocate(self, seq: Sequence) -> bool:
+ return len(self.free_block_ids) >= seq.num_blocks
+
+ def allocate(self, seq: Sequence):
+ assert not seq.block_table
+ h = -1
+ cache_miss = False
+ for i in range(seq.num_blocks):
+ token_ids = seq.block(i)
+ h = self.compute_hash(token_ids, h) if len(token_ids) == self.block_size else -1
+ block_id = self.hash_to_block_id.get(h, -1)
+ if block_id == -1 or self.blocks[block_id].token_ids != token_ids:
+ cache_miss = True
+ if cache_miss:
+ block_id = self.free_block_ids[0]
+ block = self._allocate_block(block_id)
+ else:
+ seq.num_cached_tokens += self.block_size
+ if block_id in self.used_block_ids:
+ block = self.blocks[block_id]
+ block.ref_count += 1
+ else:
+ block = self._allocate_block(block_id)
+ if h != -1:
+ block.update(h, token_ids)
+ self.hash_to_block_id[h] = block_id
+ seq.block_table.append(block_id)
+
+ def deallocate(self, seq: Sequence):
+ for block_id in reversed(seq.block_table):
+ block = self.blocks[block_id]
+ block.ref_count -= 1
+ if block.ref_count == 0:
+ # Fix: Clean up hash_to_block_id mapping to prevent stale references
+ # This prevents CUDA illegal memory access when prefix cache tries to
+ # reuse a block_id that has already been freed
+ if block.hash != -1:
+ cached_id = self.hash_to_block_id.get(block.hash)
+ if cached_id == block_id:
+ del self.hash_to_block_id[block.hash]
+ self._deallocate_block(block_id)
+ seq.num_cached_tokens = 0
+ seq.block_table.clear()
+
+ def can_append(self, seq: Sequence) -> bool:
+ return len(self.free_block_ids) >= (len(seq) % self.block_size == 1)
+
+ def may_append(self, seq: Sequence):
+ block_table = seq.block_table
+ last_block = self.blocks[block_table[-1]]
+ if len(seq) % self.block_size == 1:
+ assert last_block.hash != -1
+ block_id = self.free_block_ids[0]
+ self._allocate_block(block_id)
+ block_table.append(block_id)
+ elif len(seq) % self.block_size == 0:
+ assert last_block.hash == -1
+ token_ids = seq.block(seq.num_blocks-1)
+ prefix = self.blocks[block_table[-2]].hash if len(block_table) > 1 else -1
+ h = self.compute_hash(token_ids, prefix)
+ last_block.update(h, token_ids)
+ self.hash_to_block_id[h] = last_block.block_id
+ else:
+ assert last_block.hash == -1
diff --git a/shared/llm_engines/nanovllm/engine/llm_engine.py b/shared/llm_engines/nanovllm/engine/llm_engine.py
new file mode 100644
index 0000000..b48d179
--- /dev/null
+++ b/shared/llm_engines/nanovllm/engine/llm_engine.py
@@ -0,0 +1,203 @@
+import atexit
+from dataclasses import fields
+from time import perf_counter
+from tqdm.auto import tqdm
+from transformers import AutoTokenizer
+import torch.multiprocessing as mp
+import torch
+
+from nanovllm.config import Config
+from nanovllm.sampling_params import SamplingParams
+from nanovllm.engine.sequence import Sequence
+from nanovllm.engine.scheduler import Scheduler
+from nanovllm.engine.block_manager import BlockManager
+from nanovllm.engine.model_runner import ModelRunner
+
+
+class LLMEngine:
+
+ def __init__(self, model, **kwargs):
+ config_fields = {field.name for field in fields(Config)}
+ config_kwargs = {k: v for k, v in kwargs.items() if k in config_fields}
+ config = Config(model, **config_kwargs)
+ self.config = config
+ self.ps = []
+ self.events = []
+ ctx = mp.get_context("spawn")
+ for i in range(1, config.tensor_parallel_size):
+ event = ctx.Event()
+ process = ctx.Process(target=ModelRunner, args=(config, i, event))
+ process.start()
+ self.ps.append(process)
+ self.events.append(event)
+ self.model_runner = ModelRunner(config, 0, self.events)
+ tokenizer = kwargs.get("tokenizer", None)
+ if tokenizer is not None:
+ self.tokenizer = tokenizer
+ else:
+ self.tokenizer = AutoTokenizer.from_pretrained(config.model, use_fast=True)
+ config.eos = self.tokenizer.eos_token_id
+ self.scheduler = Scheduler(config)
+ atexit.register(self.exit)
+
+ def exit(self):
+ self.model_runner.call("exit")
+ del self.model_runner
+ for p in self.ps:
+ p.join()
+
+ def unload_weights(self):
+ self.model_runner.unload_weights()
+ # KV cache is invalid after unload/reload, so cached prefix block metadata
+ # must be dropped as well to prevent stale-cache reuse.
+ try:
+ self.reset()
+ except Exception:
+ pass
+ self.scheduler.waiting.clear()
+ self.scheduler.running.clear()
+ self.scheduler.block_manager = BlockManager(
+ self.config.num_kvcache_blocks,
+ self.config.kvcache_block_size,
+ )
+
+ def clear_graph_cache(self):
+ self.model_runner.clear_graph_cache()
+
+ def reset_guard_counts(self):
+ self.model_runner.call("reset_guard_counts")
+
+ def get_guard_counts(self, reset: bool = False):
+ return self.model_runner.call("get_guard_counts", reset)
+
+ def add_request(self, prompt: str | list[int], sampling_params: SamplingParams, unconditional_prompt: str | list[int] | None = None):
+ if isinstance(prompt, str):
+ prompt = self.tokenizer.encode(prompt)
+ # For CFG: if cfg_scale > 1.0, create both conditional and unconditional sequences
+ if sampling_params.cfg_scale > 1.0:
+ if unconditional_prompt is None:
+ # Try to construct unconditional prompt by replacing user input with "NO USER INPUT"
+ # This is a fallback - ideally users should provide unconditional_prompt
+ if isinstance(prompt, list):
+ # For now, just use the same prompt (user should provide unconditional_prompt)
+ # TODO: Implement automatic "NO USER INPUT" replacement if possible
+ unconditional_prompt = prompt
+ else:
+ unconditional_prompt = prompt
+ if isinstance(unconditional_prompt, str):
+ unconditional_prompt = self.tokenizer.encode(unconditional_prompt)
+ # Create unconditional sequence first (so we can reference it from conditional)
+ uncond_seq = Sequence(unconditional_prompt, sampling_params, is_unconditional=True)
+ # Create conditional sequence with reference to unconditional
+ cond_seq = Sequence(prompt, sampling_params, is_unconditional=False, conditional_seq=uncond_seq)
+ uncond_seq.paired_seq = cond_seq # Link them bidirectionally
+ # Add both sequences to scheduler
+ self.scheduler.add(cond_seq)
+ self.scheduler.add(uncond_seq)
+ else:
+ seq = Sequence(prompt, sampling_params)
+ self.scheduler.add(seq)
+
+ def step(self):
+ seqs, is_prefill = self.scheduler.schedule()
+ token_ids = self.model_runner.call("run", seqs, is_prefill)
+ self.scheduler.postprocess(seqs, token_ids)
+ # Only output conditional sequences (unconditional sequences are just for CFG computation)
+ output_seqs = [seq for seq in seqs if seq.is_finished and (seq.cfg_scale <= 1.0 or not seq.is_unconditional)]
+ outputs = [(seq.seq_id, seq.completion_token_ids) for seq in output_seqs]
+ num_tokens = sum(len(seq) for seq in seqs) if is_prefill else -len([s for s in seqs if not s.is_unconditional])
+ return outputs, num_tokens
+
+ def is_finished(self):
+ return self.scheduler.is_finished()
+
+ def reset(self):
+ """
+ Reset the scheduler state and release all allocated blocks.
+ This should be called when an exception occurs during generation to prevent
+ KV cache block leaks that can cause 'deque index out of range' errors.
+ """
+ # Deallocate all running sequences
+ while self.scheduler.running:
+ seq = self.scheduler.running.popleft()
+ if seq.block_table: # Only deallocate if blocks are allocated
+ self.scheduler.block_manager.deallocate(seq)
+
+ # Deallocate all waiting sequences (they might have blocks from preemption)
+ while self.scheduler.waiting:
+ seq = self.scheduler.waiting.popleft()
+ if seq.block_table:
+ self.scheduler.block_manager.deallocate(seq)
+
+ def generate(
+ self,
+ prompts: list[str] | list[list[int]],
+ sampling_params: SamplingParams | list[SamplingParams],
+ use_tqdm: bool = True,
+ unconditional_prompts: list[str] | list[list[int]] | None = None,
+ ) -> list[str]:
+ # Ensure weights/KV cache are ready for lazy/pinned modes, and sync scheduler blocks.
+ self.model_runner.ensure_weights_loaded()
+ if (self.config.num_kvcache_blocks > 0 and
+ len(self.scheduler.block_manager.blocks) != self.config.num_kvcache_blocks):
+ self.scheduler.block_manager = BlockManager(
+ self.config.num_kvcache_blocks,
+ self.config.kvcache_block_size,
+ )
+ # Clean up any residual state from previous interrupted generations
+ # This prevents 'deque index out of range' errors from accumulated block leaks
+ if not self.is_finished():
+ self.reset()
+
+ if use_tqdm:
+ pbar = tqdm(total=len(prompts), desc="Generating", dynamic_ncols=True)
+ if not isinstance(sampling_params, list):
+ sampling_params = [sampling_params] * len(prompts)
+ # Seed once per request-batch; keeps deterministic decode without per-step overhead.
+ seed_to_apply = None
+ for sp in sampling_params:
+ seed_val = getattr(sp, "seed", None)
+ if seed_val is not None:
+ try:
+ seed_to_apply = int(seed_val)
+ break
+ except Exception:
+ seed_to_apply = None
+ if seed_to_apply is not None:
+ torch.manual_seed(seed_to_apply)
+ if torch.cuda.is_available():
+ torch.cuda.manual_seed(seed_to_apply)
+ if unconditional_prompts is None:
+ unconditional_prompts = [None] * len(prompts)
+ for prompt, sp, uncond_prompt in zip(prompts, sampling_params, unconditional_prompts):
+ self.add_request(prompt, sp, uncond_prompt)
+ outputs = {}
+ prefill_throughput = decode_throughput = 0.
+ try:
+ while not self.is_finished():
+ t = perf_counter()
+ output, num_tokens = self.step()
+ if use_tqdm:
+ if num_tokens > 0:
+ prefill_throughput = num_tokens / (perf_counter() - t)
+ else:
+ decode_throughput = -num_tokens / (perf_counter() - t)
+ pbar.set_postfix({
+ "Prefill": f"{int(prefill_throughput)}tok/s",
+ "Decode": f"{int(decode_throughput)}tok/s",
+ })
+ for seq_id, token_ids in output:
+ outputs[seq_id] = token_ids
+ if use_tqdm:
+ pbar.update(1)
+ except Exception:
+ # Clean up on exception to prevent block leaks
+ self.reset()
+ raise
+ finally:
+ if use_tqdm:
+ pbar.close()
+
+ outputs = [outputs[seq_id] for seq_id in sorted(outputs.keys())]
+ outputs = [{"text": self.tokenizer.decode(token_ids), "token_ids": token_ids} for token_ids in outputs]
+ return outputs
diff --git a/shared/llm_engines/nanovllm/engine/model_runner.py b/shared/llm_engines/nanovllm/engine/model_runner.py
new file mode 100644
index 0000000..f9015a5
--- /dev/null
+++ b/shared/llm_engines/nanovllm/engine/model_runner.py
@@ -0,0 +1,814 @@
+import pickle
+import torch
+import torch.distributed as dist
+from multiprocessing.synchronize import Event
+from multiprocessing.shared_memory import SharedMemory
+import sys
+
+from nanovllm.config import Config
+from nanovllm.engine.sequence import Sequence
+from nanovllm.models.qwen3 import Qwen3ForCausalLM
+from nanovllm.layers.sampler import Sampler
+from nanovllm.utils.context import set_context, get_context, reset_context
+from nanovllm.utils.loader import load_model, WeightStore
+
+import socket
+
+
+def find_available_port(start_port: int = 2333, max_attempts: int = 100) -> int:
+ """Find an available port starting from start_port.
+
+ Args:
+ start_port: The starting port number to check
+ max_attempts: Maximum number of ports to try
+
+ Returns:
+ An available port number
+
+ Raises:
+ RuntimeError: If no available port is found within max_attempts
+ """
+ for i in range(max_attempts):
+ port = start_port + i
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind(('localhost', port))
+ return port
+ except OSError:
+ # Port is in use, try next one
+ continue
+ raise RuntimeError(f"Could not find an available port starting from {start_port} after {max_attempts} attempts")
+
+
+class ModelRunner:
+
+ def __init__(self, config: Config, rank: int, event: Event | list[Event]):
+ # Enable capturing scalar outputs to avoid graph breaks from Tensor.item() calls
+ torch._dynamo.config.capture_scalar_outputs = True
+
+ self.config = config
+ hf_config = config.hf_config
+ self.block_size = config.kvcache_block_size
+ self.enforce_eager = config.enforce_eager
+ self.world_size = config.tensor_parallel_size
+ self.rank = rank
+ self.event = event
+ if self.world_size > 1:
+ dist_port = find_available_port()
+ print(f"[debug]dist_port: {dist_port}")
+ # Use gloo backend on Windows, nccl on Linux/other platforms
+ backend = "gloo" if sys.platform == "win32" else "nccl"
+ dist.init_process_group(backend, f"tcp://127.0.0.1:{dist_port}", world_size=self.world_size, rank=rank)
+ torch.cuda.set_device(rank)
+ else:
+ if torch.cuda.is_available():
+ torch.cuda.set_device(0)
+ default_dtype = torch.get_default_dtype()
+ # Use dtype instead of deprecated torch_dtype
+ config_dtype = getattr(hf_config, 'dtype', getattr(hf_config, 'torch_dtype', None))
+
+ # Validate and convert config_dtype to a valid torch floating-point dtype
+ # Default to bfloat16 for CUDA (required for Flash Attention 2)
+ if config_dtype is None:
+ config_dtype = torch.bfloat16
+ elif isinstance(config_dtype, str):
+ # Convert string dtype to torch dtype
+ dtype_map = {
+ 'float32': torch.float32,
+ 'float16': torch.float16,
+ 'bfloat16': torch.bfloat16,
+ 'float64': torch.float64,
+ 'torch.float32': torch.float32,
+ 'torch.float16': torch.float16,
+ 'torch.bfloat16': torch.bfloat16,
+ 'torch.float64': torch.float64,
+ }
+ config_dtype = dtype_map.get(config_dtype.lower(), torch.bfloat16)
+ elif not isinstance(config_dtype, torch.dtype) or not config_dtype.is_floating_point:
+ # If not a valid floating-point torch dtype, default to bfloat16
+ config_dtype = torch.bfloat16
+
+ self.dtype = config_dtype # Save for later use
+ self.weight_load_mode = (config.weight_load_mode or "eager").lower()
+ self._weights_loaded = False
+ self._weight_store = None
+ self._is_quanto_int8 = False
+ self._graph_cache = {}
+ self._graph_cache_order = []
+ self._logits_bias_cache = {}
+ self._guard_counts = {}
+ self._guard_seen_details = set()
+ torch.set_default_dtype(config_dtype)
+ if self.weight_load_mode in ("lazy", "pinned"):
+ torch.set_default_device("cpu")
+ self.model = Qwen3ForCausalLM(hf_config)
+ self._weight_store = WeightStore(config.model_file or config.model_dir, mode=self.weight_load_mode)
+ self._is_quanto_int8 = bool(getattr(self._weight_store, "is_quanto_int8", False))
+ else:
+ torch.set_default_device("cuda")
+ self.model = Qwen3ForCausalLM(hf_config)
+ load_model(self.model, config.model_file or config.model_dir)
+ self._retie_word_embeddings_if_needed()
+ self._weights_loaded = True
+ self.sampler = Sampler()
+
+ # Pre-allocate buffers for sampling (optimization: avoid repeated tensor creation)
+ # Must be called before warmup_model() since it uses these buffers
+ self._allocate_sample_buffers()
+
+ if self._weights_loaded:
+ self.warmup_model()
+ self.allocate_kv_cache()
+ if not self.enforce_eager:
+ self.capture_cudagraph()
+
+ torch.set_default_device("cpu")
+ torch.set_default_dtype(default_dtype)
+
+ if self.world_size > 1:
+ if rank == 0:
+ self.shm = SharedMemory(name="nanovllm", create=True, size=2**20)
+ dist.barrier()
+ else:
+ dist.barrier()
+ self.shm = SharedMemory(name="nanovllm")
+ self.loop()
+
+ def ensure_weights_loaded(self):
+ if self._weights_loaded:
+ return
+ default_dtype = torch.get_default_dtype()
+ torch.set_default_dtype(self.dtype)
+ torch.set_default_device("cuda")
+ if self._is_quanto_int8:
+ for module in self.model.modules():
+ prepare = getattr(module, "prepare_for_quantized_load", None)
+ if callable(prepare):
+ prepare()
+ self.model = self.model.to("cuda")
+ load_model(self.model, "", weight_store=self._weight_store)
+ self._retie_word_embeddings_if_needed()
+ self._weights_loaded = True
+ self.warmup_model()
+ self.allocate_kv_cache()
+ if not self.enforce_eager:
+ self.capture_cudagraph()
+ torch.set_default_device("cpu")
+ torch.set_default_dtype(default_dtype)
+
+ def _retie_word_embeddings_if_needed(self):
+ # Some quantized checkpoints omit lm_head.weight and rely on tied embeddings.
+ # After device moves/load cycles, the tie can be broken; restore it explicitly.
+ try:
+ lm_head = getattr(self.model, "lm_head", None)
+ embed = getattr(self.model, "embed_tokens", None)
+ if lm_head is None or embed is None:
+ return
+ lm_w = getattr(lm_head, "weight", None)
+ emb_w = getattr(embed, "weight", None)
+ if lm_w is None or emb_w is None:
+ return
+ if lm_w.shape != emb_w.shape:
+ return
+ if lm_w.data_ptr() != emb_w.data_ptr():
+ lm_head.weight.data = emb_w.data
+ except Exception:
+ return
+
+ def unload_weights(self):
+ if not self._weights_loaded:
+ return
+ try:
+ self.model = self.model.to("cpu")
+ except Exception:
+ pass
+ # Clear attention KV cache refs so we don't write into freed storage later.
+ try:
+ for module in self.model.modules():
+ if hasattr(module, "k_cache") and hasattr(module, "v_cache"):
+ module.k_cache = module.v_cache = torch.tensor([])
+ except Exception:
+ pass
+ if hasattr(self, "kv_cache"):
+ try:
+ del self.kv_cache
+ except Exception:
+ pass
+ # CUDA graphs captured against previous weight/KV pointers are unsafe after unload/reload.
+ # Force recapture on next load to avoid stale-pointer illegal memory access.
+ try:
+ self.clear_graph_cache()
+ except Exception:
+ pass
+ try:
+ self.graphs = {}
+ self.graph_vars = {}
+ self.graph_bs = []
+ self.graph_pool = None
+ except Exception:
+ pass
+ try:
+ torch.cuda.empty_cache()
+ except Exception:
+ pass
+ self._logits_bias_cache.clear()
+ self._weights_loaded = False
+
+ def _get_graph_capture_signature(self):
+ model_ptr = -1
+ kv_ptr = -1
+ try:
+ first_param = next(self.model.parameters())
+ if first_param.is_cuda:
+ model_ptr = int(first_param.data_ptr())
+ except Exception:
+ pass
+ try:
+ if hasattr(self, "kv_cache") and torch.is_tensor(self.kv_cache) and self.kv_cache.is_cuda:
+ kv_ptr = int(self.kv_cache.data_ptr())
+ except Exception:
+ pass
+ return (model_ptr, kv_ptr, int(self.config.max_model_len), int(self.config.max_num_seqs))
+
+ def _drop_graph_cache_entry(self, cache_key):
+ entry = self._graph_cache.pop(cache_key, None)
+ if cache_key in self._graph_cache_order:
+ self._graph_cache_order.remove(cache_key)
+ if entry is None:
+ return
+ try:
+ del entry["graphs"]
+ del entry["pool"]
+ del entry["vars"]
+ del entry["bs"]
+ except Exception:
+ pass
+
+ def clear_graph_cache(self):
+ if self._graph_cache:
+ for key in list(self._graph_cache.keys()):
+ self._drop_graph_cache_entry(key)
+ self._graph_cache.clear()
+ self._graph_cache_order.clear()
+
+ def _note_guard(self, name: str, detail: str | None = None):
+ count = self._guard_counts.get(name, 0) + 1
+ self._guard_counts[name] = count
+ if detail:
+ detail_key = (name, detail)
+ if detail_key not in self._guard_seen_details:
+ print(f"[nanovllm][guard] {name}: {detail}")
+ self._guard_seen_details.add(detail_key)
+ return
+ if count == 1:
+ print(f"[nanovllm][guard] {name}")
+
+ def reset_guard_counts(self):
+ self._guard_counts.clear()
+ self._guard_seen_details.clear()
+
+ def get_guard_counts(self, reset: bool = False):
+ counts = dict(self._guard_counts)
+ if reset:
+ self.reset_guard_counts()
+ return counts
+
+ def _get_logits_bias(self, seq: Sequence, logits: torch.Tensor):
+ bias = getattr(seq, "logits_bias", None)
+ if bias is None or not torch.is_tensor(bias):
+ return None
+ key = (id(bias), logits.device, logits.dtype)
+ cached = self._logits_bias_cache.get(key)
+ if cached is not None:
+ return cached
+ cached = bias.to(device=logits.device, dtype=logits.dtype)
+ self._logits_bias_cache[key] = cached
+ return cached
+
+ @staticmethod
+ def _apply_logits_bias(logits_row: torch.Tensor, bias: torch.Tensor):
+ logits_row.add_(bias)
+
+ def _allocate_sample_buffers(self):
+ """Pre-allocate reusable buffers for sampling to avoid repeated tensor creation."""
+ max_bs = self.config.max_num_seqs
+ max_tokens = self.config.max_num_batched_tokens
+ max_num_blocks = (self.config.max_model_len + self.block_size - 1) // self.block_size
+
+ # Pre-allocate pinned memory buffers on CPU for fast transfer
+ # Must explicitly specify device="cpu" since default device may be "cuda"
+ self._cpu_temperatures = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)
+ self._cpu_cfg_scales = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)
+ self._cpu_top_ks = torch.zeros(max_bs, dtype=torch.int32, device="cpu", pin_memory=True)
+ self._cpu_top_ps = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)
+ self._cpu_repetition_penalties = torch.zeros(max_bs, dtype=torch.float32, device="cpu", pin_memory=True)
+
+ # Pre-allocate decode buffers on CPU with pinned memory
+ self._cpu_input_ids = torch.zeros(max_bs, dtype=torch.int64, device="cpu", pin_memory=True)
+ self._cpu_positions = torch.zeros(max_bs, dtype=torch.int64, device="cpu", pin_memory=True)
+ self._cpu_slot_mapping = torch.zeros(max_bs, dtype=torch.int32, device="cpu", pin_memory=True)
+ self._cpu_context_lens = torch.zeros(max_bs, dtype=torch.int32, device="cpu", pin_memory=True)
+
+ # Pre-allocate prefill buffers on CPU with pinned memory (optimization to avoid repeated tensor creation)
+ self._cpu_prefill_input_ids = torch.zeros(max_tokens, dtype=torch.int64, device="cpu", pin_memory=True)
+ self._cpu_prefill_positions = torch.zeros(max_tokens, dtype=torch.int64, device="cpu", pin_memory=True)
+ self._cpu_prefill_cu_seqlens = torch.zeros(max_bs + 1, dtype=torch.int32, device="cpu", pin_memory=True)
+ self._cpu_prefill_slot_mapping = torch.zeros(max_tokens, dtype=torch.int32, device="cpu", pin_memory=True)
+
+ # Pre-allocate block tables buffer (shared by both decode and prefill)
+ self._cpu_block_tables = torch.zeros(max_bs, max_num_blocks, dtype=torch.int32, device="cpu", pin_memory=True)
+
+ # Pre-allocate buffer for sequence token IDs (used in logits processor and sampler)
+ # Max length is max_model_len since sequences can be that long
+ self._seq_token_ids_buffer = torch.zeros(max_bs, self.config.max_model_len, dtype=torch.int64, device="cpu", pin_memory=True)
+
+ def exit(self):
+ if self.world_size > 1:
+ self.shm.close()
+ dist.barrier()
+ if self.rank == 0:
+ self.shm.unlink()
+ if not self.enforce_eager:
+ if hasattr(self, "graphs"):
+ del self.graphs
+ if hasattr(self, "graph_pool"):
+ del self.graph_pool
+ try:
+ torch.cuda.synchronize()
+ except Exception:
+ pass
+ if dist.is_initialized():
+ dist.destroy_process_group()
+
+ def loop(self):
+ while True:
+ method_name, args = self.read_shm()
+ self.call(method_name, *args)
+ if method_name == "exit":
+ break
+
+ def read_shm(self):
+ assert self.world_size > 1 and self.rank > 0
+ self.event.wait()
+ n = int.from_bytes(self.shm.buf[0:4], "little")
+ method_name, *args = pickle.loads(self.shm.buf[4:n+4])
+ self.event.clear()
+ return method_name, args
+
+ def write_shm(self, method_name, *args):
+ assert self.world_size > 1 and self.rank == 0
+ data = pickle.dumps([method_name, *args])
+ n = len(data)
+ self.shm.buf[0:4] = n.to_bytes(4, "little")
+ self.shm.buf[4:n+4] = data
+ for event in self.event:
+ event.set()
+
+ def call(self, method_name, *args):
+ if self.world_size > 1 and self.rank == 0:
+ self.write_shm(method_name, *args)
+ method = getattr(self, method_name, None)
+ return method(*args)
+
+ def warmup_model(self):
+ torch.cuda.empty_cache()
+ torch.cuda.reset_peak_memory_stats()
+ max_num_batched_tokens, max_model_len = self.config.max_num_batched_tokens, self.config.max_model_len
+ num_seqs = min(max_num_batched_tokens // max_model_len, self.config.max_num_seqs)
+ seqs = [Sequence([0] * max_model_len) for _ in range(num_seqs)]
+ self.run(seqs, True)
+ torch.cuda.empty_cache()
+
+ def allocate_kv_cache(self):
+ config = self.config
+ hf_config = config.hf_config
+ free, total = torch.cuda.mem_get_info()
+ current = torch.cuda.memory_stats()["allocated_bytes.all.current"]
+ num_kv_heads = hf_config.num_key_value_heads // self.world_size
+ head_dim = getattr(hf_config, "head_dim", hf_config.hidden_size // hf_config.num_attention_heads)
+ block_bytes = 2 * hf_config.num_hidden_layers * self.block_size * num_kv_heads * head_dim * self.dtype.itemsize
+
+ # Calculate available memory for KV cache
+ # After warmup_model, empty_cache has been called, so current represents model memory only
+ # Use free memory but respect the gpu_memory_utilization limit
+ target_total_usage = total * config.gpu_memory_utilization
+ available_for_kv_cache = min(free * 0.9, target_total_usage - current)
+
+ # Ensure we have positive memory available
+ if available_for_kv_cache <= 0:
+ available_for_kv_cache = free * 0.5 # Fallback to 50% of free memory
+
+ config.num_kvcache_blocks = max(1, int(available_for_kv_cache) // block_bytes)
+ # Cap KV cache blocks to what is required by max_model_len and max_num_seqs.
+ # This keeps VRAM usage proportional to the requested token budget (incl. CFG).
+ required_blocks_per_seq = (config.max_model_len + self.block_size - 1) // self.block_size
+ required_total_blocks = required_blocks_per_seq * max(1, config.max_num_seqs)
+ if required_total_blocks > 0:
+ config.num_kvcache_blocks = min(config.num_kvcache_blocks, required_total_blocks)
+ if config.num_kvcache_blocks <= 0:
+ raise RuntimeError(
+ f"Insufficient GPU memory for KV cache. "
+ f"Free: {free / 1024**3:.2f} GB, Current: {current / 1024**3:.2f} GB, "
+ f"Available for KV: {available_for_kv_cache / 1024**3:.2f} GB, "
+ f"Block size: {block_bytes / 1024**2:.2f} MB"
+ )
+ self.kv_cache = torch.empty(
+ 2,
+ hf_config.num_hidden_layers,
+ config.num_kvcache_blocks,
+ self.block_size,
+ num_kv_heads,
+ head_dim,
+ device="cuda",
+ dtype=self.dtype,
+ )
+ layer_id = 0
+ for module in self.model.modules():
+ if hasattr(module, "k_cache") and hasattr(module, "v_cache"):
+ module.k_cache = self.kv_cache[0, layer_id]
+ module.v_cache = self.kv_cache[1, layer_id]
+ layer_id += 1
+
+ def prepare_block_tables(self, seqs: list[Sequence]):
+ max_len = max(len(seq.block_table) for seq in seqs)
+ block_tables = [seq.block_table + [-1] * (max_len - len(seq.block_table)) for seq in seqs]
+ block_tables = torch.tensor(block_tables, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)
+ return block_tables
+
+ def prepare_prefill(self, seqs: list[Sequence]):
+ input_ids = []
+ positions = []
+ cu_seqlens_q = [0]
+ cu_seqlens_k = [0]
+ max_seqlen_q = 0
+ max_seqlen_k = 0
+ slot_mapping = []
+ block_tables = None
+ for seq in seqs:
+ seqlen = len(seq)
+ input_ids.extend(seq[seq.num_cached_tokens:])
+ positions.extend(list(range(seq.num_cached_tokens, seqlen)))
+ seqlen_q = seqlen - seq.num_cached_tokens
+ seqlen_k = seqlen
+ cu_seqlens_q.append(cu_seqlens_q[-1] + seqlen_q)
+ cu_seqlens_k.append(cu_seqlens_k[-1] + seqlen_k)
+ max_seqlen_q = max(seqlen_q, max_seqlen_q)
+ max_seqlen_k = max(seqlen_k, max_seqlen_k)
+ if not seq.block_table: # warmup: no blocks allocated yet
+ slot_mapping.extend([-1] * seqlen_q)
+ continue
+ for i in range(seq.num_cached_blocks, seq.num_blocks):
+ start = seq.block_table[i] * self.block_size
+ if i != seq.num_blocks - 1:
+ end = start + self.block_size
+ else:
+ end = start + seq.last_block_num_tokens
+ slot_mapping.extend(list(range(start, end)))
+ if cu_seqlens_k[-1] > cu_seqlens_q[-1]: # prefix cache
+ block_tables = self.prepare_block_tables(seqs)
+ input_ids = torch.tensor(input_ids, dtype=torch.int64, pin_memory=True).cuda(non_blocking=True)
+ positions = torch.tensor(positions, dtype=torch.int64, pin_memory=True).cuda(non_blocking=True)
+ cu_seqlens_q = torch.tensor(cu_seqlens_q, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)
+ cu_seqlens_k = torch.tensor(cu_seqlens_k, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)
+ slot_mapping = torch.tensor(slot_mapping, dtype=torch.int32, pin_memory=True).cuda(non_blocking=True)
+ set_context(True, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, slot_mapping, None, block_tables)
+ return input_ids, positions
+
+ def prepare_decode(self, seqs: list[Sequence]):
+ """Optimized decode preparation using pre-allocated buffers."""
+ bs = len(seqs)
+
+ # Use pre-allocated CPU buffers
+ for i, seq in enumerate(seqs):
+ self._cpu_input_ids[i] = seq.last_token
+ self._cpu_positions[i] = len(seq) - 1
+ self._cpu_context_lens[i] = len(seq)
+ self._cpu_slot_mapping[i] = seq.block_table[-1] * self.block_size + seq.last_block_num_tokens - 1
+
+ # Transfer to GPU using sliced views
+ input_ids = self._cpu_input_ids[:bs].cuda(non_blocking=True)
+ positions = self._cpu_positions[:bs].cuda(non_blocking=True)
+ slot_mapping = self._cpu_slot_mapping[:bs].cuda(non_blocking=True)
+ context_lens = self._cpu_context_lens[:bs].cuda(non_blocking=True)
+ block_tables = self.prepare_block_tables(seqs)
+ set_context(False, slot_mapping=slot_mapping, context_lens=context_lens, block_tables=block_tables)
+ return input_ids, positions
+
+ def prepare_sample(self, seqs: list[Sequence], is_cfg_batch: bool = False):
+ """Optimized sample preparation using pre-allocated buffers."""
+ if is_cfg_batch:
+ num_seqs = len(seqs) // 2
+ target_seqs = seqs[:num_seqs]
+ else:
+ num_seqs = len(seqs)
+ target_seqs = seqs
+
+ # Fill pre-allocated CPU buffers
+ top_ks_is_zero = True
+ top_ps_is_one = True
+ repetition_penalties_is_one = True
+ for i, seq in enumerate(target_seqs):
+ self._cpu_temperatures[i] = seq.temperature
+ self._cpu_cfg_scales[i] = seq.cfg_scale
+ self._cpu_top_ks[i] = seq.top_k if seq.top_k is not None else 0
+ if seq.top_k is not None and seq.top_k > 0:
+ top_ks_is_zero = False
+ self._cpu_top_ps[i] = seq.top_p if seq.top_p is not None else 1.0
+ if seq.top_p is not None and seq.top_p != 1.0:
+ top_ps_is_one = False
+ self._cpu_repetition_penalties[i] = seq.repetition_penalty if seq.repetition_penalty is not None else 1.0
+ if seq.repetition_penalty is not None and seq.repetition_penalty != 1.0:
+ repetition_penalties_is_one = False
+
+ # Transfer to GPU using sliced views (single batched transfer)
+ temperatures = self._cpu_temperatures[:num_seqs].cuda(non_blocking=True)
+ cfg_scales = self._cpu_cfg_scales[:num_seqs].cuda(non_blocking=True)
+ top_ks = self._cpu_top_ks[:num_seqs].cuda(non_blocking=True) if not top_ks_is_zero else None
+ top_ps = self._cpu_top_ps[:num_seqs].cuda(non_blocking=True) if not top_ps_is_one else None
+ repetition_penalties = self._cpu_repetition_penalties[:num_seqs].cuda(non_blocking=True) if not repetition_penalties_is_one else None
+
+ return temperatures, cfg_scales, top_ks, top_ps, repetition_penalties
+
+ @torch.inference_mode()
+ def run_model(self, input_ids: torch.Tensor, positions: torch.Tensor, is_prefill: bool):
+ if is_prefill or self.enforce_eager or input_ids.size(0) > 512:
+ return self.model.compute_logits(self.model(input_ids, positions))
+ else:
+ bs = input_ids.size(0)
+ context = get_context()
+
+ # Check if block_tables size exceeds pre-allocated buffer size
+ # This can happen when conditional and unconditional sequences have different lengths
+ # in CFG mode, causing block_tables to have more columns than expected
+ max_num_blocks = self.graph_vars["block_tables"].size(1)
+ if context.block_tables.size(1) > max_num_blocks:
+ # Fall back to eager mode when block_tables is too large for CUDA graph
+ self._note_guard(
+ "cudagraph_fallback_block_table_cols",
+ f"requested={context.block_tables.size(1)} max={max_num_blocks}",
+ )
+ return self.model.compute_logits(self.model(input_ids, positions))
+
+ # Fix: Also check if block_tables row count matches batch size
+ # Dimension mismatch can cause CUDA illegal memory access during graph replay
+ if context.block_tables.size(0) != bs:
+ # Fall back to eager mode when block_tables row count doesn't match batch size
+ self._note_guard(
+ "cudagraph_fallback_block_table_rows",
+ f"rows={context.block_tables.size(0)} bs={bs}",
+ )
+ return self.model.compute_logits(self.model(input_ids, positions))
+
+ # Fix: Verify slot_mapping and context_lens dimensions match batch size
+ if context.slot_mapping.size(0) != bs or context.context_lens.size(0) != bs:
+ # Fall back to eager mode when dimensions don't match
+ self._note_guard(
+ "cudagraph_fallback_context_shape",
+ f"slot={context.slot_mapping.size(0)} ctx={context.context_lens.size(0)} bs={bs}",
+ )
+ return self.model.compute_logits(self.model(input_ids, positions))
+
+ graph = self.graphs[next(x for x in self.graph_bs if x >= bs)]
+ graph_vars = self.graph_vars
+ graph_vars["input_ids"][:bs] = input_ids
+ graph_vars["positions"][:bs] = positions
+ graph_vars["slot_mapping"].fill_(-1)
+ graph_vars["slot_mapping"][:bs] = context.slot_mapping
+ graph_vars["context_lens"].zero_()
+ graph_vars["context_lens"][:bs] = context.context_lens
+ # Clear block_tables first to ensure no stale data from previous runs
+ graph_vars["block_tables"][:bs].fill_(-1)
+ graph_vars["block_tables"][:bs, :context.block_tables.size(1)] = context.block_tables
+ graph.replay()
+ return self.model.compute_logits(graph_vars["outputs"][:bs])
+
+ def run(self, seqs: list[Sequence], is_prefill: bool) -> list[int]:
+ """Run model forward and sampling. For CFG sequences, batch is structured as:
+ [cond_seq1, cond_seq2, ..., uncond_seq1, uncond_seq2, ...]
+ where uncond_seqi is the paired unconditional sequence of cond_seqi."""
+ self.ensure_weights_loaded()
+ # Check if this is a CFG batch (contains paired conditional and unconditional sequences)
+ is_cfg_batch = seqs[0].cfg_scale > 1.0 and seqs[0].paired_seq is not None
+ if is_cfg_batch:
+ # CFG batch: seqs = [cond_seq1, cond_seq2, ..., uncond_seq1, uncond_seq2, ...]
+ num_cond = len(seqs) // 2
+ cond_seqs = seqs[:num_cond]
+ # uncond_seqs = seqs[num_cond:]
+
+ # Prepare inputs for both conditional and unconditional (they're already in the batch)
+ input_ids, positions = (self.prepare_prefill(seqs) if is_prefill else self.prepare_decode(seqs))
+ sample_params = self.prepare_sample(seqs, is_cfg_batch=True) if self.rank == 0 else None
+ if sample_params is not None:
+ temperatures, cfg_scales, top_ks, top_ps, repetition_penalties = sample_params
+ else:
+ temperatures = cfg_scales = top_ks = top_ps = repetition_penalties = None
+
+ # Run model forward (processes entire batch: cond + uncond)
+ logits_all = self.run_model(input_ids, positions, is_prefill)
+ reset_context()
+
+ if self.rank == 0:
+ # Split logits: first half is conditional, second half is unconditional
+ logits_cond = logits_all[:num_cond]
+ logits_uncond = logits_all[num_cond:]
+
+ # Apply repetition penalty to conditional logits (before CFG)
+ if repetition_penalties is not None:
+ for i, seq in enumerate(cond_seqs):
+ penalty = repetition_penalties[i].item()
+ if penalty != 1.0:
+ # Only penalize completion tokens (not prompt tokens)
+ completion_tokens = torch.tensor(seq.completion_token_ids, device=logits_cond.device)
+ if len(completion_tokens) > 0:
+ # Create token mask: mark tokens that appeared in completion
+ token_mask = torch.zeros(logits_cond.shape[1], dtype=torch.bool, device=logits_cond.device)
+ token_mask[completion_tokens] = True
+
+ # Apply standard repetition penalty formula (matching transformers implementation):
+ # For tokens in completion: if score < 0 then score * penalty, else score / penalty
+ penalty_scores = torch.where(
+ logits_cond[i] < 0,
+ logits_cond[i] * penalty,
+ logits_cond[i] / penalty
+ )
+ # Only apply penalty to tokens that appeared in completion
+ logits_cond[i] = torch.where(token_mask, penalty_scores, logits_cond[i])
+
+ # Apply CFG formula: logits_cfg = logits_uncond + cfg_scale * (logits_cond - logits_uncond)
+ cfg_scales_tensor = cfg_scales.unsqueeze(1) # [num_cond, 1]
+ logits_cfg = logits_uncond + cfg_scales_tensor * (logits_cond - logits_uncond)
+
+ # Apply optional per-sequence logits bias before processors/sampling.
+ for i, seq in enumerate(cond_seqs):
+ bias = self._get_logits_bias(seq, logits_cfg)
+ if bias is not None:
+ self._apply_logits_bias(logits_cfg[i], bias)
+
+ # Apply logits processor for constrained decoding (if any sequence has one)
+ for i, seq in enumerate(cond_seqs):
+ if seq.logits_processor is not None:
+ # Create input_ids tensor for this sequence
+ seq_input_ids = torch.tensor([seq.token_ids], device=logits_cfg.device)
+ # Apply processor to this sequence's logits
+ logits_cfg[i:i+1] = seq.logits_processor(seq_input_ids, logits_cfg[i:i+1])
+
+ # Prepare input_ids for sampler (for repetition penalty, though we already applied it)
+ # cond_input_ids = torch.tensor([seq.token_ids for seq in cond_seqs], device=logits_cfg.device)
+
+ # Sample from CFG logits
+ token_ids_cfg = self.sampler(
+ logits_cfg,
+ temperatures,
+ top_ks=top_ks if top_ks is not None else None,
+ top_ps=top_ps if top_ps is not None else None,
+ repetition_penalties=None, # Already applied above
+ # input_ids=cond_input_ids,
+ ).tolist()
+
+ # Update logits processor state after sampling
+ # NOTE: Only update for the first sequence since all sequences share the same processor
+ # Updating multiple times would cause duplicate state updates (e.g., codes_count += N instead of += 1)
+ if cond_seqs and cond_seqs[0].logits_processor_update_state is not None:
+ cond_seqs[0].logits_processor_update_state(token_ids_cfg[0])
+
+ # Return token_ids (will be applied to both conditional and unconditional sequences)
+ return token_ids_cfg
+ else:
+ return None
+ else:
+ # Normal batch (non-CFG)
+ input_ids, positions = (self.prepare_prefill(seqs) if is_prefill
+ else self.prepare_decode(seqs))
+ sample_params = self.prepare_sample(seqs, is_cfg_batch=False) if self.rank == 0 else None
+ if sample_params is not None:
+ temperatures, cfg_scales, top_ks, top_ps, repetition_penalties = sample_params
+ else:
+ temperatures = cfg_scales = top_ks = top_ps = repetition_penalties = None
+ logits = self.run_model(input_ids, positions, is_prefill)
+ reset_context()
+
+ if self.rank == 0:
+ # Apply repetition penalty to logits
+ if repetition_penalties is not None:
+ for i, seq in enumerate(seqs):
+ penalty = repetition_penalties[i].item()
+ if penalty != 1.0:
+ # Only penalize completion tokens (not prompt tokens)
+ completion_tokens = torch.tensor(seq.completion_token_ids, device=logits.device)
+ if len(completion_tokens) > 0:
+ # Create token mask: mark tokens that appeared in completion
+ token_mask = torch.zeros(logits.shape[1], dtype=torch.bool, device=logits.device)
+ token_mask[completion_tokens] = True
+
+ # Apply standard repetition penalty formula (matching transformers implementation):
+ # For tokens in completion: if score < 0 then score * penalty, else score / penalty
+ penalty_scores = torch.where(
+ logits[i] < 0,
+ logits[i] * penalty,
+ logits[i] / penalty
+ )
+ # Only apply penalty to tokens that appeared in completion
+ logits[i] = torch.where(token_mask, penalty_scores, logits[i])
+
+ # Apply logits processor for constrained decoding (if any sequence has one)
+ # Clone logits to avoid in-place update issues in inference mode
+ logits = logits.clone()
+ for i, seq in enumerate(seqs):
+ bias = self._get_logits_bias(seq, logits)
+ if bias is not None:
+ self._apply_logits_bias(logits[i], bias)
+ for i, seq in enumerate(seqs):
+ if seq.logits_processor is not None:
+ # Create input_ids tensor for this sequence
+ seq_input_ids = torch.tensor([seq.token_ids], device=logits.device)
+ # Apply processor to this sequence's logits (clone to avoid inference mode issues)
+ processed = seq.logits_processor(seq_input_ids, logits[i:i+1].clone())
+ logits[i] = processed[0]
+
+ # Prepare input_ids for sampler
+ # seq_input_ids = torch.tensor([seq.token_ids for seq in seqs], device=logits.device)
+
+ token_ids = self.sampler(
+ logits,
+ temperatures,
+ top_ks=top_ks if top_ks is not None else None,
+ top_ps=top_ps if top_ps is not None else None,
+ repetition_penalties=None, # Already applied above
+ # input_ids=seq_input_ids,
+ ).tolist()
+
+ # Update logits processor state after sampling
+ # NOTE: Only update for the first sequence since all sequences may share the same processor
+ # (when using a single SamplingParams for batch generation)
+ # Updating multiple times would cause duplicate state updates (e.g., codes_count += N instead of += 1)
+ if seqs and seqs[0].logits_processor_update_state is not None:
+ seqs[0].logits_processor_update_state(token_ids[0])
+
+ return token_ids
+ else:
+ return None
+
+ @torch.inference_mode()
+ def capture_cudagraph(self):
+ config = self.config
+ cache_key = (config.max_model_len, config.max_num_seqs)
+ cached = self._graph_cache.get(cache_key)
+ if cached is not None:
+ current_sig = self._get_graph_capture_signature()
+ if cached.get("sig") == current_sig:
+ self.graphs = cached["graphs"]
+ self.graph_pool = cached["pool"]
+ self.graph_vars = cached["vars"]
+ self.graph_bs = cached["bs"]
+ if cache_key in self._graph_cache_order:
+ self._graph_cache_order.remove(cache_key)
+ self._graph_cache_order.append(cache_key)
+ return
+ self._drop_graph_cache_entry(cache_key)
+ hf_config = config.hf_config
+ max_bs = min(self.config.max_num_seqs, 512)
+ max_num_blocks = (config.max_model_len + self.block_size - 1) // self.block_size
+ input_ids = torch.zeros(max_bs, dtype=torch.int64)
+ positions = torch.zeros(max_bs, dtype=torch.int64)
+ slot_mapping = torch.zeros(max_bs, dtype=torch.int32)
+ context_lens = torch.zeros(max_bs, dtype=torch.int32)
+ block_tables = torch.zeros(max_bs, max_num_blocks, dtype=torch.int32)
+ outputs = torch.zeros(max_bs, hf_config.hidden_size)
+ self.graph_bs = [1, 2, 4, 8] + list(range(16, max_bs + 1, 16))
+ self.graphs = {}
+ self.graph_pool = None
+
+ for bs in reversed(self.graph_bs):
+ graph = torch.cuda.CUDAGraph()
+ set_context(False, slot_mapping=slot_mapping[:bs], context_lens=context_lens[:bs], block_tables=block_tables[:bs])
+ outputs[:bs] = self.model(input_ids[:bs], positions[:bs]) # warmup
+ with torch.cuda.graph(graph, self.graph_pool):
+ outputs[:bs] = self.model(input_ids[:bs], positions[:bs]) # capture
+ if self.graph_pool is None:
+ self.graph_pool = graph.pool()
+ self.graphs[bs] = graph
+ torch.cuda.synchronize()
+ reset_context()
+
+ self.graph_vars = dict(
+ input_ids=input_ids,
+ positions=positions,
+ slot_mapping=slot_mapping,
+ context_lens=context_lens,
+ block_tables=block_tables,
+ outputs=outputs,
+ )
+ self._graph_cache[cache_key] = {
+ "graphs": self.graphs,
+ "pool": self.graph_pool,
+ "vars": self.graph_vars,
+ "bs": self.graph_bs,
+ "sig": self._get_graph_capture_signature(),
+ }
+ if cache_key in self._graph_cache_order:
+ self._graph_cache_order.remove(cache_key)
+ self._graph_cache_order.append(cache_key)
+ while len(self._graph_cache_order) > 5:
+ old_key = self._graph_cache_order.pop(0)
+ self._drop_graph_cache_entry(old_key)
diff --git a/shared/llm_engines/nanovllm/engine/scheduler.py b/shared/llm_engines/nanovllm/engine/scheduler.py
new file mode 100644
index 0000000..3178c22
--- /dev/null
+++ b/shared/llm_engines/nanovllm/engine/scheduler.py
@@ -0,0 +1,230 @@
+from collections import deque
+
+from nanovllm.config import Config
+from nanovllm.engine.sequence import Sequence, SequenceStatus
+from nanovllm.engine.block_manager import BlockManager
+
+
+class Scheduler:
+
+ def __init__(self, config: Config):
+ self.max_num_seqs = config.max_num_seqs
+ self.max_num_batched_tokens = config.max_num_batched_tokens
+ self.eos = config.eos
+ self.block_manager = BlockManager(config.num_kvcache_blocks, config.kvcache_block_size)
+ self.waiting: deque[Sequence] = deque()
+ self.running: deque[Sequence] = deque()
+
+ def is_finished(self):
+ return not self.waiting and not self.running
+
+ def add(self, seq: Sequence):
+ self.waiting.append(seq)
+
+ def schedule(self) -> tuple[list[Sequence], bool]:
+ # prefill
+ scheduled_seqs = []
+ num_seqs = 0
+ num_batched_tokens = 0
+ processed_seqs = set() # Track processed sequences to handle CFG pairs
+
+ while self.waiting and num_seqs < self.max_num_seqs:
+ seq = self.waiting[0]
+
+ # For CFG sequences, ensure conditional and unconditional are scheduled together
+ if seq.cfg_scale > 1.0 and seq.paired_seq is not None and not seq.is_unconditional:
+ # This is a conditional sequence, need to schedule its paired unconditional sequence too
+ paired_seq = seq.paired_seq
+ if paired_seq.status != SequenceStatus.WAITING:
+ # Paired sequence not in waiting, skip this conditional sequence for now
+ break
+
+ # Calculate tokens for both sequences
+ total_tokens = (len(seq) - seq.num_cached_tokens) + (len(paired_seq) - paired_seq.num_cached_tokens)
+
+ # FIX: Check if we have enough blocks for BOTH sequences combined
+ # The old check was wrong: it checked each sequence independently,
+ # but didn't account for the total blocks needed by both
+ total_blocks_needed = seq.num_blocks + paired_seq.num_blocks
+ can_allocate_both = len(self.block_manager.free_block_ids) >= total_blocks_needed
+
+ if num_batched_tokens + total_tokens > self.max_num_batched_tokens or not can_allocate_both:
+ break
+
+ # Schedule both sequences: conditional first, then unconditional
+ for s in [seq, paired_seq]:
+ num_seqs += 1
+ self.block_manager.allocate(s)
+ num_batched_tokens += len(s) - s.num_cached_tokens
+ s.status = SequenceStatus.RUNNING
+ self.waiting.remove(s)
+ self.running.append(s)
+ scheduled_seqs.append(s)
+ processed_seqs.add(s.seq_id)
+ else:
+ # Normal sequence or unconditional sequence (already processed with its conditional)
+ if seq.seq_id in processed_seqs:
+ # Skip if already processed as part of a CFG pair
+ self.waiting.popleft()
+ continue
+
+ if num_batched_tokens + len(seq) > self.max_num_batched_tokens or not self.block_manager.can_allocate(seq):
+ break
+ num_seqs += 1
+ self.block_manager.allocate(seq)
+ num_batched_tokens += len(seq) - seq.num_cached_tokens
+ seq.status = SequenceStatus.RUNNING
+ self.waiting.popleft()
+ self.running.append(seq)
+ scheduled_seqs.append(seq)
+
+ if scheduled_seqs:
+ # For CFG batches, ensure conditional sequences come before their unconditional pairs
+ cfg_cond_seqs = [s for s in scheduled_seqs if s.cfg_scale > 1.0 and not s.is_unconditional]
+ cfg_uncond_seqs = [s for s in scheduled_seqs if s.is_unconditional]
+ non_cfg_seqs = [s for s in scheduled_seqs if s.cfg_scale <= 1.0]
+
+ # Reorder: non-CFG, then CFG conditional, then CFG unconditional
+ scheduled_seqs = non_cfg_seqs + cfg_cond_seqs + cfg_uncond_seqs
+ return scheduled_seqs, True
+
+ # decode
+ processed_seqs = set()
+ temp_running = list(self.running) # Work with a copy
+
+ while temp_running and num_seqs < self.max_num_seqs:
+ seq = temp_running.pop(0)
+
+ # For CFG sequences, ensure conditional and unconditional are scheduled together
+ if seq.cfg_scale > 1.0 and seq.paired_seq is not None and not seq.is_unconditional:
+ paired_seq = seq.paired_seq
+ if paired_seq not in temp_running:
+ # Paired sequence not available, skip for now
+ continue
+
+ # Remove paired_seq from temp_running
+ temp_running.remove(paired_seq)
+
+ # FIX: Check if we have enough blocks for BOTH sequences to append
+ # Each sequence needs 1 block when at block boundary (len % block_size == 1)
+ block_size = self.block_manager.block_size
+ blocks_needed_seq = 1 if len(seq) % block_size == 1 else 0
+ blocks_needed_paired = 1 if len(paired_seq) % block_size == 1 else 0
+ total_blocks_needed = blocks_needed_seq + blocks_needed_paired
+ can_append_both = len(self.block_manager.free_block_ids) >= total_blocks_needed
+
+ if not can_append_both:
+ # Try preempting other sequences
+ preempted = False
+ while not can_append_both and temp_running:
+ other_seq = temp_running.pop(0)
+ if other_seq != seq and other_seq != paired_seq:
+ self.preempt(other_seq)
+ # Recalculate with the same correct logic
+ can_append_both = len(self.block_manager.free_block_ids) >= total_blocks_needed
+ preempted = True
+ else:
+ temp_running.append(other_seq)
+ break
+
+ if not can_append_both:
+ # Can't schedule this pair right now
+ temp_running.append(seq)
+ temp_running.append(paired_seq)
+ continue
+
+ # Schedule both sequences
+ for s in [seq, paired_seq]:
+ num_seqs += 1
+ self.block_manager.may_append(s)
+ scheduled_seqs.append(s)
+ processed_seqs.add(s.seq_id)
+ # Remove from actual running list if scheduled
+ if s in self.running:
+ self.running.remove(s)
+ else:
+ # Normal sequence or unconditional (already processed)
+ if seq.seq_id in processed_seqs:
+ continue
+
+ while not self.block_manager.can_append(seq):
+ if temp_running:
+ other_seq = temp_running.pop(0)
+ if other_seq != seq:
+ self.preempt(other_seq)
+ else:
+ temp_running.append(other_seq)
+ break
+ else:
+ self.preempt(seq)
+ if seq in self.running:
+ self.running.remove(seq)
+ break
+ else:
+ num_seqs += 1
+ self.block_manager.may_append(seq)
+ scheduled_seqs.append(seq)
+ if seq in self.running:
+ self.running.remove(seq)
+
+ assert scheduled_seqs
+
+ # For CFG batches in decode, ensure conditional sequences come before unconditional
+ cfg_cond_seqs = [s for s in scheduled_seqs if s.cfg_scale > 1.0 and not s.is_unconditional]
+ cfg_uncond_seqs = [s for s in scheduled_seqs if s.is_unconditional]
+ non_cfg_seqs = [s for s in scheduled_seqs if s.cfg_scale <= 1.0]
+ scheduled_seqs = non_cfg_seqs + cfg_cond_seqs + cfg_uncond_seqs
+
+ self.running.extendleft(reversed(scheduled_seqs))
+ return scheduled_seqs, False
+
+ def preempt(self, seq: Sequence):
+ seq.status = SequenceStatus.WAITING
+ self.block_manager.deallocate(seq)
+ self.waiting.appendleft(seq)
+
+ def postprocess(self, seqs: list[Sequence], token_ids: list[int]) -> list[bool]:
+ # Check if this is a CFG batch
+ is_cfg_batch = False
+ if len(seqs) > 0 and seqs[0].cfg_scale > 1.0 and seqs[0].paired_seq is not None:
+ num_cond = len(seqs) // 2
+ is_cfg_batch = (num_cond > 0 and
+ not seqs[0].is_unconditional and
+ seqs[num_cond].is_unconditional)
+
+ if is_cfg_batch:
+ # CFG batch: seqs = [cond_seq1, cond_seq2, ..., uncond_seq1, uncond_seq2, ...]
+ # token_ids correspond to conditional sequences only (sampled from CFG logits)
+ num_cond = len(seqs) // 2
+ cond_seqs = seqs[:num_cond]
+ uncond_seqs = seqs[num_cond:]
+
+ # Apply the same sampled token to both conditional and unconditional sequences
+ for i, (cond_seq, uncond_seq, token_id) in enumerate(zip(cond_seqs, uncond_seqs, token_ids)):
+ cond_seq.append_token(token_id)
+ uncond_seq.append_token(token_id) # Same token for unconditional
+
+ # Check if either sequence is finished
+ cond_finished = ((not cond_seq.ignore_eos and token_id == self.eos) or
+ cond_seq.num_completion_tokens == cond_seq.max_tokens)
+ uncond_finished = ((not uncond_seq.ignore_eos and token_id == self.eos) or
+ uncond_seq.num_completion_tokens == uncond_seq.max_tokens)
+
+ if cond_finished or uncond_finished:
+ # Mark both as finished
+ cond_seq.status = SequenceStatus.FINISHED
+ uncond_seq.status = SequenceStatus.FINISHED
+ self.block_manager.deallocate(cond_seq)
+ self.block_manager.deallocate(uncond_seq)
+ if cond_seq in self.running:
+ self.running.remove(cond_seq)
+ if uncond_seq in self.running:
+ self.running.remove(uncond_seq)
+ else:
+ # Normal batch
+ for seq, token_id in zip(seqs, token_ids):
+ seq.append_token(token_id)
+ if (not seq.ignore_eos and token_id == self.eos) or seq.num_completion_tokens == seq.max_tokens:
+ seq.status = SequenceStatus.FINISHED
+ self.block_manager.deallocate(seq)
+ self.running.remove(seq)
diff --git a/shared/llm_engines/nanovllm/engine/sequence.py b/shared/llm_engines/nanovllm/engine/sequence.py
new file mode 100644
index 0000000..bda2e53
--- /dev/null
+++ b/shared/llm_engines/nanovllm/engine/sequence.py
@@ -0,0 +1,97 @@
+from copy import copy
+from enum import Enum, auto
+from itertools import count
+from typing import Optional, Callable, Any
+
+from nanovllm.sampling_params import SamplingParams
+
+
+class SequenceStatus(Enum):
+ WAITING = auto()
+ RUNNING = auto()
+ FINISHED = auto()
+
+
+class Sequence:
+ block_size = 256
+ counter = count()
+
+ def __init__(self, token_ids: list[int], sampling_params = SamplingParams(), is_unconditional: bool = False, conditional_seq = None):
+ self.seq_id = next(Sequence.counter)
+ self.status = SequenceStatus.WAITING
+ self.token_ids = copy(token_ids)
+ self.last_token = token_ids[-1]
+ self.num_tokens = len(self.token_ids)
+ self.num_prompt_tokens = len(token_ids)
+ self.num_cached_tokens = 0
+ self.block_table = []
+ self.temperature = sampling_params.temperature
+ self.max_tokens = sampling_params.max_tokens
+ self.ignore_eos = sampling_params.ignore_eos
+ self.cfg_scale = sampling_params.cfg_scale
+ self.top_k = sampling_params.top_k
+ self.top_p = sampling_params.top_p
+ self.repetition_penalty = sampling_params.repetition_penalty
+ # For CFG: mark if this is an unconditional sequence
+ self.is_unconditional = is_unconditional
+ # For CFG: reference to the corresponding conditional sequence (if this is unconditional)
+ # For conditional sequences, this points to the unconditional sequence
+ self.paired_seq = conditional_seq # For conditional seq, points to uncond; for uncond seq, points to cond
+ # For constrained decoding: logits processor and state update callback
+ self.logits_processor: Optional[Any] = sampling_params.logits_processor
+ self.logits_processor_update_state: Optional[Callable[[int], None]] = sampling_params.logits_processor_update_state
+ self.logits_bias: Optional[Any] = sampling_params.logits_bias
+
+ def __len__(self):
+ return self.num_tokens
+
+ def __getitem__(self, key):
+ return self.token_ids[key]
+
+ @property
+ def is_finished(self):
+ return self.status == SequenceStatus.FINISHED
+
+ @property
+ def num_completion_tokens(self):
+ return self.num_tokens - self.num_prompt_tokens
+
+ @property
+ def prompt_token_ids(self):
+ return self.token_ids[:self.num_prompt_tokens]
+
+ @property
+ def completion_token_ids(self):
+ return self.token_ids[self.num_prompt_tokens:]
+
+ @property
+ def num_cached_blocks(self):
+ return self.num_cached_tokens // self.block_size
+
+ @property
+ def num_blocks(self):
+ return (self.num_tokens + self.block_size - 1) // self.block_size
+
+ @property
+ def last_block_num_tokens(self):
+ return self.num_tokens - (self.num_blocks - 1) * self.block_size
+
+ def block(self, i):
+ assert 0 <= i < self.num_blocks
+ return self.token_ids[i*self.block_size: (i+1)*self.block_size]
+
+ def append_token(self, token_id: int):
+ self.token_ids.append(token_id)
+ self.last_token = token_id
+ self.num_tokens += 1
+
+ def __getstate__(self):
+ return (self.num_tokens, self.num_prompt_tokens, self.num_cached_tokens, self.block_table,
+ self.token_ids if self.num_completion_tokens == 0 else self.last_token)
+
+ def __setstate__(self, state):
+ self.num_tokens, self.num_prompt_tokens, self.num_cached_tokens, self.block_table = state[:-1]
+ if self.num_completion_tokens == 0:
+ self.token_ids = state[-1]
+ else:
+ self.last_token = state[-1]
diff --git a/shared/llm_engines/nanovllm/layers/activation.py b/shared/llm_engines/nanovllm/layers/activation.py
new file mode 100644
index 0000000..041ee20
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/activation.py
@@ -0,0 +1,14 @@
+import torch
+from torch import nn
+import torch.nn.functional as F
+
+
+class SiluAndMul(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+
+ @torch.compile
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x, y = x.chunk(2, -1)
+ return F.silu(x) * y
diff --git a/shared/llm_engines/nanovllm/layers/attention.py b/shared/llm_engines/nanovllm/layers/attention.py
new file mode 100644
index 0000000..e416139
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/attention.py
@@ -0,0 +1,75 @@
+import torch
+from torch import nn
+import triton
+import triton.language as tl
+
+from flash_attn import flash_attn_varlen_func, flash_attn_with_kvcache
+from nanovllm.utils.context import get_context
+
+
+def store_kvcache_kernel(
+ key_ptr,
+ key_stride,
+ value_ptr,
+ value_stride,
+ k_cache_ptr,
+ v_cache_ptr,
+ slot_mapping_ptr,
+ D: tl.constexpr,
+):
+ idx = tl.program_id(0)
+ slot = tl.load(slot_mapping_ptr + idx)
+ if slot == -1: return
+ key_offsets = idx * key_stride + tl.arange(0, D)
+ value_offsets = idx * value_stride + tl.arange(0, D)
+ key = tl.load(key_ptr + key_offsets)
+ value = tl.load(value_ptr + value_offsets)
+ cache_offsets = slot * D + tl.arange(0, D)
+ tl.store(k_cache_ptr + cache_offsets, key)
+ tl.store(v_cache_ptr + cache_offsets, value)
+
+
+def store_kvcache(key: torch.Tensor, value: torch.Tensor, k_cache: torch.Tensor, v_cache: torch.Tensor, slot_mapping: torch.Tensor):
+ N, num_heads, head_dim = key.shape
+ D = num_heads * head_dim
+ assert key.stride(-1) == 1 and value.stride(-1) == 1
+ assert key.stride(1) == head_dim and value.stride(1) == head_dim
+ assert k_cache.stride(1) == D and v_cache.stride(1) == D
+ assert slot_mapping.numel() == N
+ store_kvcache_kernel[(N,)](key, key.stride(0), value, value.stride(0), k_cache, v_cache, slot_mapping, D)
+
+
+class Attention(nn.Module):
+
+ def __init__(
+ self,
+ num_heads,
+ head_dim,
+ scale,
+ num_kv_heads,
+ ):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = head_dim
+ self.scale = scale
+ self.num_kv_heads = num_kv_heads
+ self.k_cache = self.v_cache = torch.tensor([])
+
+ def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor):
+ context = get_context()
+ k_cache, v_cache = self.k_cache, self.v_cache
+ if k_cache.numel() and v_cache.numel():
+ store_kvcache(k, v, k_cache, v_cache, context.slot_mapping)
+ if context.is_prefill:
+ if context.block_tables is not None: # prefix cache
+ k, v = k_cache, v_cache
+ o = flash_attn_varlen_func(q, k, v,
+ max_seqlen_q=context.max_seqlen_q, cu_seqlens_q=context.cu_seqlens_q,
+ max_seqlen_k=context.max_seqlen_k, cu_seqlens_k=context.cu_seqlens_k,
+ softmax_scale=self.scale, causal=True, block_table=context.block_tables)
+ else: # decode
+ o = flash_attn_with_kvcache(q.unsqueeze(1), k_cache, v_cache,
+ cache_seqlens=context.context_lens, block_table=context.block_tables,
+ softmax_scale=self.scale, causal=True)
+ return o
diff --git a/shared/llm_engines/nanovllm/layers/embed_head.py b/shared/llm_engines/nanovllm/layers/embed_head.py
new file mode 100644
index 0000000..4475b41
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/embed_head.py
@@ -0,0 +1,71 @@
+import torch
+from torch import nn
+import torch.nn.functional as F
+import torch.distributed as dist
+
+from nanovllm.utils.context import get_context
+
+
+def _get_tp_info():
+ if dist.is_available() and dist.is_initialized():
+ return dist.get_rank(), dist.get_world_size()
+ return 0, 1
+
+
+class VocabParallelEmbedding(nn.Module):
+
+ def __init__(
+ self,
+ num_embeddings: int,
+ embedding_dim: int,
+ ):
+ super().__init__()
+ self.tp_rank, self.tp_size = _get_tp_info()
+ assert num_embeddings % self.tp_size == 0
+ self.num_embeddings = num_embeddings
+ self.num_embeddings_per_partition = self.num_embeddings // self.tp_size
+ self.vocab_start_idx = self.num_embeddings_per_partition * self.tp_rank
+ self.vocab_end_idx = self.vocab_start_idx + self.num_embeddings_per_partition
+ self.weight = nn.Parameter(torch.empty(self.num_embeddings_per_partition, embedding_dim))
+ self.weight.weight_loader = self.weight_loader
+
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor):
+ param_data = param.data
+ shard_size = param_data.size(0)
+ start_idx = self.tp_rank * shard_size
+ loaded_weight = loaded_weight.narrow(0, start_idx, shard_size)
+ param_data.copy_(loaded_weight)
+
+ def forward(self, x: torch.Tensor):
+ if self.tp_size > 1:
+ mask = (x >= self.vocab_start_idx) & (x < self.vocab_end_idx)
+ x = mask * (x - self.vocab_start_idx)
+ y = F.embedding(x, self.weight)
+ if self.tp_size > 1:
+ y = mask.unsqueeze(1) * y
+ dist.all_reduce(y)
+ return y
+
+
+class ParallelLMHead(VocabParallelEmbedding):
+
+ def __init__(
+ self,
+ num_embeddings: int,
+ embedding_dim: int,
+ bias: bool = False,
+ ):
+ assert not bias
+ super().__init__(num_embeddings, embedding_dim)
+
+ def forward(self, x: torch.Tensor):
+ context = get_context()
+ if context.is_prefill:
+ last_indices = context.cu_seqlens_q[1:] - 1
+ x = x[last_indices].contiguous()
+ logits = F.linear(x, self.weight)
+ if self.tp_size > 1:
+ all_logits = [torch.empty_like(logits) for _ in range(self.tp_size)] if self.tp_rank == 0 else None
+ dist.gather(logits, all_logits, 0)
+ logits = torch.cat(all_logits, -1) if self.tp_rank == 0 else None
+ return logits
diff --git a/shared/llm_engines/nanovllm/layers/layernorm.py b/shared/llm_engines/nanovllm/layers/layernorm.py
new file mode 100644
index 0000000..71bf419
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/layernorm.py
@@ -0,0 +1,50 @@
+import torch
+from torch import nn
+
+
+class RMSNorm(nn.Module):
+
+ def __init__(
+ self,
+ hidden_size: int,
+ eps: float = 1e-6,
+ ) -> None:
+ super().__init__()
+ self.eps = eps
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+
+ @torch.compile
+ def rms_forward(
+ self,
+ x: torch.Tensor,
+ ) -> torch.Tensor:
+ orig_dtype = x.dtype
+ x = x.float()
+ var = x.pow(2).mean(dim=-1, keepdim=True)
+ x.mul_(torch.rsqrt(var + self.eps))
+ x = x.to(orig_dtype).mul_(self.weight)
+ return x
+
+ @torch.compile
+ def add_rms_forward(
+ self,
+ x: torch.Tensor,
+ residual: torch.Tensor,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ orig_dtype = x.dtype
+ x = x.float().add_(residual.float())
+ residual = x.to(orig_dtype)
+ var = x.pow(2).mean(dim=-1, keepdim=True)
+ x.mul_(torch.rsqrt(var + self.eps))
+ x = x.to(orig_dtype).mul_(self.weight)
+ return x, residual
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ residual: torch.Tensor | None = None,
+ ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
+ if residual is None:
+ return self.rms_forward(x)
+ else:
+ return self.add_rms_forward(x, residual)
diff --git a/shared/llm_engines/nanovllm/layers/linear.py b/shared/llm_engines/nanovllm/layers/linear.py
new file mode 100644
index 0000000..3476cbb
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/linear.py
@@ -0,0 +1,416 @@
+import torch
+from torch import nn
+import torch.nn.functional as F
+import torch.distributed as dist
+import math
+
+try:
+ from shared.kernels import quanto_int8_triton as _shared_quanto_int8_triton
+except Exception: # pragma: no cover
+ _shared_quanto_int8_triton = None # type: ignore
+
+
+def _shared_kernel_available() -> bool:
+ if _shared_quanto_int8_triton is None:
+ return False
+ is_available = getattr(_shared_quanto_int8_triton, "is_available", None)
+ if not callable(is_available):
+ return False
+ try:
+ return bool(is_available())
+ except Exception:
+ return False
+
+
+_TRITON_AVAILABLE = _shared_kernel_available()
+
+
+def divide(numerator, denominator):
+ assert numerator % denominator == 0
+ return numerator // denominator
+
+
+def _get_tp_info():
+ if dist.is_available() and dist.is_initialized():
+ return dist.get_rank(), dist.get_world_size()
+ return 0, 1
+
+
+def _flatten_scale(scale: torch.Tensor) -> torch.Tensor:
+ if scale.ndim == 2 and scale.shape[1] == 1:
+ return scale.view(-1)
+ if scale.ndim == 1:
+ return scale
+ return scale.reshape(-1)
+
+
+def _run_triton_fused_int8_mm(
+ x2d: torch.Tensor,
+ qweight_t: torch.Tensor,
+ qweight_scale_fp32: torch.Tensor,
+ input_scale: float | None = None,
+) -> torch.Tensor:
+ del input_scale
+ if _shared_quanto_int8_triton is None:
+ raise RuntimeError("shared.kernels.quanto_int8_triton is unavailable")
+ run_kernel = getattr(_shared_quanto_int8_triton, "fused_quant_scaled_mm_transposed", None)
+ if run_kernel is None:
+ raise RuntimeError("shared.kernels.quanto_int8_triton.fused_quant_scaled_mm_transposed is missing")
+
+ m, k = x2d.shape
+ k2, n = qweight_t.shape
+ if k != k2:
+ raise RuntimeError(f"Triton int8 GEMM shape mismatch: x={x2d.shape}, w_t={qweight_t.shape}")
+ qweight_scale_fp32 = _flatten_scale(qweight_scale_fp32)
+ if qweight_scale_fp32.numel() != n:
+ raise RuntimeError(
+ f"Triton int8 qweight_scale length mismatch: expected {n}, got {qweight_scale_fp32.numel()}"
+ )
+ return run_kernel(x2d, qweight_t, qweight_scale_fp32, out_dtype=x2d.dtype)
+
+
+class LinearBase(nn.Module):
+
+ def __init__(
+ self,
+ input_size: int,
+ output_size: int,
+ bias: bool = False,
+ tp_dim: int | None = None,
+ ):
+ super().__init__()
+ self.tp_dim = tp_dim
+ self.tp_rank, self.tp_size = _get_tp_info()
+ self.input_size = input_size
+ self.output_size = output_size
+ self.weight = nn.Parameter(torch.empty(output_size, input_size))
+ self.weight.weight_loader = self.weight_loader
+ self.register_buffer("qweight_data", torch.empty(0, dtype=torch.int8))
+ self.register_buffer("qweight_t", torch.empty(0, dtype=torch.int8))
+ self.register_buffer("qweight_scale", torch.empty(0))
+ self.register_buffer("qweight_scale_fp32", torch.empty(0, dtype=torch.float32))
+ self.register_buffer("input_scale", torch.ones((), dtype=torch.bfloat16))
+ self.register_buffer("output_scale", torch.ones((), dtype=torch.bfloat16))
+ self.use_int8_weight = False
+ self.use_triton_int8 = False
+ self._input_scale_value = 1.0
+ self._quant_expected_shards = 1
+ self._quant_data_loaded = set()
+ self._quant_scale_loaded = set()
+ if bias:
+ self.bias = nn.Parameter(torch.empty(output_size))
+ self.bias.weight_loader = self.weight_loader
+ else:
+ self.register_parameter("bias", None)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ raise NotImplementedError
+
+ def _shard_weight(self, loaded_weight: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ return loaded_weight
+
+ def _shard_weight_scale(self, loaded_scale: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ return loaded_scale
+
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor, loaded_shard_id=None):
+ param.data.copy_(self._shard_weight(loaded_weight, loaded_shard_id))
+
+ def quant_weight_data_loader(self, loaded_weight: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device
+ shard = self._shard_weight(loaded_weight, loaded_shard_id).contiguous()
+ q = shard.to(device=device, dtype=torch.int8, non_blocking=True)
+ self.qweight_data = q
+ shard_key = loaded_shard_id if loaded_shard_id is not None else 0
+ self._quant_data_loaded.add(shard_key)
+
+ def quant_weight_scale_loader(self, loaded_scale: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device if self.weight.numel() != 0 else self.qweight_data.device
+ shard_scale = self._shard_weight_scale(loaded_scale, loaded_shard_id).contiguous()
+ if shard_scale.dim() == 2 and shard_scale.size(1) == 1:
+ shard_scale = shard_scale.squeeze(1)
+ self.qweight_scale = shard_scale.to(device=device, dtype=torch.bfloat16, non_blocking=True)
+ shard_key = loaded_shard_id if loaded_shard_id is not None else 0
+ self._quant_scale_loaded.add(shard_key)
+
+ def quant_input_scale_loader(self, loaded_scale: torch.Tensor):
+ device = self.weight.device if self.weight.numel() != 0 else self.qweight_data.device
+ self.input_scale = loaded_scale.to(device=device, dtype=torch.bfloat16, non_blocking=True)
+
+ def quant_output_scale_loader(self, loaded_scale: torch.Tensor):
+ device = self.weight.device if self.weight.numel() != 0 else self.qweight_data.device
+ self.output_scale = loaded_scale.to(device=device, dtype=torch.bfloat16, non_blocking=True)
+
+ def finalize_quantized(self):
+ if self.qweight_data.numel() == 0 or self.qweight_scale.numel() == 0:
+ return
+ if len(self._quant_data_loaded) < self._quant_expected_shards:
+ return
+ if len(self._quant_scale_loaded) < self._quant_expected_shards:
+ return
+ # Keep int8 weights in KxN layout for int8 GEMM paths.
+ self.qweight_t = self.qweight_data.transpose(0, 1).contiguous()
+ self.qweight_data = torch.empty(0, dtype=torch.int8, device=self.qweight_t.device)
+ self.qweight_scale_fp32 = self.qweight_scale.to(dtype=torch.float32)
+ if not torch.is_tensor(self.input_scale):
+ raise RuntimeError(f"Invalid input_scale type: {type(self.input_scale)}")
+ input_scale_flat = self.input_scale.reshape(-1)
+ if input_scale_flat.numel() != 1:
+ raise RuntimeError(
+ f"Expected scalar input_scale, got shape={tuple(self.input_scale.shape)}"
+ )
+ input_scale_value = float(input_scale_flat[0].item())
+ if not math.isfinite(input_scale_value) or input_scale_value <= 0:
+ raise RuntimeError(f"Invalid input_scale value: {input_scale_value}")
+ self._input_scale_value = max(input_scale_value, 1e-8)
+ self.use_triton_int8 = bool(_TRITON_AVAILABLE and self.qweight_t.is_cuda)
+ self.use_int8_weight = True
+ device = self.qweight_t.device
+ if self.weight.numel() != 0:
+ self.weight = nn.Parameter(torch.empty(0, device=device, dtype=torch.bfloat16), requires_grad=False)
+ if self.bias is not None:
+ self.bias = nn.Parameter(self.bias.data.to(device=device), requires_grad=False)
+
+ def _quant_int8_mm(self, x: torch.Tensor) -> torch.Tensor:
+ x_shape = x.shape
+ x2d = x.reshape(-1, x_shape[-1])
+ if self.use_triton_int8 and x2d.is_cuda and self.qweight_t.numel() != 0 and self.qweight_scale_fp32.numel() != 0:
+ y = _run_triton_fused_int8_mm(
+ x2d,
+ self.qweight_t,
+ self.qweight_scale_fp32,
+ )
+ return y.view(*x_shape[:-1], y.size(-1))
+
+ # Fallback path: use Quanto qbytes_mm for dynamic activation quantization parity.
+ if not hasattr(torch.ops, "quanto") or not hasattr(torch.ops.quanto, "qbytes_mm"):
+ raise RuntimeError("quanto.qbytes_mm op unavailable for int8 fallback path")
+ if self.qweight_t.numel() == 0 and self.qweight_data.numel() != 0:
+ self.qweight_t = self.qweight_data.transpose(0, 1).contiguous()
+ qweight = self.qweight_t.transpose(0, 1).contiguous()
+ scales = self.qweight_scale_fp32
+ if scales.numel() == 0:
+ scales = self.qweight_scale.to(torch.float32)
+ scales = _flatten_scale(scales).reshape(-1, 1).contiguous()
+ out = torch.ops.quanto.qbytes_mm(x2d, qweight, scales).to(x2d.dtype)
+ return out.view(*x_shape[:-1], out.size(-1))
+
+ def prepare_for_quantized_load(self):
+ device = None
+ if self.qweight_t.numel() != 0:
+ device = self.qweight_t.device
+ elif self.qweight_data.numel() != 0:
+ device = self.qweight_data.device
+ elif self.weight.numel() != 0:
+ device = self.weight.device
+ elif self.qweight_scale.numel() != 0:
+ device = self.qweight_scale.device
+ else:
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+ if self.weight.numel() != 0:
+ self.weight = nn.Parameter(torch.empty(0, device=device, dtype=torch.bfloat16), requires_grad=False)
+
+ # Reset all quantized buffers/state so each reload is complete and deterministic.
+ self.qweight_data = torch.empty(0, dtype=torch.int8, device=device)
+ self.qweight_t = torch.empty(0, dtype=torch.int8, device=device)
+ self.qweight_scale = torch.empty(0, dtype=torch.bfloat16, device=device)
+ self.qweight_scale_fp32 = torch.empty(0, dtype=torch.float32, device=device)
+ self.input_scale = torch.ones((), dtype=torch.bfloat16, device=device)
+ self.output_scale = torch.ones((), dtype=torch.bfloat16, device=device)
+ self.use_int8_weight = False
+ self.use_triton_int8 = False
+ self._input_scale_value = 1.0
+ self._quant_data_loaded.clear()
+ self._quant_scale_loaded.clear()
+
+
+class ReplicatedLinear(LinearBase):
+
+ def __init__(
+ self,
+ input_size: int,
+ output_size: int,
+ bias: bool = False,
+ ):
+ super().__init__(input_size, output_size, bias)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.use_int8_weight:
+ y = self._quant_int8_mm(x)
+ if self.bias is not None:
+ y = y + self.bias
+ return y
+ return F.linear(x, self.weight, self.bias)
+
+
+class ColumnParallelLinear(LinearBase):
+
+ def __init__(
+ self,
+ input_size: int,
+ output_size: int,
+ bias: bool = False,
+ ):
+ tp_size = _get_tp_info()[1]
+ super().__init__(input_size, divide(output_size, tp_size), bias, 0)
+
+ def _shard_weight(self, loaded_weight: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ shard_size = divide(loaded_weight.size(self.tp_dim), self.tp_size)
+ start_idx = self.tp_rank * shard_size
+ return loaded_weight.narrow(self.tp_dim, start_idx, shard_size)
+
+ def _shard_weight_scale(self, loaded_scale: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ if loaded_scale.dim() == 0:
+ return loaded_scale
+ shard_size = divide(loaded_scale.size(0), self.tp_size)
+ start_idx = self.tp_rank * shard_size
+ return loaded_scale.narrow(0, start_idx, shard_size)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.use_int8_weight:
+ y = self._quant_int8_mm(x)
+ if self.bias is not None:
+ y = y + self.bias
+ return y
+ return F.linear(x, self.weight, self.bias)
+
+
+class MergedColumnParallelLinear(ColumnParallelLinear):
+
+ def __init__(
+ self,
+ input_size: int,
+ output_sizes: list[int],
+ bias: bool = False,
+ ):
+ self.output_sizes = output_sizes
+ super().__init__(input_size, sum(output_sizes), bias)
+ self._quant_expected_shards = len(output_sizes)
+
+ def _merged_shard_meta(self, loaded_shard_id: int):
+ shard_offset = sum(self.output_sizes[:loaded_shard_id]) // self.tp_size
+ shard_size = self.output_sizes[loaded_shard_id] // self.tp_size
+ return shard_offset, shard_size
+
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor, loaded_shard_id: int):
+ param_data = param.data
+ shard_offset, shard_size = self._merged_shard_meta(loaded_shard_id)
+ param_slice = param_data.narrow(self.tp_dim, shard_offset, shard_size)
+ shard = loaded_weight.chunk(self.tp_size, self.tp_dim)[self.tp_rank]
+ param_slice.copy_(shard)
+
+ def quant_weight_data_loader(self, loaded_weight: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device
+ if self.qweight_data.numel() == 0:
+ self.qweight_data = torch.empty((self.output_size, self.input_size), dtype=torch.int8, device=device)
+ shard_offset, shard_size = self._merged_shard_meta(int(loaded_shard_id))
+ param_slice = self.qweight_data.narrow(0, shard_offset, shard_size)
+ shard = loaded_weight.chunk(self.tp_size, self.tp_dim)[self.tp_rank]
+ param_slice.copy_(shard.to(device=device, dtype=torch.int8, non_blocking=True))
+ self._quant_data_loaded.add(int(loaded_shard_id))
+
+ def quant_weight_scale_loader(self, loaded_scale: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device if self.weight.numel() != 0 else self.qweight_data.device
+ if self.qweight_scale.numel() == 0:
+ self.qweight_scale = torch.empty((self.output_size,), dtype=torch.bfloat16, device=device)
+ shard_offset, shard_size = self._merged_shard_meta(int(loaded_shard_id))
+ scale_slice = self.qweight_scale.narrow(0, shard_offset, shard_size)
+ shard = loaded_scale.chunk(self.tp_size, 0)[self.tp_rank]
+ if shard.dim() == 2 and shard.size(1) == 1:
+ shard = shard.squeeze(1)
+ scale_slice.copy_(shard.to(device=device, dtype=torch.bfloat16, non_blocking=True))
+ self._quant_scale_loaded.add(int(loaded_shard_id))
+
+
+class QKVParallelLinear(ColumnParallelLinear):
+
+ def __init__(
+ self,
+ hidden_size: int,
+ head_size: int,
+ total_num_heads: int,
+ total_num_kv_heads: int | None = None,
+ bias: bool = False,
+ ):
+ tp_size = _get_tp_info()[1]
+ total_num_kv_heads = total_num_kv_heads or total_num_heads
+ self.head_size = head_size
+ self.num_heads = divide(total_num_heads, tp_size)
+ self.num_kv_heads = divide(total_num_kv_heads, tp_size)
+ output_size = (total_num_heads + 2 * total_num_kv_heads) * self.head_size
+ super().__init__(hidden_size, output_size, bias)
+ self._quant_expected_shards = 3
+
+ def _qkv_offset_size(self, loaded_shard_id: str):
+ assert loaded_shard_id in ["q", "k", "v"]
+ if loaded_shard_id == "q":
+ shard_size = self.num_heads * self.head_size
+ shard_offset = 0
+ elif loaded_shard_id == "k":
+ shard_size = self.num_kv_heads * self.head_size
+ shard_offset = self.num_heads * self.head_size
+ else:
+ shard_size = self.num_kv_heads * self.head_size
+ shard_offset = self.num_heads * self.head_size + self.num_kv_heads * self.head_size
+ return shard_offset, shard_size
+
+ def weight_loader(self, param: nn.Parameter, loaded_weight: torch.Tensor, loaded_shard_id: str):
+ param_data = param.data
+ shard_offset, shard_size = self._qkv_offset_size(loaded_shard_id)
+ param_slice = param_data.narrow(self.tp_dim, shard_offset, shard_size)
+ shard = loaded_weight.chunk(self.tp_size, self.tp_dim)[self.tp_rank]
+ param_slice.copy_(shard)
+
+ def quant_weight_data_loader(self, loaded_weight: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device
+ if self.qweight_data.numel() == 0:
+ self.qweight_data = torch.empty((self.output_size, self.input_size), dtype=torch.int8, device=device)
+ shard_offset, shard_size = self._qkv_offset_size(str(loaded_shard_id))
+ param_slice = self.qweight_data.narrow(0, shard_offset, shard_size)
+ shard = loaded_weight.chunk(self.tp_size, self.tp_dim)[self.tp_rank]
+ param_slice.copy_(shard.to(device=device, dtype=torch.int8, non_blocking=True))
+ self._quant_data_loaded.add(str(loaded_shard_id))
+
+ def quant_weight_scale_loader(self, loaded_scale: torch.Tensor, loaded_shard_id=None):
+ device = self.weight.device if self.weight.numel() != 0 else self.qweight_data.device
+ if self.qweight_scale.numel() == 0:
+ self.qweight_scale = torch.empty((self.output_size,), dtype=torch.bfloat16, device=device)
+ shard_offset, shard_size = self._qkv_offset_size(str(loaded_shard_id))
+ scale_slice = self.qweight_scale.narrow(0, shard_offset, shard_size)
+ shard = loaded_scale.chunk(self.tp_size, 0)[self.tp_rank]
+ if shard.dim() == 2 and shard.size(1) == 1:
+ shard = shard.squeeze(1)
+ scale_slice.copy_(shard.to(device=device, dtype=torch.bfloat16, non_blocking=True))
+ self._quant_scale_loaded.add(str(loaded_shard_id))
+
+
+class RowParallelLinear(LinearBase):
+
+ def __init__(
+ self,
+ input_size: int,
+ output_size: int,
+ bias: bool = False,
+ ):
+ tp_size = _get_tp_info()[1]
+ super().__init__(divide(input_size, tp_size), output_size, bias, 1)
+
+ def _shard_weight(self, loaded_weight: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ shard_size = divide(loaded_weight.size(self.tp_dim), self.tp_size)
+ start_idx = self.tp_rank * shard_size
+ return loaded_weight.narrow(self.tp_dim, start_idx, shard_size)
+
+ def _shard_weight_scale(self, loaded_scale: torch.Tensor, loaded_shard_id=None) -> torch.Tensor:
+ # Output rows are not sharded in RowParallelLinear.
+ return loaded_scale
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.use_int8_weight:
+ y = self._quant_int8_mm(x)
+ if self.bias is not None and self.tp_rank == 0:
+ y = y + self.bias
+ else:
+ y = F.linear(x, self.weight, self.bias if self.tp_rank == 0 else None)
+ if self.tp_size > 1:
+ dist.all_reduce(y)
+ return y
diff --git a/shared/llm_engines/nanovllm/layers/rotary_embedding.py b/shared/llm_engines/nanovllm/layers/rotary_embedding.py
new file mode 100644
index 0000000..998d116
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/rotary_embedding.py
@@ -0,0 +1,61 @@
+from functools import lru_cache
+import torch
+from torch import nn
+
+
+def apply_rotary_emb(
+ x: torch.Tensor,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+) -> torch.Tensor:
+ x1, x2 = torch.chunk(x.float(), 2, dim=-1)
+ y1 = x1 * cos - x2 * sin
+ y2 = x2 * cos + x1 * sin
+ return torch.cat((y1, y2), dim=-1).to(x.dtype)
+
+
+class RotaryEmbedding(nn.Module):
+
+ def __init__(
+ self,
+ head_size: int,
+ rotary_dim: int,
+ max_position_embeddings: int,
+ base: float,
+ ) -> None:
+ super().__init__()
+ self.head_size = head_size
+ assert rotary_dim == head_size
+ inv_freq = 1.0 / (base**(torch.arange(0, rotary_dim, 2, dtype=torch.float) / rotary_dim))
+ t = torch.arange(max_position_embeddings, dtype=torch.float)
+ freqs = torch.einsum("i,j -> ij", t, inv_freq)
+ cos = freqs.cos()
+ sin = freqs.sin()
+ cache = torch.cat((cos, sin), dim=-1).unsqueeze_(1)
+ self.register_buffer("cos_sin_cache", cache, persistent=False)
+
+ @torch.compile
+ def forward(
+ self,
+ positions: torch.Tensor,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ cos_sin = self.cos_sin_cache[positions]
+ cos, sin = cos_sin.chunk(2, dim=-1)
+ query = apply_rotary_emb(query, cos, sin)
+ key = apply_rotary_emb(key, cos, sin)
+ return query, key
+
+
+@lru_cache(1)
+def get_rope(
+ head_size: int,
+ rotary_dim: int,
+ max_position: int,
+ base: float,
+ rope_scaling: dict | None = None,
+):
+ assert rope_scaling is None
+ rotary_emb = RotaryEmbedding(head_size, rotary_dim, max_position, base)
+ return rotary_emb
diff --git a/shared/llm_engines/nanovllm/layers/sampler.py b/shared/llm_engines/nanovllm/layers/sampler.py
new file mode 100644
index 0000000..41fcb27
--- /dev/null
+++ b/shared/llm_engines/nanovllm/layers/sampler.py
@@ -0,0 +1,122 @@
+import torch
+from torch import nn
+from typing import Optional
+import os
+
+
+_SAMPLER_NUMERIC_GUARD = os.environ.get("WAN2GP_NANOVLLM_SAMPLER_NUMERIC_GUARD", "0") == "1"
+
+
+def apply_top_k_top_p(
+ logits: torch.Tensor,
+ k: Optional[torch.Tensor],
+ p: Optional[torch.Tensor],
+) -> torch.Tensor:
+ """Apply top-k and top-p masks to the logits (vLLM style).
+
+ The logits tensor is updated in-place.
+ """
+ if p is None:
+ if k is None:
+ return logits
+ # Avoid sorting vocab for top-k only case
+ return apply_top_k_only(logits, k)
+
+ # Need to sort for top-p
+ logits_sort, logits_idx = logits.sort(dim=-1, descending=False)
+
+ if k is not None:
+ # Apply top-k first
+ vocab_size = logits_sort.size(1)
+ # Clamp k to valid range
+ k_clamped = k.clamp(1, vocab_size).long()
+ top_k_mask_idx = vocab_size - k_clamped # shape: [B]
+ # Get the threshold value for each batch
+ top_k_thresh = logits_sort.gather(1, top_k_mask_idx.unsqueeze(1))
+ top_k_mask = logits_sort < top_k_thresh
+ logits_sort.masked_fill_(top_k_mask, float('-inf'))
+
+ # Apply top-p
+ probs_sort = logits_sort.softmax(dim=-1)
+ probs_sum = torch.cumsum(probs_sort, dim=-1, out=probs_sort) # reuse buffer
+ top_p_mask = probs_sum <= (1.0 - p.unsqueeze(1))
+ # Ensure at least one token is kept
+ top_p_mask[:, -1] = False
+ logits_sort.masked_fill_(top_p_mask, float('-inf'))
+
+ # Re-sort back to original positions
+ logits.scatter_(dim=-1, index=logits_idx, src=logits_sort)
+ return logits
+
+
+def apply_top_k_only(
+ logits: torch.Tensor,
+ k: torch.Tensor,
+) -> torch.Tensor:
+ """Apply top-k mask without sorting the entire vocab (vLLM style).
+
+ This is much faster than sorting for top-k only cases.
+ The logits tensor is updated in-place.
+ """
+ vocab_size = logits.shape[1]
+ # Handle cases where k >= vocab_size (no filtering needed)
+ no_top_k_mask = (k <= 0) | (k >= vocab_size)
+ # Set invalid k to 1 so we can still gather
+ k_safe = k.masked_fill(no_top_k_mask, 1).long()
+ # NOTE: This int() causes CPU-GPU sync, but torch.topk requires Python int
+ max_top_k = int(k_safe.max().clamp(max=vocab_size))
+
+ # Get top-k values for all batches
+ # topk.values has shape [batch_size, max_top_k]
+ topk_values = logits.topk(max_top_k, dim=1).values
+
+ # Convert k to 0-based index: we want the k-th largest value (index k-1)
+ # Clamp to valid range for gather
+ k_index = (k_safe - 1).clamp(0, max_top_k - 1).unsqueeze(1) # shape: [B, 1]
+ # Gather the threshold value (the k-th largest)
+ top_k_thresh = topk_values.gather(1, k_index)
+
+ # For rows with no top-k filtering, set threshold to -inf so nothing gets masked
+ top_k_thresh.masked_fill_(no_top_k_mask.unsqueeze(1), float('-inf'))
+
+ # Mask all values below the threshold
+ logits.masked_fill_(logits < top_k_thresh, float('-inf'))
+ return logits
+
+
+class Sampler(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(
+ self,
+ logits: torch.Tensor,
+ temperatures: torch.Tensor,
+ top_ks: Optional[torch.Tensor] = None,
+ top_ps: Optional[torch.Tensor] = None,
+ repetition_penalties: Optional[torch.Tensor] = None,
+ input_ids: Optional[torch.Tensor] = None,
+ ):
+ """
+ Sample tokens from logits with optional top-k and top-p filtering.
+
+ Condition checking is done OUTSIDE the compiled function to avoid
+ graph breaks from .any() calls.
+ """
+ # Apply temperature
+ logits = logits.float().div_(temperatures.unsqueeze(dim=1))
+
+ logits = apply_top_k_top_p(
+ logits,
+ top_ks,
+ top_ps,
+ )
+ if _SAMPLER_NUMERIC_GUARD:
+ logits = torch.nan_to_num(logits, nan=float("-inf"))
+ invalid_rows = ~torch.isfinite(logits).any(dim=-1)
+ if invalid_rows.any():
+ logits[invalid_rows, 0] = 0.0
+ probs = torch.softmax(logits, dim=-1)
+ sample_tokens = probs.div_(torch.empty_like(probs).exponential_(1).clamp_min_(1e-10)).argmax(dim=-1)
+ return sample_tokens
diff --git a/shared/llm_engines/nanovllm/llm.py b/shared/llm_engines/nanovllm/llm.py
new file mode 100644
index 0000000..4f51a44
--- /dev/null
+++ b/shared/llm_engines/nanovllm/llm.py
@@ -0,0 +1,5 @@
+from nanovllm.engine.llm_engine import LLMEngine
+
+
+class LLM(LLMEngine):
+ pass
diff --git a/shared/llm_engines/nanovllm/models/qwen3.py b/shared/llm_engines/nanovllm/models/qwen3.py
new file mode 100644
index 0000000..3f1c845
--- /dev/null
+++ b/shared/llm_engines/nanovllm/models/qwen3.py
@@ -0,0 +1,235 @@
+import torch
+from torch import nn
+import torch.distributed as dist
+from transformers import Qwen3Config
+
+from nanovllm.layers.activation import SiluAndMul
+from nanovllm.layers.attention import Attention
+from nanovllm.layers.layernorm import RMSNorm
+from nanovllm.layers.linear import QKVParallelLinear, MergedColumnParallelLinear, RowParallelLinear
+from nanovllm.layers.rotary_embedding import get_rope
+from nanovllm.layers.embed_head import VocabParallelEmbedding, ParallelLMHead
+
+
+def _get_tp_size():
+ if dist.is_available() and dist.is_initialized():
+ return dist.get_world_size()
+ return 1
+
+
+class Qwen3Attention(nn.Module):
+
+ def __init__(
+ self,
+ hidden_size: int,
+ num_heads: int,
+ num_kv_heads: int,
+ max_position: int = 4096 * 32,
+ head_dim: int | None = None,
+ rms_norm_eps: float = 1e-06,
+ qkv_bias: bool = False,
+ rope_theta: float = 10000,
+ rope_scaling: tuple | None = None,
+ ) -> None:
+ super().__init__()
+ tp_size = _get_tp_size()
+ self.total_num_heads = num_heads
+ assert self.total_num_heads % tp_size == 0
+ self.num_heads = self.total_num_heads // tp_size
+ self.total_num_kv_heads = num_kv_heads
+ assert self.total_num_kv_heads % tp_size == 0
+ self.num_kv_heads = self.total_num_kv_heads // tp_size
+ self.head_dim = head_dim or hidden_size // self.total_num_heads
+ self.q_size = self.num_heads * self.head_dim
+ self.kv_size = self.num_kv_heads * self.head_dim
+ self.scaling = self.head_dim ** -0.5
+ self.qkv_bias = qkv_bias
+
+ self.qkv_proj = QKVParallelLinear(
+ hidden_size,
+ self.head_dim,
+ self.total_num_heads,
+ self.total_num_kv_heads,
+ bias=qkv_bias,
+ )
+ self.o_proj = RowParallelLinear(
+ self.total_num_heads * self.head_dim,
+ hidden_size,
+ bias=False,
+ )
+ self.rotary_emb = get_rope(
+ self.head_dim,
+ rotary_dim=self.head_dim,
+ max_position=max_position,
+ base=rope_theta,
+ rope_scaling=rope_scaling,
+ )
+ self.attn = Attention(
+ self.num_heads,
+ self.head_dim,
+ self.scaling,
+ self.num_kv_heads,
+ )
+ if not self.qkv_bias:
+ self.q_norm = RMSNorm(self.head_dim, eps=rms_norm_eps)
+ self.k_norm = RMSNorm(self.head_dim, eps=rms_norm_eps)
+
+ def forward(
+ self,
+ positions: torch.Tensor,
+ hidden_states: torch.Tensor,
+ ) -> torch.Tensor:
+ qkv = self.qkv_proj(hidden_states)
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
+ q = q.view(-1, self.num_heads, self.head_dim)
+ k = k.view(-1, self.num_kv_heads, self.head_dim)
+ v = v.view(-1, self.num_kv_heads, self.head_dim)
+ if not self.qkv_bias:
+ q = self.q_norm(q)
+ k = self.k_norm(k)
+ q, k = self.rotary_emb(positions, q, k)
+ o = self.attn(q, k, v)
+ output = self.o_proj(o.flatten(1, -1))
+ return output
+
+
+class Qwen3MLP(nn.Module):
+
+ def __init__(
+ self,
+ hidden_size: int,
+ intermediate_size: int,
+ hidden_act: str,
+ ) -> None:
+ super().__init__()
+ self.gate_up_proj = MergedColumnParallelLinear(
+ hidden_size,
+ [intermediate_size] * 2,
+ bias=False,
+ )
+ self.down_proj = RowParallelLinear(
+ intermediate_size,
+ hidden_size,
+ bias=False,
+ )
+ assert hidden_act == "silu"
+ self.act_fn = SiluAndMul()
+
+ def forward(self, x):
+ gate_up = self.gate_up_proj(x)
+ x = self.act_fn(gate_up)
+ x = self.down_proj(x)
+ return x
+
+
+class Qwen3DecoderLayer(nn.Module):
+
+ def __init__(
+ self,
+ config: Qwen3Config,
+ ) -> None:
+ super().__init__()
+ self.self_attn = Qwen3Attention(
+ hidden_size=config.hidden_size,
+ num_heads=config.num_attention_heads,
+ num_kv_heads=config.num_key_value_heads,
+ max_position=config.max_position_embeddings,
+ rms_norm_eps=config.rms_norm_eps,
+ qkv_bias=getattr(config, 'attention_bias', True),
+ head_dim=getattr(config, 'head_dim', None),
+ rope_theta=getattr(config, "rope_theta", 1000000),
+ rope_scaling=getattr(config, "rope_scaling", None),
+ )
+ self.mlp = Qwen3MLP(
+ hidden_size=config.hidden_size,
+ intermediate_size=config.intermediate_size,
+ hidden_act=config.hidden_act,
+ )
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ positions: torch.Tensor,
+ hidden_states: torch.Tensor,
+ residual: torch.Tensor | None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ if residual is None:
+ hidden_states, residual = self.input_layernorm(hidden_states), hidden_states
+ else:
+ hidden_states, residual = self.input_layernorm(hidden_states, residual)
+ hidden_states = self.self_attn(positions, hidden_states)
+ hidden_states, residual = self.post_attention_layernorm(hidden_states, residual)
+ hidden_states = self.mlp(hidden_states)
+ return hidden_states, residual
+
+
+class Qwen3Model(nn.Module):
+
+ def __init__(
+ self,
+ config: Qwen3Config,
+ ) -> None:
+ super().__init__()
+ self.embed_tokens = VocabParallelEmbedding(config.vocab_size, config.hidden_size)
+ self.layers = nn.ModuleList([Qwen3DecoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ def forward(
+ self,
+ input_ids: torch.Tensor,
+ positions: torch.Tensor,
+ ) -> torch.Tensor:
+ hidden_states = self.embed_tokens(input_ids)
+ residual = None
+ for layer in self.layers:
+ hidden_states, residual = layer(positions, hidden_states, residual)
+ hidden_states, _ = self.norm(hidden_states, residual)
+ return hidden_states
+
+
+class Qwen3ForCausalLM(nn.Module):
+ packed_modules_mapping = {
+ "q_proj": ("qkv_proj", "q"),
+ "k_proj": ("qkv_proj", "k"),
+ "v_proj": ("qkv_proj", "v"),
+ "gate_proj": ("gate_up_proj", 0),
+ "up_proj": ("gate_up_proj", 1),
+ }
+
+ def __init__(
+ self,
+ config: Qwen3Config
+ ) -> None:
+ super().__init__()
+ self.model = Qwen3Model(config)
+ self.lm_head = ParallelLMHead(config.vocab_size, config.hidden_size)
+ if config.tie_word_embeddings:
+ self.lm_head.weight.data = self.model.embed_tokens.weight.data
+
+ # Proxy attributes for weight loading compatibility
+ # Some model weights use "embed_tokens" instead of "model.embed_tokens"
+ @property
+ def embed_tokens(self):
+ return self.model.embed_tokens
+
+ @property
+ def layers(self):
+ return self.model.layers
+
+ @property
+ def norm(self):
+ return self.model.norm
+
+ def forward(
+ self,
+ input_ids: torch.Tensor,
+ positions: torch.Tensor,
+ ) -> torch.Tensor:
+ return self.model(input_ids, positions)
+
+ def compute_logits(
+ self,
+ hidden_states: torch.Tensor,
+ ) -> torch.Tensor:
+ return self.lm_head(hidden_states)
diff --git a/shared/llm_engines/nanovllm/sampling_params.py b/shared/llm_engines/nanovllm/sampling_params.py
new file mode 100644
index 0000000..291a1c2
--- /dev/null
+++ b/shared/llm_engines/nanovllm/sampling_params.py
@@ -0,0 +1,32 @@
+from dataclasses import dataclass, field
+from typing import Optional, Callable, Any
+
+
+@dataclass
+class SamplingParams:
+ temperature: float = 1.0
+ max_tokens: int = 64
+ ignore_eos: bool = False
+ cfg_scale: float = 1.0 # CFG guidance scale. When > 1.0, applies classifier-free guidance
+ top_k: Optional[int] = None # Top-k sampling: consider only top k tokens
+ top_p: Optional[float] = None # Top-p (nucleus) sampling: consider tokens with cumulative probability <= top_p
+ repetition_penalty: float = 1.0 # Repetition penalty: >1.0 reduces repetition, <1.0 increases it
+ # Optional logits processor for constrained decoding
+ # Should be a callable with signature: (input_ids: torch.Tensor, logits: torch.Tensor) -> torch.Tensor
+ logits_processor: Optional[Any] = field(default=None, repr=False)
+ # Optional callback to update processor state after each token
+ # Should be a callable with signature: (token_id: int) -> None
+ logits_processor_update_state: Optional[Callable[[int], None]] = field(default=None, repr=False)
+ # Optional additive logits bias (shape [vocab_size]) applied each decode step.
+ logits_bias: Optional[Any] = field(default=None, repr=False)
+ # Optional RNG seed for deterministic sampling.
+ seed: Optional[int] = None
+
+ def __post_init__(self):
+ assert self.temperature > 1e-10, "greedy sampling is not permitted"
+ assert self.cfg_scale >= 1.0, "cfg_scale must be >= 1.0"
+ if self.top_k is not None:
+ assert self.top_k > 0, "top_k must be > 0"
+ if self.top_p is not None:
+ assert 0.0 < self.top_p <= 1.0, "top_p must be in (0.0, 1.0]"
+ assert self.repetition_penalty > 0.0, "repetition_penalty must be > 0.0"
diff --git a/shared/llm_engines/nanovllm/utils/context.py b/shared/llm_engines/nanovllm/utils/context.py
new file mode 100644
index 0000000..2281888
--- /dev/null
+++ b/shared/llm_engines/nanovllm/utils/context.py
@@ -0,0 +1,27 @@
+from dataclasses import dataclass
+import torch
+
+
+@dataclass
+class Context:
+ is_prefill: bool = False
+ cu_seqlens_q: torch.Tensor | None = None
+ cu_seqlens_k: torch.Tensor | None = None
+ max_seqlen_q: int = 0
+ max_seqlen_k: int = 0
+ slot_mapping: torch.Tensor | None = None
+ context_lens: torch.Tensor | None = None
+ block_tables: torch.Tensor | None = None
+
+_CONTEXT = Context()
+
+def get_context():
+ return _CONTEXT
+
+def set_context(is_prefill, cu_seqlens_q=None, cu_seqlens_k=None, max_seqlen_q=0, max_seqlen_k=0, slot_mapping=None, context_lens=None, block_tables=None):
+ global _CONTEXT
+ _CONTEXT = Context(is_prefill, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, slot_mapping, context_lens, block_tables)
+
+def reset_context():
+ global _CONTEXT
+ _CONTEXT = Context()
diff --git a/shared/llm_engines/nanovllm/utils/loader.py b/shared/llm_engines/nanovllm/utils/loader.py
new file mode 100644
index 0000000..17ac800
--- /dev/null
+++ b/shared/llm_engines/nanovllm/utils/loader.py
@@ -0,0 +1,221 @@
+import os
+from glob import glob
+import torch
+from torch import nn
+from safetensors import safe_open
+
+
+def default_weight_loader(param: nn.Parameter, loaded_weight: torch.Tensor):
+ param.data.copy_(loaded_weight)
+
+
+def _get_parameter_safe(model: nn.Module, weight_name: str):
+ """
+ Try to get parameter from model, handling name mismatches.
+
+ Some models have nested structure (e.g., Qwen3ForCausalLM has model.embed_tokens)
+ but weight files may have flat names (embed_tokens.weight).
+ """
+ # Try direct access first
+ try:
+ return model.get_parameter(weight_name)
+ except AttributeError:
+ pass
+
+ # Try with 'model.' prefix (for nested model structure)
+ try:
+ prefixed_name = f"model.{weight_name}"
+ return model.get_parameter(prefixed_name)
+ except AttributeError:
+ pass
+
+ # Try removing 'model.' prefix
+ if weight_name.startswith("model."):
+ try:
+ unprefixed_name = weight_name[6:] # Remove 'model.' prefix
+ return model.get_parameter(unprefixed_name)
+ except AttributeError:
+ pass
+
+ return None
+
+
+def _get_submodule_safe(model: nn.Module, module_name: str):
+ try:
+ return model.get_submodule(module_name)
+ except Exception:
+ pass
+ try:
+ return model.get_submodule(f"model.{module_name}")
+ except Exception:
+ pass
+ if module_name.startswith("model."):
+ try:
+ return model.get_submodule(module_name[6:])
+ except Exception:
+ pass
+ return None
+
+
+def _list_safetensor_files(path: str) -> list[str]:
+ if os.path.isfile(path) and path.endswith(".safetensors"):
+ return [path]
+ return glob(os.path.join(path, "*.safetensors"))
+
+
+class WeightStore:
+ def __init__(self, path: str, mode: str = "lazy"):
+ self.path = path
+ self.mode = (mode or "lazy").lower()
+ self.files = _list_safetensor_files(path)
+ if not self.files:
+ raise FileNotFoundError(f"No .safetensors files found in {path}")
+ self._file_handles = {}
+ self._weight_to_file = {}
+ self._pinned_weights = {}
+ self.is_quanto_int8 = False
+ for file in self.files:
+ with safe_open(file, "pt", "cpu") as f:
+ for key in f.keys():
+ self._weight_to_file[key] = file
+ if key.endswith(".weight._data"):
+ self.is_quanto_int8 = True
+ if self.mode == "pinned":
+ self._preload_pinned()
+
+ def _get_handle(self, file_path: str):
+ handle = self._file_handles.get(file_path)
+ if handle is None:
+ handle = safe_open(file_path, "pt", "cpu")
+ self._file_handles[file_path] = handle
+ return handle
+
+ def _preload_pinned(self):
+ for key, file in self._weight_to_file.items():
+ handle = self._get_handle(file)
+ tensor = handle.get_tensor(key)
+ if tensor.device.type != "cpu":
+ tensor = tensor.cpu()
+ if not tensor.is_pinned():
+ tensor = tensor.pin_memory()
+ self._pinned_weights[key] = tensor
+
+ def get_tensor(self, key: str) -> torch.Tensor:
+ if self.mode == "pinned":
+ return self._pinned_weights[key]
+ handle = self._get_handle(self._weight_to_file[key])
+ return handle.get_tensor(key)
+
+
+def load_model(model: nn.Module, path: str, weight_store: WeightStore | None = None):
+ packed_modules_mapping = getattr(model, "packed_modules_mapping", {})
+ if weight_store is None:
+ safetensor_files = _list_safetensor_files(path)
+ if not safetensor_files:
+ raise FileNotFoundError(f"No .safetensors files found in {path}")
+ for file in safetensor_files:
+ with safe_open(file, "pt", "cpu") as f:
+ for weight_name in f.keys():
+ tensor = f.get_tensor(weight_name)
+ _apply_weight(model, packed_modules_mapping, weight_name, tensor)
+ _finalize_quantized_modules(model)
+ return
+
+ for weight_name in weight_store._weight_to_file.keys():
+ tensor = weight_store.get_tensor(weight_name)
+ _apply_weight(model, packed_modules_mapping, weight_name, tensor)
+ _finalize_quantized_modules(model)
+
+
+def _apply_weight(model: nn.Module, packed_modules_mapping, weight_name: str, tensor: torch.Tensor):
+ quant_suffix = None
+ if weight_name.endswith(".weight._data"):
+ quant_suffix = "qdata"
+ elif weight_name.endswith(".weight._scale"):
+ quant_suffix = "qscale"
+ elif weight_name.endswith(".input_scale"):
+ quant_suffix = "input_scale"
+ elif weight_name.endswith(".output_scale"):
+ quant_suffix = "output_scale"
+
+ for k in packed_modules_mapping:
+ if k in weight_name:
+ v, shard_id = packed_modules_mapping[k]
+ mapped_name = weight_name.replace(k, v)
+ if quant_suffix is not None:
+ module_name = mapped_name
+ if quant_suffix == "qdata":
+ module_name = mapped_name[: -len(".weight._data")]
+ elif quant_suffix == "qscale":
+ module_name = mapped_name[: -len(".weight._scale")]
+ elif quant_suffix == "input_scale":
+ module_name = mapped_name[: -len(".input_scale")]
+ elif quant_suffix == "output_scale":
+ module_name = mapped_name[: -len(".output_scale")]
+ module = _get_submodule_safe(model, module_name)
+ if module is None:
+ print(f"[loader] Warning: Module not found: {module_name}")
+ return
+ if quant_suffix == "qdata":
+ loader_fn = getattr(module, "quant_weight_data_loader", None)
+ elif quant_suffix == "qscale":
+ loader_fn = getattr(module, "quant_weight_scale_loader", None)
+ elif quant_suffix == "input_scale":
+ loader_fn = getattr(module, "quant_input_scale_loader", None)
+ else:
+ loader_fn = getattr(module, "quant_output_scale_loader", None)
+ if loader_fn is None:
+ print(f"[loader] Warning: Quant loader not found on module: {module_name}")
+ return
+ if quant_suffix in ("qdata", "qscale"):
+ loader_fn(tensor, shard_id)
+ else:
+ loader_fn(tensor)
+ return
+ param_name = mapped_name
+ param = _get_parameter_safe(model, param_name)
+ if param is None:
+ print(f"[loader] Warning: Parameter not found: {param_name}")
+ return
+ weight_loader = getattr(param, "weight_loader")
+ weight_loader(param, tensor, shard_id)
+ return
+ if quant_suffix is not None:
+ if quant_suffix == "qdata":
+ module_name = weight_name[: -len(".weight._data")]
+ elif quant_suffix == "qscale":
+ module_name = weight_name[: -len(".weight._scale")]
+ elif quant_suffix == "input_scale":
+ module_name = weight_name[: -len(".input_scale")]
+ else:
+ module_name = weight_name[: -len(".output_scale")]
+ module = _get_submodule_safe(model, module_name)
+ if module is None:
+ print(f"[loader] Warning: Module not found: {module_name}")
+ return
+ if quant_suffix == "qdata":
+ loader_fn = getattr(module, "quant_weight_data_loader", None)
+ elif quant_suffix == "qscale":
+ loader_fn = getattr(module, "quant_weight_scale_loader", None)
+ elif quant_suffix == "input_scale":
+ loader_fn = getattr(module, "quant_input_scale_loader", None)
+ else:
+ loader_fn = getattr(module, "quant_output_scale_loader", None)
+ if loader_fn is None:
+ print(f"[loader] Warning: Quant loader not found on module: {module_name}")
+ return
+ loader_fn(tensor)
+ return
+ param = _get_parameter_safe(model, weight_name)
+ if param is None:
+ print(f"[loader] Warning: Parameter not found: {weight_name}")
+ return
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
+ weight_loader(param, tensor)
+
+
+def _finalize_quantized_modules(model: nn.Module):
+ for module in model.modules():
+ finalize = getattr(module, "finalize_quantized", None)
+ if callable(finalize):
+ finalize()
diff --git a/shared/llm_engines/nanovllm/vllm_support.py b/shared/llm_engines/nanovllm/vllm_support.py
new file mode 100644
index 0000000..f8c195e
--- /dev/null
+++ b/shared/llm_engines/nanovllm/vllm_support.py
@@ -0,0 +1,139 @@
+_PROBE_CACHE = None
+_WARNED_REQUESTED_VLLM_UNAVAILABLE = False
+
+
+def _check_triton():
+ try:
+ import triton # noqa: F401
+ import triton.language as tl # noqa: F401
+ except Exception as exc:
+ return False, f"Triton import failed: {exc}"
+ return True, "ok"
+
+
+def _check_flash_attention_2():
+ try:
+ import flash_attn
+ from flash_attn import flash_attn_varlen_func # noqa: F401
+ from flash_attn import flash_attn_with_kvcache # noqa: F401
+ version = str(getattr(flash_attn, "__version__", ""))
+ except Exception as exc:
+ return False, f"FlashAttention import failed: {exc}"
+
+ major = None
+ if len(version) > 0:
+ try:
+ major = int(version.split(".", 1)[0])
+ except Exception:
+ major = None
+ if major is not None and major < 2:
+ return False, f"FlashAttention major version is {major}, expected >= 2"
+ return True, "ok"
+
+
+def _load_linear_module():
+ import importlib.util
+ import os
+
+ base_dir = os.path.dirname(os.path.abspath(__file__))
+ linear_path = os.path.join(base_dir, "layers", "linear.py")
+ if not os.path.isfile(linear_path):
+ raise RuntimeError(f"Missing nanovllm linear kernel file: {linear_path}")
+
+ spec = importlib.util.spec_from_file_location("nanovllm_linear_probe", linear_path)
+ if spec is None or spec.loader is None:
+ raise RuntimeError("Unable to build import spec for nanovllm linear kernel probe")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _check_triton_int8_kernel():
+ import inspect
+ import torch
+
+ if not torch.cuda.is_available():
+ return False, "CUDA is not available"
+
+ try:
+ linear_module = _load_linear_module()
+ if not getattr(linear_module, "_TRITON_AVAILABLE", False):
+ return False, "nanovllm Triton path is disabled"
+
+ run_kernel = getattr(linear_module, "_run_triton_fused_int8_mm", None)
+ if run_kernel is None:
+ return False, "nanovllm Triton int8 kernel entrypoint is missing"
+
+ device = torch.device("cuda")
+ x = torch.randn((2, 64), device=device, dtype=torch.bfloat16)
+ qweight_t = torch.randint(-127, 128, (64, 32), device=device, dtype=torch.int8)
+ qweight_scale = torch.ones((32,), device=device, dtype=torch.float32)
+ # Support both legacy (4-arg) and current (3-arg) probe signatures.
+ param_count = len(inspect.signature(run_kernel).parameters)
+ if param_count >= 4:
+ out = run_kernel(x, qweight_t, qweight_scale, 0.01)
+ else:
+ out = run_kernel(x, qweight_t, qweight_scale)
+ torch.cuda.synchronize()
+
+ if tuple(out.shape) != (2, 32):
+ return False, f"Unexpected kernel output shape: {tuple(out.shape)}"
+ if not torch.isfinite(out).all().item():
+ return False, "Kernel output contains non-finite values"
+ except Exception as exc:
+ return False, f"Triton int8 kernel smoke test failed: {exc}"
+
+ return True, "ok"
+
+
+def probe_vllm_runtime(force=False):
+ global _PROBE_CACHE
+ if _PROBE_CACHE is not None and not force:
+ return _PROBE_CACHE.copy()
+
+ checks = {}
+
+ triton_ok, triton_msg = _check_triton()
+ checks["triton"] = {"ok": triton_ok, "message": triton_msg}
+
+ flash_ok, flash_msg = _check_flash_attention_2()
+ checks["flash_attention_2"] = {"ok": flash_ok, "message": flash_msg}
+
+ kernel_ok, kernel_msg = _check_triton_int8_kernel()
+ checks["triton_int8_kernel"] = {"ok": kernel_ok, "message": kernel_msg}
+
+ supported = triton_ok and flash_ok and kernel_ok
+ result = {
+ "supported": supported,
+ "preferred_engine": "vllm" if supported else "legacy",
+ "checks": checks,
+ }
+
+ _PROBE_CACHE = result.copy()
+ return result
+
+
+def resolve_lm_decoder_engine(requested_engine):
+ probe_result = probe_vllm_runtime()
+ supported = bool(probe_result.get("supported", False))
+ 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 requested_engine == "":
+ return "vllm" if supported else "legacy"
+ return requested_engine
diff --git a/wgp.py b/wgp.py
index 7ae0430..77dc41e 100644
--- a/wgp.py
+++ b/wgp.py
@@ -7,6 +7,9 @@ import torch._logging as tlog
p = os.path.dirname(os.path.abspath(__file__))
if p not in sys.path:
sys.path.insert(0, p)
+# Ensure plugin-side `import wgp` resolves to this live module instance.
+if sys.modules.get("wgp") is not sys.modules.get(__name__):
+ sys.modules["wgp"] = sys.modules[__name__]
import asyncio
if os.name == "nt":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
@@ -65,6 +68,7 @@ import shutil
import glob
import cv2
import html
+import re
from transformers.utils import logging
logging.set_verbosity_error
from tqdm import tqdm
@@ -72,6 +76,7 @@ import requests
from shared.gradio.gallery import AdvancedMediaGallery
from shared.ffmpeg_setup import download_ffmpeg
from shared.utils.plugins import PluginManager, WAN2GPApplication, SYSTEM_PLUGINS
+from shared.llm_engines.nanovllm.vllm_support import resolve_lm_decoder_engine
from collections import defaultdict
# import torch._dynamo as dynamo
@@ -82,15 +87,22 @@ STARTUP_LOCK_FILE = "startup.lock"
global_queue_ref = []
AUTOSAVE_FILENAME = "queue.zip"
AUTOSAVE_PATH = AUTOSAVE_FILENAME
+AUTOSAVE_ERROR_FILENAME = "error_queue.zip"
AUTOSAVE_TEMPLATE_PATH = AUTOSAVE_FILENAME
CONFIG_FILENAME = "wgp_config.json"
PROMPT_VARS_MAX = 10
-target_mmgp_version = "3.7.3"
-WanGP_version = "10.70"
-settings_version = 2.49
+target_mmgp_version = "3.7.4"
+WanGP_version = "10.80"
+settings_version = 2.50
max_source_video_frames = 3000
prompt_enhancer_image_caption_model, prompt_enhancer_image_caption_processor, prompt_enhancer_llm_model, prompt_enhancer_llm_tokenizer = None, None, None, None
image_names_list = ["image_start", "image_end", "image_refs"]
+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",
"video_guide", "video_mask", "video_source", "audio_guide", "audio_guide2", "audio_source", "custom_guide"]
@@ -119,8 +131,20 @@ for handler in _HANDLER_MODULES:
quant_router.register_handler(handler)
from shared.qtypes import gguf as gguf_handler
quant_router.register_file_extension("gguf", gguf_handler)
+from shared.kernels.quanto_int8_inject import maybe_enable_quanto_int8_kernel, disable_quanto_int8_kernel
-# from mmgp import quanto_int8_inject
+
+def apply_int8_kernel_setting(enabled: int, notify_disabled = False) -> bool:
+ global enable_int8_kernels
+ try:
+ enable_int8_kernels = 1 if int(enabled) == 1 else 0
+ except Exception:
+ enable_int8_kernels = 0
+ os.environ["WAN2GP_QUANTO_INT8_KERNEL"] = "1" if enable_int8_kernels == 1 else "0"
+ if enable_int8_kernels == 1:
+ return bool(maybe_enable_quanto_int8_kernel())
+ disable_quanto_int8_kernel(notify_disabled)
+ return False
def set_wgp_global(variable_name: str, new_value: any) -> str:
if variable_name not in globals():
@@ -144,6 +168,13 @@ def clear_gen_cache():
def release_model():
global wan_model, offloadobj, reload_needed
+ if wan_model is not None:
+ close_fn = getattr(wan_model, "close", None)
+ if callable(close_fn):
+ try:
+ close_fn()
+ except Exception:
+ pass
wan_model = None
clear_gen_cache()
if "_cache" in offload.shared_state:
@@ -393,7 +424,7 @@ def process_prompt_and_add_tasks(state, current_gallery_tab, model_choice):
if has_image_file_extension(edit_video_source) and len(temporal_upsampling) > 0:
gr.Info("Temporal Upsampling can not be used with an Image")
return ret()
- film_grain_intensity = inputs.get("film_grain_intensity",0)
+ film_grain_intensity = inputs.get("film_grain<<_intensity",0)
film_grain_saturation = inputs.get("film_grain_saturation",0.5)
# if film_grain_intensity >0: prompt += [f"Film Grain: intensity={film_grain_intensity}, saturation={film_grain_saturation}"]
if film_grain_intensity >0: prompt += ["Film Grain"]
@@ -497,6 +528,123 @@ def process_prompt_and_add_tasks(state, current_gallery_tab, model_choice):
queue= gen.get("queue", [])
return update_queue_data(queue), gr.update(open=True) if new_prompts_count > 1 else gr.update()
+def get_custom_setting_key(index):
+ return f"custom_setting_{index + 1}"
+
+def _normalize_custom_setting_type(setting_type):
+ parsed_type = str(setting_type or "text").strip().lower()
+ return parsed_type if parsed_type in CUSTOM_SETTING_TYPES else "text"
+
+def _normalize_custom_setting_name(name):
+ normalized = re.sub(r"[^a-z0-9_]+", "_", str(name or "").strip().lower()).strip("_")
+ return normalized
+
+def get_custom_setting_id(setting_def, setting_index):
+ explicit_id = setting_def.get("id", None)
+ if explicit_id is not None and len(str(explicit_id).strip()) > 0:
+ normalized_id = _normalize_custom_setting_name(explicit_id)
+ if len(normalized_id) > 0:
+ return normalized_id
+ for field_name in ("name", "param"):
+ normalized_name = _normalize_custom_setting_name(setting_def.get(field_name, ""))
+ if len(normalized_name) > 0:
+ return normalized_name
+ return get_custom_setting_key(setting_index)
+
+def get_model_custom_settings(model_def):
+ if not isinstance(model_def, dict):
+ return []
+ custom_settings = model_def.get("custom_settings", [])
+ if not isinstance(custom_settings, list):
+ return []
+ normalized = []
+ used_ids = set()
+ for idx, setting in enumerate(custom_settings[:CUSTOM_SETTINGS_MAX]):
+ if not isinstance(setting, dict):
+ continue
+ one = setting.copy()
+ one["label"] = str(one.get("label", f"Custom Setting {idx + 1}"))
+ one["name"] = str(one.get("name", f"Custom Setting {idx + 1}"))
+ one["type"] = _normalize_custom_setting_type(one.get("type", "text"))
+ setting_id = get_custom_setting_id(one, idx)
+ if setting_id in used_ids:
+ setting_id = get_custom_setting_key(idx)
+ used_ids.add(setting_id)
+ one["id"] = setting_id
+ normalized.append(one)
+ return normalized
+
+def parse_custom_setting_typed_value(raw_value, setting_type):
+ if raw_value is None:
+ return None, None
+ if isinstance(raw_value, str):
+ raw_value = raw_value.strip()
+ if len(raw_value) == 0:
+ return None, None
+ setting_type = _normalize_custom_setting_type(setting_type)
+ if setting_type == "int":
+ if isinstance(raw_value, bool):
+ return None, "Expected an integer value."
+ if isinstance(raw_value, int):
+ return raw_value, None
+ if isinstance(raw_value, float):
+ if raw_value.is_integer():
+ return int(raw_value), None
+ return None, "Expected an integer value."
+ try:
+ return int(str(raw_value).strip()), None
+ except Exception:
+ try:
+ float_value = float(str(raw_value).strip())
+ if float_value.is_integer():
+ return int(float_value), None
+ except Exception:
+ pass
+ return None, "Expected an integer value."
+ if setting_type == "float":
+ if isinstance(raw_value, bool):
+ return None, "Expected a float value."
+ try:
+ return float(raw_value), None
+ except Exception:
+ return None, "Expected a float value."
+ return str(raw_value).strip(), None
+
+def get_custom_setting_value_from_dict(custom_settings_values, setting_def, setting_index):
+ setting_id = setting_def.get("id", get_custom_setting_id(setting_def, setting_index))
+ if isinstance(custom_settings_values, dict) and setting_id in custom_settings_values:
+ return custom_settings_values.get(setting_id, None)
+ return setting_def.get("default", "")
+
+def collect_custom_settings_from_inputs(model_def, inputs, strict=False):
+ custom_settings_dict = {}
+ existing_custom_settings = inputs.get("custom_settings", None)
+ if not isinstance(existing_custom_settings, dict):
+ existing_custom_settings = {}
+ custom_settings = get_model_custom_settings(model_def)
+ for idx, setting_def in enumerate(custom_settings):
+ slot_key = get_custom_setting_key(idx)
+ setting_id = setting_def["id"]
+ raw_value = inputs.get(slot_key, None)
+ if raw_value is None and setting_id in existing_custom_settings:
+ raw_value = existing_custom_settings.get(setting_id, None)
+ parsed_value, parse_error = parse_custom_setting_typed_value(raw_value, setting_def.get("type", "text"))
+ if parse_error is not None:
+ if strict:
+ return None, f"{setting_def.get('label', slot_key)} {parse_error}"
+ if raw_value is not None:
+ raw_text = str(raw_value).strip() if isinstance(raw_value, str) else raw_value
+ if not (isinstance(raw_text, str) and len(raw_text) == 0):
+ custom_settings_dict[setting_id] = raw_text
+ continue
+ if parsed_value is not None:
+ custom_settings_dict[setting_id] = parsed_value
+ return custom_settings_dict if len(custom_settings_dict) > 0 else None, None
+
+def clear_custom_setting_slots(inputs):
+ for idx in range(CUSTOM_SETTINGS_MAX):
+ inputs.pop(get_custom_setting_key(idx), None)
+
def validate_settings(state, model_type, single_prompt, inputs):
def ret():
return None, None, None, None
@@ -538,6 +686,13 @@ def validate_settings(state, model_type, single_prompt, inputs):
queue = gen.get("queue", [])
return ret()
+ parsed_custom_settings, custom_settings_error = collect_custom_settings_from_inputs(model_def, inputs, strict=True)
+ if custom_settings_error is not None:
+ gr.Info(custom_settings_error)
+ return ret()
+ inputs["custom_settings"] = parsed_custom_settings
+ clear_custom_setting_slots(inputs)
+
if hasattr(model_handler, "validate_generative_prompt"):
for one_prompt in prompts:
error = model_handler.validate_generative_prompt(model_type, model_def, inputs, one_prompt)
@@ -924,6 +1079,7 @@ def validate_settings(state, model_type, single_prompt, inputs):
"motion_amplitude": motion_amplitude,
"model_mode": model_mode,
"video_guide_outpainting": video_guide_outpainting,
+ "custom_settings": inputs.get("custom_settings", None),
}
inputs.update(override_inputs)
if hasattr(model_handler, "validate_generative_settings"):
@@ -2172,11 +2328,13 @@ if not Path(config_load_filename).is_file():
"transformer_types": [],
"transformer_quantization": "int8",
"text_encoder_quantization" : "int8",
+ "lm_decoder_engine": "",
"save_path": "outputs",
"image_save_path": "outputs",
"compile" : "",
"metadata_type": "metadata",
"boost" : 1,
+ "enable_int8_kernels": 0,
"clear_file_list" : 5,
"enable_4k_resolutions": 0,
"max_reserved_loras": -1,
@@ -2272,6 +2430,8 @@ 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",
@@ -2796,6 +2956,8 @@ default_profile = default_profile_video
loaded_profile = force_profile_no = -1
compile = server_config.get("compile", "")
boost = server_config.get("boost", 1)
+enable_int8_kernels = server_config.get("enable_int8_kernels", 0)
+apply_int8_kernel_setting(enable_int8_kernels)
vae_config = server_config.get("vae_config", 0)
if len(args.vae_config) > 0:
vae_config = int(args.vae_config)
@@ -2817,6 +2979,7 @@ if "loras_root" not in server_config: server_config["loras_root"] = DEFAULT_LORA
if "prompt_enhancer_temperature" not in server_config: server_config["prompt_enhancer_temperature"] = 0.6
if "prompt_enhancer_top_p" not in server_config: server_config["prompt_enhancer_top_p"] = 0.9
if "prompt_enhancer_randomize_seed" not in server_config: server_config["prompt_enhancer_randomize_seed"] = True
+if "enable_int8_kernels" not in server_config: server_config["enable_int8_kernels"] = 0
preload_model_policy = server_config.get("preload_model_policy", [])
@@ -3404,9 +3567,11 @@ def setup_prompt_enhancer(pipe, kwargs):
def load_models(model_type, override_profile = -1, output_type="video", **model_kwargs):
- global transformer_type, loaded_profile
+ global transformer_type, loaded_profile, lm_decoder_engine_obtained
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:
@@ -3494,7 +3659,7 @@ def load_models(model_type, override_profile = -1, output_type="video", **model_
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,
- dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, text_encoder_filename = text_encoder_filename, profile=profile, **model_kwargs )
+ dtype = transformer_dtype, VAE_dtype = VAE_dtype, mixed_precision_transformer = mixed_precision_transformer, save_quantized = save_quantized, submodel_no_list = model_submodel_no_list, text_encoder_filename = text_encoder_filename, profile=profile, lm_decoder_engine=lm_decoder_engine_obtained, **model_kwargs )
kwargs = {}
if "pipe" in pipe:
@@ -3502,7 +3667,7 @@ def load_models(model_type, override_profile = -1, output_type="video", **model_
pipe = kwargs.pop("pipe")
if "coTenantsMap" not in kwargs: kwargs["coTenantsMap"] = {}
mmgp_profile = init_pipe(pipe, kwargs, profile)
- if server_config.get("enhancer_mode", 0) == 0:
+ if server_config.get("enhancer_mode", 1) == 0:
setup_prompt_enhancer(pipe, kwargs)
loras_transformer = kwargs.pop("loras", [])
if "transformer" in pipe:
@@ -3641,12 +3806,13 @@ def build_callback(state, pipe, send_cmd, status, num_inference_steps, preview_m
return
if override_num_inference_steps > 0:
gen["num_inference_steps"] = override_num_inference_steps
-
+
num_inference_steps = gen.get("num_inference_steps", 0)
status = gen["progress_status"]
state["refresh"] = refresh_id
if read_state:
- phase, step_idx = gen["progress_phase"]
+ phase, state_step_idx = gen["progress_phase"]
+ step_idx = state_step_idx if step_idx < 0 else step_idx + 1
else:
step_idx += 1
if gen.get("abort", False):
@@ -4204,17 +4370,33 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
video_activated_loras = [ f"<span class='copy-swap' tabindex=0><SPAN class='copy-swap__trunc' >{os.path.basename(lora)}</span><span class='copy-swap__full'>{lora}</span></span>" for lora in video_activated_loras]
video_activated_loras = [ f"<TR><TD style='padding-top:0px;padding-left:0px'>{lora}</TD><TD>x{multiplier if len(multiplier)>0 else '1'}</TD></TR>" for lora, multiplier in zip(video_activated_loras, video_loras_multipliers) ]
video_activated_loras_str = "<TABLE style='border:0px;padding:0px'>" + "".join(video_activated_loras) + "</TABLE>" if len(video_activated_loras) > 0 else ""
+ video_duration_seconds = configs.get("duration_seconds", 0)
+ if model_def.get("duration_slider", None) is not None and video_duration_seconds > 0:
+ misc_values += [ f"{video_duration_seconds}s"]
+ misc_labels += ["Duration"]
+ prompt_class = model_def.get("prompt_class","Text Prompt")
values += misc_values + [video_prompt]
- labels += misc_labels + ["Text Prompt"]
+ labels += misc_labels + [ prompt_class]
alt_prompt_def = model_def.get("alt_prompt", None)
- alt_prompt_label = alt_prompt_def.get("label") if isinstance(alt_prompt_def, dict) else None
- alt_prompt = html.escape(configs.get("alt_prompt", "")[:1024]).replace("\n", "<BR>")
- if alt_prompt_label and len(alt_prompt):
- values += [alt_prompt]
- labels += [alt_prompt_label]
+ if alt_prompt_def is not None:
+ alt_prompt_label = alt_prompt_def.get("name", alt_prompt_def.get("label"))
+ alt_prompt = html.escape(configs.get("alt_prompt", "")[:1024]).replace("\n", "<BR>")
+ if len(alt_prompt):
+ values += [alt_prompt]
+ labels += [alt_prompt_label]
+ extra_info = configs.get("extra_info", None)
+ if isinstance(extra_info, dict):
+ for extra_label, extra_text in extra_info.items():
+ if extra_text is None:
+ continue
+ extra_text = str(extra_text).strip()
+ if len(extra_text) == 0:
+ continue
+ values += [html.escape(extra_text[:4096]).replace("\n", "<BR>")]
+ labels += [html.escape(str(extra_label))]
if len(enhanced_video_prompt):
values += [enhanced_video_prompt]
- labels += ["Enhanced Text Prompt"]
+ labels += ["Enhanced {prompt_class}"]
if len(video_other_prompts) >0 :
values += [video_other_prompts]
labels += ["Other Prompts"]
@@ -4266,6 +4448,18 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, aud
if model_def.get("temperature", True) and video_temperature is not None:
values += [video_temperature]
labels += ["Temperature"]
+ video_custom_settings = configs.get("custom_settings", None)
+ if isinstance(video_custom_settings, dict):
+ custom_settings = get_model_custom_settings(model_def)
+ for idx, setting_def in enumerate(custom_settings):
+ setting_id = setting_def.get("id", get_custom_setting_id(setting_def, idx))
+ setting_value = video_custom_settings.get(setting_id, None)
+ if setting_value is None:
+ continue
+ if isinstance(setting_value, str) and len(setting_value.strip()) == 0:
+ continue
+ values += [setting_value]
+ labels += [setting_def.get("name", f"Custom Setting {idx + 1}")]
if model_def.get("top_k_slider", False) and video_top_k is not None:
values += [video_top_k]
labels += ["Top-k"]
@@ -5534,9 +5728,8 @@ def generate_video(
min_frames_if_references,
override_profile,
override_attention,
- pace,
- exaggeration,
temperature,
+ custom_settings,
top_k,
self_refiner_setting,
self_refiner_plan,
@@ -5556,6 +5749,13 @@ def generate_video(
if temp_filename!= None and os.path.isfile(temp_filename):
os.remove(temp_filename)
+ def set_progress_status(status):
+ phase_text = str(status or "").strip()
+ if len(phase_text) == 0:
+ return
+ gen["progress_phase"] = (phase_text, -1)
+ send_cmd("progress", [0, get_latest_status(state, phase_text)])
+
global wan_model, offloadobj, reload_needed
gen = get_gen_info(state)
gen["early_stop"] = False
@@ -5615,7 +5815,7 @@ def generate_video(
if new_vae_upsampling: model_kwargs = {"VAE_upsampling": new_vae_upsampling}
output_type = get_output_type_for_model(model_type, image_mode)
profile = compute_profile(override_profile, output_type)
- enhancer_mode = server_config.get("enhancer_mode", 0)
+ enhancer_mode = server_config.get("enhancer_mode", 1)
if model_type != transformer_type or reload_needed or profile != loaded_profile:
wan_model = None
release_model()
@@ -6306,6 +6506,8 @@ def generate_video(
prefix_video_for_model = prefix_video
if prefix_video is not None and prefix_video.dtype == torch.uint8:
prefix_video_for_model = prefix_video.float().div_(127.5).sub_(1.0)
+ custom_settings_for_model = custom_settings if isinstance(custom_settings, dict) else {}
+ overridden_inputs = None
samples = wan_model.generate(
input_prompt = prompt,
alt_prompt = alt_prompt,
@@ -6393,8 +6595,7 @@ def generate_video(
image_refs_relative_size = image_refs_relative_size,
outpainting_dims = outpainting_dims,
face_arc_embeds = face_arc_embeds,
- exaggeration=exaggeration,
- pace=pace,
+ custom_settings=custom_settings_for_model,
temperature=temperature,
window_start_frame_no = window_start_frame,
input_video_strength = input_video_strength,
@@ -6405,6 +6606,7 @@ def generate_video(
duration_seconds=duration_seconds,
pause_seconds=pause_seconds,
top_k=top_k,
+ set_progress_status=set_progress_status,
)
except Exception as e:
if len(control_audio_tracks) > 0 or len(source_audio_tracks) > 0:
@@ -6459,6 +6661,7 @@ def generate_video(
overlapped_latents = samples.get("latent_slice", None)
BGRA_frames = samples.get("BGRA_frames", None)
generated_audio = samples.get("audio", generated_audio)
+ overridden_inputs = samples.get("overridden_inputs", None)
if generated_audio is not None:
if model_def.get("output_audio_is_input_audio", False) and output_new_audio_filepath is not None:
generated_audio = None
@@ -6577,6 +6780,7 @@ def generate_video(
extension = container
output_dir = save_path
inputs = get_function_arguments(generate_video, locals())
+ if overridden_inputs is not None: inputs.update(overridden_inputs)
if len(output_filename):
from shared.utils.filename_formatter import FilenameFormatter
file_name = FilenameFormatter.format_filename(output_filename, inputs)
@@ -6853,7 +7057,7 @@ def process_tasks(state):
gen_in_progress = True
gen["in_progress"] = True
gen["preview"] = None
- gen["status"] = "Generating Video"
+ gen["status"] = "Generating..."
gen["header_text"] = ""
yield time.time(), time.time()
@@ -6895,6 +7099,7 @@ def process_tasks(state):
model_type = params.get('model_type')
known_defaults = {
'image_refs_relative_size': 50,
+ 'custom_settings': None,
}
for arg_name, default_value in known_defaults.items():
@@ -6903,12 +7108,15 @@ def process_tasks(state):
params[arg_name] = default_value
if model_type:
default_settings = get_default_settings(model_type)
- expected_args = inspect.signature(generate_video).parameters.keys()
+ expected_args = set(inspect.signature(generate_video).parameters.keys())
for arg_name in expected_args:
if arg_name not in params and arg_name in default_settings:
params[arg_name] = default_settings[arg_name]
+ else:
+ expected_args = set(inspect.signature(generate_video).parameters.keys())
+ filtered_params = {k: v for k, v in params.items() if k in expected_args}
plugin_data = task.pop('plugin_data', {})
- generate_video(task, send_cmd, plugin_data=plugin_data, **params)
+ generate_video(task, send_cmd, plugin_data=plugin_data, **filtered_params)
except Exception as e:
tb = traceback.format_exc().split('\n')[:-1]
print('\n'.join(tb))
@@ -6926,6 +7134,16 @@ def process_tasks(state):
gr.Info(data)
elif cmd == "error":
queue.clear()
+ try:
+ error_filename = get_available_filename("", AUTOSAVE_ERROR_FILENAME)
+ if _save_queue_to_zip(global_queue_ref, error_filename):
+ print(f"Error Queue autosaved successfully to {error_filename}")
+ gr.Info(f"Error Queue autosaved successfully to {error_filename}")
+ else:
+ print("Autosave Error Queue failed.")
+ except Exception as e:
+ print(f"Error during autosave: {e}")
+ update_global_queue_ref(queue)
gen["prompts_max"] = 0
gen["prompt"] = ""
gen["status_display"] = False
@@ -7634,6 +7852,13 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
if model_type == None: model_type = get_state_model_type(state)
inputs["activated_loras"] = update_loras_url_cache(get_lora_dir(model_type), loras_choices)
+ model_def = get_model_def(model_type)
+ custom_settings = get_model_custom_settings(model_def)
+ parsed_custom_settings, _ = collect_custom_settings_from_inputs(model_def, inputs, strict=False)
+ inputs["custom_settings"] = parsed_custom_settings if len(custom_settings) > 0 else None
+ clear_custom_setting_slots(inputs)
+ inputs.pop("pace", None)
+ inputs.pop("exaggeration", None)
if target in ["state", "edit_state"]:
return inputs
@@ -7646,7 +7871,6 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
inputs.pop(k)
inputs["type"] = get_model_record(get_model_name(model_type))
inputs["settings_version"] = settings_version
- model_def = get_model_def(model_type)
base_model_type = get_base_model_type(model_type)
model_family = get_model_family(base_model_type)
if model_type != base_model_type:
@@ -7661,8 +7885,10 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
image_outputs = inputs.get("image_mode",0) > 0
pop=[]
+ if len(custom_settings) == 0:
+ pop += ["custom_settings"]
if not model_def.get("audio_only", False):
- pop += [ "pace", "exaggeration", "temperature"]
+ pop += ["temperature"]
if model_def.get("duration_slider", None) is None:
pop += ["duration_seconds"]
if not model_def.get("pause_between_sentences", False):
@@ -7695,7 +7921,7 @@ def prepare_inputs_dict(target, inputs, model_type = None, model_filename = None
pop += ["input_video_strength"]
- if not (server_config.get("enhancer_enabled", 0) > 0 and server_config.get("enhancer_mode", 0) == 0):
+ if not (server_config.get("enhancer_enabled", 0) > 0 and server_config.get("enhancer_mode", 1) == 0):
pop += ["prompt_enhancer"]
if model_def.get("model_modes", None) is None:
@@ -8427,9 +8653,12 @@ def save_inputs(
min_frames_if_references,
override_profile,
override_attention,
- pace,
- exaggeration,
temperature,
+ custom_setting_1,
+ custom_setting_2,
+ custom_setting_3,
+ custom_setting_4,
+ custom_setting_5,
top_k,
self_refiner_setting,
self_refiner_plan,
@@ -8874,23 +9103,25 @@ def show_modal_image(state, action_string):
html_content = get_modal_image(image_data[img_index], label_data[img_index])
return gr.HTML(value=html_content), gr.Column(visible=True)
-def get_prompt_labels(multi_prompts_gen_type, image_outputs = False, audio_only = False):
+def get_prompt_labels(multi_prompts_gen_type, model_def, image_outputs = False, audio_only = False):
+
+ prompt_description= model_def.get("prompt_description", None)
+ if prompt_description is not None: return prompt_description, prompt_description
if multi_prompts_gen_type == 1:
new_line_text = "each Line of Prompt will be used for a Sliding Window"
elif multi_prompts_gen_type == 0:
new_line_text = "each Line of Prompt will generate " + ("a new Image" if image_outputs else ("a new Audio File" if audio_only else "a new Video"))
else:
new_line_text = "all the Lines are Parts of the Same Prompt"
+ prompt_class= model_def.get("prompt_class", "Prompts")
- return "Prompts (" + new_line_text + ", # lines = comments, ! lines = macros)", "Prompts (" + new_line_text + ", # lines = comments)"
+ return f"{prompt_class} ({new_line_text}, # lines = comments, ! lines = macros)", f"{prompt_class} ({new_line_text}, # lines = comments)"
def get_image_end_label(multi_prompts_gen_type):
return "Images as ending points for new Videos in the Generation Queue" if multi_prompts_gen_type == 0 else "Images as ending points for each new Window of the same Video Generation"
def refresh_prompt_labels(state, multi_prompts_gen_type, image_mode):
- mode_def = get_model_def(get_state_model_type(state))
-
- prompt_label, wizard_prompt_label = get_prompt_labels(multi_prompts_gen_type, image_mode > 0, mode_def.get("audio_only", False))
+ prompt_label, wizard_prompt_label = get_prompt_labels(multi_prompts_gen_type, model_def, image_mode > 0, mode_def.get("audio_only", False))
return gr.update(label=prompt_label), gr.update(label = wizard_prompt_label), gr.update(label=get_image_end_label(multi_prompts_gen_type))
def update_video_guide_outpainting(video_guide_outpainting_value, value, pos):
@@ -9201,6 +9432,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
state_dict["loras"] = loras
state_dict["loras_presets"] = loras_presets
+ custom_setting_components_map = {}
launch_prompt = ""
launch_preset = ""
@@ -9269,7 +9501,6 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
any_mag_cache = model_def.get("mag_cache", False)
recammaster = base_model_type in ["recam_1.3B"]
vace = test_vace_module(base_model_type)
- fantasy = base_model_type in ["fantasy"]
multitalk = model_def.get("multitalk_class", False)
infinitetalk = base_model_type in ["infinitetalk"]
hunyuan_t2v = "hunyuan_video_720" in model_filename
@@ -9279,7 +9510,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
image_outputs = model_def.get("image_outputs", False)
sliding_window_enabled = test_any_sliding_window(model_type)
multi_prompts_gen_type_value = ui_get("multi_prompts_gen_type")
- prompt_label, wizard_prompt_label = get_prompt_labels(multi_prompts_gen_type_value, image_outputs, audio_only)
+ prompt_label, wizard_prompt_label = get_prompt_labels(multi_prompts_gen_type_value, model_def, image_outputs, audio_only)
any_video_source = False
fps = get_model_fps(base_model_type)
image_prompt_type_value = ""
@@ -9703,7 +9934,8 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
on_demand_prompt_enhancer = server_config.get("enhancer_mode", 0) == 1
prompt_enhancer_choices_allowed = model_def.get("prompt_enhancer_choices_allowed", ["T"] if audio_only else ["T", "I", "TI"])
prompt_enhancer_value = ui_get("prompt_enhancer")
- prompt_enhancer_btn = gr.Button( value ="Enhance Prompt", visible= on_demand_prompt_enhancer, size="lg", elem_classes="btn_centered")
+ prompt_enhancer_btn_label = str(model_def.get("prompt_enhancer_button_label", "Enhance Prompt"))
+ prompt_enhancer_btn = gr.Button( value =prompt_enhancer_btn_label, visible= on_demand_prompt_enhancer, size="lg", elem_classes="btn_centered")
prompt_enhancer_choices= ([] if on_demand_prompt_enhancer else [("Disabled", "")])
if "T" in prompt_enhancer_choices_allowed:
prompt_enhancer_choices += [("Based on Text Prompt Content", "T")]
@@ -9739,10 +9971,36 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
else:
with gr.Row(visible=False) as alt_prompt_row:
alt_prompt = gr.Textbox(value=ui_get("alt_prompt", ""), visible=False)
- chatterbox_controls = model_def.get("chatterbox_controls", False)
- with gr.Row(visible=audio_only and chatterbox_controls) as chatter_row:
- exaggeration = gr.Slider( 0.25, 2.0, value=ui_get("exaggeration"), step=0.01, label="Emotion Exaggeration (0.5 = Neutral)", show_reset_button= False)
- pace = gr.Slider( 0.2, 1, value=ui_get("pace"), step=0.01, label="Pace", show_reset_button= False)
+
+ custom_settings = get_model_custom_settings(model_def)
+ custom_settings_values = ui_get("custom_settings", None)
+ if not isinstance(custom_settings_values, dict):
+ custom_settings_values = {}
+ custom_settings_rows = []
+ custom_setting_rows_count = math.ceil(CUSTOM_SETTINGS_MAX / CUSTOM_SETTINGS_PER_ROW)
+ for row_idx in range(custom_setting_rows_count):
+ row_start = row_idx * CUSTOM_SETTINGS_PER_ROW
+ row_end = min(row_start + CUSTOM_SETTINGS_PER_ROW, CUSTOM_SETTINGS_MAX)
+ row_visible = row_start < len(custom_settings)
+ with gr.Row(visible=row_visible) as custom_settings_row:
+ for setting_index in range(row_start, row_end):
+ setting_key = get_custom_setting_key(setting_index)
+ setting_def = custom_settings[setting_index] if setting_index < len(custom_settings) else None
+ setting_visible = setting_def is not None
+ setting_default = get_custom_setting_value_from_dict(custom_settings_values, setting_def, setting_index) if setting_def is not None else ""
+ if setting_default is None:
+ setting_default = ""
+ setting_label = setting_def.get("label", f"Custom Setting {setting_index + 1}") if setting_def is not None else f"Custom Setting {setting_index + 1}"
+ custom_setting_component = gr.Textbox(
+ value=str(setting_default),
+ label=setting_label,
+ visible=setting_visible,
+ lines=1,
+ )
+ custom_setting_components_map[setting_key] = custom_setting_component
+ custom_settings_rows.append(custom_settings_row)
+
+
duration_def = model_def.get("duration_slider", None)
duration_visible = audio_only and duration_def is not None
if duration_def is None:
@@ -10397,11 +10655,12 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
audio_buttons_row, deleted_audio_buttons_row, video_info_extract_audio_settings_btn, video_info_to_audio_guide_btn, video_info_to_audio_guide2_btn, video_info_to_audio_source_btn, video_info_eject_audio_btn,
video_info_to_start_image_btn, video_info_to_end_image_btn, video_info_to_reference_image_btn, video_info_to_image_guide_btn, video_info_to_image_mask_btn,
NAG_col, remove_background_sound , speakers_locations_row, embedded_guidance_row, guidance_phases_row, guidance_row, resolution_group, cfg_free_guidance_col, control_net_weights_row, guide_selection_row, image_mode_tabs,
- min_frames_if_references_col, motion_amplitude_col, video_prompt_type_alignment, prompt_enhancer_btn, tab_inpaint, tab_t2v, resolution_row, loras_tab, post_processing_tab, temperature_row, top_k_row, number_frames_row, negative_prompt_row, chatter_row,
+ min_frames_if_references_col, motion_amplitude_col, video_prompt_type_alignment, prompt_enhancer_btn, tab_inpaint, tab_t2v, resolution_row, loras_tab, post_processing_tab, temperature_row, *custom_settings_rows, top_k_row, number_frames_row, negative_prompt_row,
self_refiner_col, pause_row]+\
image_start_extra + image_end_extra + image_refs_extra # presets_column,
if update_form:
locals_dict = locals()
+ locals_dict.update(custom_setting_components_map)
gen_inputs = [state_dict if k=="state" else locals_dict[k] for k in inputs_names] + [state_dict, plugin_data] + extra_inputs
return gen_inputs
else:
@@ -10503,6 +10762,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
inputs_names= list(inspect.signature(save_inputs).parameters)[1:-2]
locals_dict = locals()
+ locals_dict.update(custom_setting_components_map)
gen_inputs = [locals_dict[k] for k in inputs_names] + [state, plugin_data]
save_settings_btn.click( fn=validate_wizard_prompt, inputs =[state, wizard_prompt_activated_var, wizard_variables_var, prompt, wizard_prompt, *prompt_vars] , outputs= [prompt]).then(
save_inputs, inputs =[target_settings] + gen_inputs, outputs = [])
@@ -10813,6 +11073,7 @@ def generate_video_tab(update_form = False, state_dict = None, ui_defaults = Non
outputs=[current_gen_column, queue_accordion]
)
locals_dict = locals()
+ locals_dict.update(custom_setting_components_map)
if update_form:
gen_inputs = [state_dict if k=="state" else locals_dict[k] for k in inputs_names] + [state_dict, plugin_data] + extra_inputs
return gen_inputs
@@ -11513,12 +11774,6 @@ if __name__ == "__main__":
except Exception as e:
print(f"Warning: Could not create startup lock file: {e}")
- def mark_startup_success():
- time.sleep(30)
- clear_startup_lock()
-
- threading.Thread(target=mark_startup_success, daemon=True).start()
-
download_ffmpeg()
# threading.Thread(target=runner, daemon=True).start()
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
@@ -11531,6 +11786,7 @@ if __name__ == "__main__":
if len(server_name) == 0:
server_name = os.getenv("SERVER_NAME", "localhost")
demo = create_ui()
+ clear_startup_lock()
if args.open_browser:
import webbrowser
if server_name.startswith("http"):