Merge main and preserve dispatch backlog across monitor windows
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
ea7de7e3de
769 files changed
+73802
-22805
No files matched your search
@@ -24,6 +24,14 @@ def _triton_backend() -> Any:
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
# The Fish kvcache fast path is CUDA-only: it depends on FlashAttention's
|
||||
# use_cascade metadata (absent from Ascend's metadata) and a Triton CUDA
|
||||
# kernel. On other platforms report unavailable so the native attention
|
||||
# backend takes over instead of crashing on attn_metadata.use_cascade.
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
return False
|
||||
return _triton_backend().is_available()
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,237 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Video-MME multiple-choice accuracy scoring for vLLM-Omni bench serve.
|
||||
|
||||
Answer extraction ports ``extract_characters_regex`` from the official Video-MME
|
||||
script (MME-Benchmarks ``eval_your_results.py``, also used by lmms-eval).
|
||||
|
||||
**Denominator:** responses where no A–D can be extracted are counted as wrong, which
|
||||
matches lmms-eval and OmniEvalKit (the numbers this bench is compared against). The
|
||||
official standalone script instead drops them from ``answered``; ``videomme_parse_failed``
|
||||
is reported so that view can be recovered.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import regex as re
|
||||
from vllm.benchmarks.lib.endpoint_request_func import RequestFuncOutput
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.videomme_dataset import VideoMMESampleRequest
|
||||
|
||||
_VALID = frozenset("ABCD")
|
||||
|
||||
VIDEOMME_DURATION_KEYS: tuple[str, ...] = ("short", "medium", "long")
|
||||
|
||||
#: Report dimension -> ``VideoMMESampleRequest`` attribute (official Video-MME breakdowns).
|
||||
_DIMENSIONS: dict[str, str] = {
|
||||
"duration": "videomme_duration",
|
||||
"domain": "videomme_domain",
|
||||
"sub_category": "videomme_sub_category",
|
||||
"task": "videomme_task_type",
|
||||
}
|
||||
|
||||
# Official prefix list, with the two accidental string concatenations in the upstream
|
||||
# tuple (missing commas after "The best option is" / "Best answer:") split apart.
|
||||
_ANSWER_PREFIXES = (
|
||||
"The best answer is",
|
||||
"The correct answer is",
|
||||
"The answer is",
|
||||
"The answer",
|
||||
"The best option is",
|
||||
"The correct option is",
|
||||
"Best answer:",
|
||||
"Best option:",
|
||||
"Answer:",
|
||||
"Option:",
|
||||
"The correct answer",
|
||||
"The correct option",
|
||||
)
|
||||
|
||||
|
||||
def extract_characters_regex(text: str | None) -> str | None:
|
||||
"""Port of official Video-MME / lmms-eval ``extract_characters_regex``."""
|
||||
if not text:
|
||||
return None
|
||||
s = str(text).strip()
|
||||
for prefix in _ANSWER_PREFIXES:
|
||||
s = s.replace(prefix, "")
|
||||
if len(s.split()) > 10 and not re.search(r"[ABCD]", s):
|
||||
return None
|
||||
match = re.search(r"[ABCD]", s)
|
||||
return match.group(0) if match else None
|
||||
|
||||
|
||||
def normalize_gold_answer(gold: str) -> str | None:
|
||||
g = (gold or "").strip().upper()
|
||||
if len(g) == 1 and g in _VALID:
|
||||
return g
|
||||
m = re.search(r"([ABCD])\b", g)
|
||||
return m.group(1).upper() if m else None
|
||||
|
||||
|
||||
def _bucket(req: VideoMMESampleRequest, dimension: str) -> str:
|
||||
value = (getattr(req, _DIMENSIONS[dimension]) or "").strip()
|
||||
if dimension == "duration":
|
||||
return value.lower()
|
||||
return value or "unknown"
|
||||
|
||||
|
||||
def compute_videomme_accuracy_metrics(
|
||||
input_requests: list[Any],
|
||||
outputs: list[RequestFuncOutput],
|
||||
*,
|
||||
include_per_item: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
"""If all requests are :class:`VideoMMESampleRequest`, compute accuracy stats.
|
||||
|
||||
Rows without a gold answer are skipped (``no_gold``). Failed HTTP requests are
|
||||
excluded from ``videomme_accuracy`` and counted in
|
||||
``videomme_accuracy_incl_http_fail`` instead. The accuracy wrapper gate
|
||||
(``_validate_videomme``) additionally rejects HTTP failures, duplicate question
|
||||
IDs, skipped source rows and missing gold answers. Direct
|
||||
``vllm bench serve`` still reports both metrics without that completeness
|
||||
check.
|
||||
|
||||
``videomme_submitted`` / ``videomme_unique_question_ids`` show when
|
||||
oversampling made the request count differ from unique question coverage.
|
||||
``videomme_skipped_rows`` counts source rows skipped during sampling (for
|
||||
example, missing or undecodable media), before any oversampling.
|
||||
"""
|
||||
if not input_requests or len(input_requests) != len(outputs):
|
||||
return None
|
||||
if not all(isinstance(r, VideoMMESampleRequest) for r in input_requests):
|
||||
return None
|
||||
|
||||
stats: dict[str, dict[str, dict[str, int]]] = {
|
||||
dim: ({k: {"correct": 0, "total": 0} for k in VIDEOMME_DURATION_KEYS} if dim == "duration" else {})
|
||||
for dim in _DIMENSIONS
|
||||
}
|
||||
items: list[dict[str, Any]] = []
|
||||
correct = evaluated = no_gold = request_failed = parse_failed = 0
|
||||
|
||||
for req, out in zip(input_requests, outputs, strict=True):
|
||||
assert isinstance(req, VideoMMESampleRequest)
|
||||
gold_raw = (req.videomme_gold_answer or "").strip()
|
||||
buckets = {dim: _bucket(req, dim) for dim in _DIMENSIONS}
|
||||
row: dict[str, Any] = {
|
||||
"request_id": req.request_id,
|
||||
"video_id": req.videomme_video_id,
|
||||
"question_id": req.videomme_question_id,
|
||||
**buckets,
|
||||
}
|
||||
|
||||
if not gold_raw:
|
||||
no_gold += 1
|
||||
if include_per_item:
|
||||
items.append({**row, "skipped": True, "reason": "no_gold"})
|
||||
continue
|
||||
|
||||
evaluated += 1
|
||||
gold_norm = normalize_gold_answer(gold_raw)
|
||||
pred = extract_characters_regex(out.generated_text) if out.success else None
|
||||
is_correct = pred is not None and pred.upper() == (gold_norm or gold_raw).upper()
|
||||
|
||||
if not out.success:
|
||||
request_failed += 1
|
||||
else:
|
||||
if pred is None:
|
||||
parse_failed += 1
|
||||
# Only successful responses enter the per-dimension denominators, mirroring
|
||||
# the overall videomme_accuracy definition.
|
||||
for dim, key in buckets.items():
|
||||
bucket = stats[dim].setdefault(key, {"correct": 0, "total": 0})
|
||||
bucket["total"] += 1
|
||||
bucket["correct"] += int(is_correct)
|
||||
|
||||
if is_correct:
|
||||
correct += 1
|
||||
|
||||
if include_per_item:
|
||||
items.append(
|
||||
{
|
||||
**row,
|
||||
"gold": gold_raw,
|
||||
"gold_normalized": gold_norm,
|
||||
"predicted": pred,
|
||||
"correct": is_correct,
|
||||
"parse_failed": out.success and pred is None,
|
||||
**({"error": (out.error or "")[:500]} if not out.success else {}),
|
||||
}
|
||||
)
|
||||
|
||||
evaluated_ok = evaluated - request_failed
|
||||
unique_question_ids = {
|
||||
(req.videomme_question_id or req.request_id) for req in input_requests if isinstance(req, VideoMMESampleRequest)
|
||||
}
|
||||
result: dict[str, Any] = {
|
||||
"videomme_accuracy": (correct / evaluated_ok) if evaluated_ok else None,
|
||||
"videomme_accuracy_incl_http_fail": (correct / evaluated) if evaluated else None,
|
||||
"videomme_correct": correct,
|
||||
"videomme_evaluated": evaluated,
|
||||
"videomme_evaluated_ok": evaluated_ok,
|
||||
"videomme_no_gold": no_gold,
|
||||
"videomme_request_failed": request_failed,
|
||||
"videomme_parse_failed": parse_failed,
|
||||
"videomme_submitted": len(input_requests),
|
||||
"videomme_unique_question_ids": len(unique_question_ids),
|
||||
"videomme_skipped_rows": max(req.videomme_skipped_rows for req in input_requests),
|
||||
}
|
||||
for dim, per_bucket in stats.items():
|
||||
result[f"videomme_per_{dim}"] = {k: dict(v) for k, v in per_bucket.items()}
|
||||
result[f"videomme_per_{dim}_accuracy"] = {
|
||||
k: (v["correct"] / v["total"]) if v["total"] else None for k, v in per_bucket.items()
|
||||
}
|
||||
if include_per_item:
|
||||
result["videomme_eval_items"] = items
|
||||
return result
|
||||
|
||||
|
||||
def print_videomme_accuracy_summary(metrics: dict[str, Any]) -> None:
|
||||
"""Pretty-print the Video-MME accuracy block (stdout)."""
|
||||
acc = metrics.get("videomme_accuracy")
|
||||
if acc is None and not metrics.get("videomme_evaluated", 0):
|
||||
return
|
||||
|
||||
print("{s:{c}^{n}}".format(s=" Video-MME accuracy (MCQ) ", n=50, c="="))
|
||||
ok = int(metrics.get("videomme_evaluated_ok", 0) or 0)
|
||||
if ok and acc is not None:
|
||||
print(f"Overall Accuracy: {metrics.get('videomme_correct', 0)}/{ok} = {acc:.2%}")
|
||||
else:
|
||||
print("Overall Accuracy: 0/0 = N/A (no successful HTTP responses)")
|
||||
for label, key in (
|
||||
("Submitted (gold present):", "videomme_evaluated"),
|
||||
("Successful HTTP (denominator):", "videomme_evaluated_ok"),
|
||||
("Correct:", "videomme_correct"),
|
||||
("Skipped (no gold):", "videomme_no_gold"),
|
||||
("HTTP failed:", "videomme_request_failed"),
|
||||
("Parsed OK but no A-D found:", "videomme_parse_failed"),
|
||||
("Submitted requests:", "videomme_submitted"),
|
||||
("Unique questions:", "videomme_unique_question_ids"),
|
||||
("Skipped source rows:", "videomme_skipped_rows"),
|
||||
):
|
||||
print(f"{label:<40} {metrics.get(key, 0):<10}")
|
||||
|
||||
for dim, title in (
|
||||
("duration", "Duration"),
|
||||
("domain", "Domain"),
|
||||
("sub_category", "Sub Category"),
|
||||
("task", "Task Type"),
|
||||
):
|
||||
per_acc = metrics.get(f"videomme_per_{dim}_accuracy") or {}
|
||||
if not per_acc:
|
||||
continue
|
||||
counts = metrics.get(f"videomme_per_{dim}") or {}
|
||||
names = VIDEOMME_DURATION_KEYS if dim == "duration" else sorted(per_acc)
|
||||
print(f"\n--- Accuracy by {title} ---")
|
||||
for name in names:
|
||||
st = counts.get(name) or {}
|
||||
total = int(st.get("total", 0) or 0)
|
||||
value = per_acc.get(name)
|
||||
if total and value is not None:
|
||||
print(f"{name}: {int(st.get('correct', 0))}/{total} = {value:.2%}")
|
||||
else:
|
||||
print(f"{name}: 0/0 = N/A")
|
||||
print("=" * 50)
|
||||
@@ -6,7 +6,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -168,7 +167,7 @@ def _extract_frames(path: str | Path, timestamps: list[float]) -> list[bytes]:
|
||||
for timestamp in timestamps:
|
||||
try:
|
||||
frame = extract_jpeg(path, timestamp=timestamp)
|
||||
except (OSError, subprocess.CalledProcessError, ValueError):
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if frame.startswith(b"\xff\xd8"):
|
||||
frames.append(frame)
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Small ffmpeg-backed media helpers used by the duplex runner and judge."""
|
||||
"""Small media helpers used by the duplex runner and judge.
|
||||
|
||||
Video and audio decoding is delegated to PyAV (``av``), which bundles a pinned
|
||||
FFmpeg version, so results do not depend on whatever ffmpeg binary the host
|
||||
provides (see #7364: host ffmpeg 4.4.2 could hang forever on some HEVC clips).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
from collections.abc import Iterator
|
||||
@@ -15,10 +21,7 @@ from typing import Any
|
||||
|
||||
from vllm_omni.experimental.fullduplex.client import PCM16_BYTES_PER_SAMPLE, PCM16_SAMPLE_RATE
|
||||
|
||||
|
||||
def _run_ffmpeg(args: list[str]) -> bytes:
|
||||
result = subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", *args], capture_output=True, check=True)
|
||||
return result.stdout
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def materialize_media(value: Any, output_dir: str | Path, stem: str, suffix: str) -> Path:
|
||||
@@ -77,31 +80,73 @@ def _write_media_bytes(payload: bytes | bytearray, output_dir: str | Path, stem:
|
||||
|
||||
|
||||
def video_duration(path: str | Path) -> float:
|
||||
result = subprocess.run(
|
||||
["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=nw=1:nk=1", str(path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return max(0.0, float(result.stdout.strip()))
|
||||
"""Return the video duration in seconds using PyAV (no ffprobe subprocess).
|
||||
|
||||
Raises:
|
||||
OSError: If the file cannot be opened (missing file, permission denied, etc.).
|
||||
ValueError: If the file is corrupt or cannot be parsed (e.g.
|
||||
:class:`av.error.InvalidDataError`).
|
||||
"""
|
||||
import av
|
||||
|
||||
try:
|
||||
with av.open(str(path)) as container:
|
||||
# Container-level duration is the same source ffprobe's format=duration reads.
|
||||
if container.duration and container.duration > 0:
|
||||
return max(0.0, container.duration / av.time_base)
|
||||
if container.streams.video:
|
||||
stream = container.streams.video[0]
|
||||
if stream.duration is not None and stream.time_base is not None:
|
||||
return max(0.0, float(stream.duration * stream.time_base))
|
||||
# Last resort: count decodable frames.
|
||||
if container.streams.video:
|
||||
stream = container.streams.video[0]
|
||||
stream.thread_type = "AUTO"
|
||||
frame_count = sum(1 for _ in container.decode(stream))
|
||||
if stream.average_rate and frame_count > 0:
|
||||
return frame_count / float(stream.average_rate)
|
||||
return 0.0
|
||||
except (OSError, ValueError) as exc:
|
||||
logger.warning("Failed to read video duration from %s: %s", path, exc)
|
||||
raise
|
||||
|
||||
|
||||
def extract_jpeg(path: str | Path, *, timestamp: float, quality: int = 3) -> bytes:
|
||||
return _run_ffmpeg(
|
||||
[
|
||||
"-ss",
|
||||
f"{max(0.0, timestamp):.3f}",
|
||||
"-i",
|
||||
str(path),
|
||||
"-frames:v",
|
||||
"1",
|
||||
"-q:v",
|
||||
str(quality),
|
||||
"-f",
|
||||
"image2",
|
||||
"pipe:1",
|
||||
]
|
||||
)
|
||||
"""Extract a single JPEG frame at ``timestamp`` using PyAV.
|
||||
|
||||
``quality`` follows the ffmpeg ``-q:v`` convention (lower = better, 1..31)
|
||||
and is mapped to the PIL JPEG quality scale (higher = better).
|
||||
|
||||
After ``seek`` the function continues decoding until a frame with PTS >=
|
||||
target_pts is found, matching the ``ffmpeg -ss`` semantic of returning the
|
||||
first decodable frame *at or after* the requested timestamp.
|
||||
|
||||
Raises:
|
||||
ValueError: If the file contains no video stream or no frame could be decoded.
|
||||
"""
|
||||
import av
|
||||
|
||||
with av.open(str(path)) as container:
|
||||
if not container.streams.video:
|
||||
raise ValueError(f"no video stream in {path}")
|
||||
stream = container.streams.video[0]
|
||||
stream.thread_type = "AUTO"
|
||||
time_base = stream.time_base
|
||||
if time_base is None:
|
||||
time_base = 1 / 90000
|
||||
target_pts = int(max(0.0, timestamp) / time_base)
|
||||
container.seek(target_pts, any_frame=False, backward=True, stream=stream)
|
||||
closest_frame = None
|
||||
for frame in container.decode(stream):
|
||||
closest_frame = frame
|
||||
if frame.pts is not None and frame.pts >= target_pts:
|
||||
break
|
||||
if closest_frame is not None:
|
||||
image = closest_frame.to_image()
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="JPEG", quality=_ffmpeg_q_to_pil_quality(quality))
|
||||
return buf.getvalue()
|
||||
raise ValueError(f"no decodable video frames in {path} at timestamp {timestamp}")
|
||||
|
||||
|
||||
def iter_jpegs(
|
||||
@@ -113,7 +158,8 @@ def iter_jpegs(
|
||||
while timestamp < end:
|
||||
try:
|
||||
frame = extract_jpeg(path, timestamp=timestamp, quality=quality)
|
||||
except (OSError, subprocess.CalledProcessError):
|
||||
except (OSError, ValueError) as exc:
|
||||
logger.warning("Frame extraction failed at %.3fs for %s: %s", timestamp, path, exc)
|
||||
break
|
||||
if frame:
|
||||
yield timestamp, frame
|
||||
@@ -132,9 +178,28 @@ def read_audio_pcm16(path: str | Path) -> bytes:
|
||||
and wav_file.getcomptype() == "NONE"
|
||||
):
|
||||
return wav_file.readframes(wav_file.getnframes())
|
||||
except wave.Error:
|
||||
except (wave.Error, OSError):
|
||||
pass
|
||||
return _run_ffmpeg(["-i", str(source), "-f", "s16le", "-ac", "1", "-ar", str(PCM16_SAMPLE_RATE), "pipe:1"])
|
||||
# Non-WAV audio: decode and resample to mono s16 PCM via PyAV.
|
||||
import av
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
resampler = av.AudioResampler(format="s16", layout="mono", rate=PCM16_SAMPLE_RATE)
|
||||
chunks: list[Any] = []
|
||||
with av.open(str(source)) as container:
|
||||
for frame in container.decode(audio=0):
|
||||
for resampled in resampler.resample(frame):
|
||||
chunks.append(resampled.to_ndarray())
|
||||
# Flush the resampler to drain buffered tail samples (P3).
|
||||
for resampled in resampler.resample(None):
|
||||
chunks.append(resampled.to_ndarray())
|
||||
if not chunks:
|
||||
return b""
|
||||
return np.concatenate([chunk.reshape(-1) for chunk in chunks]).astype(np.int16).tobytes()
|
||||
except (OSError, ValueError) as exc:
|
||||
logger.warning("Failed to decode audio in %s: %s", source, exc)
|
||||
raise
|
||||
|
||||
|
||||
def iter_av_units(
|
||||
@@ -150,3 +215,9 @@ def iter_av_units(
|
||||
frame = next_frame[1]
|
||||
next_frame = next(frame_iter, None)
|
||||
yield audio_pcm16[offset : offset + unit_bytes], frame
|
||||
|
||||
|
||||
def _ffmpeg_q_to_pil_quality(quality: int) -> int:
|
||||
"""Map ffmpeg ``-q:v`` (1..31, lower = better) to PIL JPEG quality (1..100, higher = better)."""
|
||||
ffmpeg_q = max(1, min(31, int(quality)))
|
||||
return max(1, min(100, round(95 - (ffmpeg_q - 1) * (93 / 30))))
|
||||
@@ -14,7 +14,7 @@ import time
|
||||
import traceback
|
||||
import uuid
|
||||
import wave
|
||||
from collections.abc import Callable, Iterable, Mapping
|
||||
from collections.abc import Callable, Iterable, Iterator, Mapping
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -67,6 +67,12 @@ from vllm_omni.benchmarks.data_modules.seed_tts_dataset import (
|
||||
)
|
||||
from vllm_omni.benchmarks.data_modules.sound_effect_dataset import SoundEffectDataset
|
||||
from vllm_omni.benchmarks.data_modules.ttsd_dataset import TTSDDataset
|
||||
from vllm_omni.benchmarks.data_modules.videomme_dataset import (
|
||||
VIDEOMME_DEFAULT_HF_REPO,
|
||||
VideoMMEDataset,
|
||||
VideoMMESampleRequest,
|
||||
resolve_videomme_local_root,
|
||||
)
|
||||
from vllm_omni.benchmarks.omniinteract import (
|
||||
VIDEO_FPS,
|
||||
OmniInteractBenchmarkConfig,
|
||||
@@ -283,14 +289,14 @@ def _merge_extra_body_mm_kwargs(base: dict | None, overlay: dict | None) -> dict
|
||||
return out
|
||||
|
||||
|
||||
def _attach_daily_omni_to_request_func_input(sample: SampleRequest, rfi: RequestFuncInput) -> None:
|
||||
"""Apply per-request OpenAI fields (``mm_processor_kwargs``, messages) for Daily-Omni."""
|
||||
if not isinstance(sample, DailyOmniSampleRequest):
|
||||
def _attach_omni_chat_to_request_func_input(sample: SampleRequest, rfi: RequestFuncInput) -> None:
|
||||
"""Apply per-request OpenAI fields (``mm_processor_kwargs``, messages) for Daily-Omni / Video-MME."""
|
||||
if not isinstance(sample, (DailyOmniSampleRequest, VideoMMESampleRequest)):
|
||||
return
|
||||
rfi.extra_body = _merge_extra_body_mm_kwargs(rfi.extra_body, sample.omni_extra_body)
|
||||
if sample.omni_chat_messages is not None:
|
||||
setattr(rfi, "omni_chat_messages", sample.omni_chat_messages)
|
||||
else:
|
||||
elif isinstance(sample, DailyOmniSampleRequest):
|
||||
setattr(rfi, "mm_position", sample.omni_chat_mm_position)
|
||||
|
||||
|
||||
@@ -334,6 +340,29 @@ def _attach_omniinteract_to_request_func_input(sample: SampleRequest, rfi: Reque
|
||||
setattr(rfi, "omniinteract_prepared_input", sample.omniinteract_prepared_input)
|
||||
|
||||
|
||||
def _async_limiter(max_concurrency: int | None) -> contextlib.AbstractAsyncContextManager[object]:
|
||||
if max_concurrency:
|
||||
return asyncio.Semaphore(max_concurrency)
|
||||
return contextlib.nullcontext()
|
||||
|
||||
|
||||
def _as_float(value: object, default: float = 0.0) -> float:
|
||||
"""Coerce loosely-typed metric dict values to ``float`` for mypy.
|
||||
|
||||
Strings are parsed rather than dropped: JSON-sourced session metrics such as
|
||||
``audio_duration_ms`` may arrive quoted, and silently reporting ``0.0`` would
|
||||
corrupt the derived TTFT / RTF numbers.
|
||||
"""
|
||||
if isinstance(value, bool) or value is None:
|
||||
return default
|
||||
if isinstance(value, (int, float, str)):
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError:
|
||||
return default
|
||||
return default
|
||||
|
||||
|
||||
def _append_error(existing: str, message: str) -> str:
|
||||
return f"{existing}\n{message}" if existing else message
|
||||
|
||||
@@ -404,9 +433,13 @@ def _prepare_omniinteract_batch(input_requests: list[SampleRequest]) -> None:
|
||||
for sample in input_requests:
|
||||
if not isinstance(sample, OmniInteractSampleRequest):
|
||||
continue
|
||||
root = sample.omniinteract_options.output_root.resolve()
|
||||
options = sample.omniinteract_options
|
||||
case = sample.omniinteract_case
|
||||
if options is None or case is None:
|
||||
raise RuntimeError("OmniInteract benchmark input lost its dataset identity")
|
||||
root = options.output_root.resolve()
|
||||
roots.add(root)
|
||||
clear_case_artifacts(sample.omniinteract_options.output_root, sample.omniinteract_case)
|
||||
clear_case_artifacts(options.output_root, case)
|
||||
for root in roots:
|
||||
clear_batch_artifacts(root)
|
||||
|
||||
@@ -428,11 +461,55 @@ def _daily_omni_repo_from_args(args) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _looks_like_hf_dataset_id(value: str) -> bool:
|
||||
"""True for Hub ids such as ``org/name``; false for local paths."""
|
||||
raw = value.strip()
|
||||
if not raw or raw.startswith((".", "~", "/")) or "\\" in raw:
|
||||
return False
|
||||
parts = raw.split("/")
|
||||
return len(parts) == 2 and all(part.strip() and part.strip() not in (".", "..") for part in parts)
|
||||
|
||||
|
||||
def _videomme_repo_from_args(args, *, explicit: bool = False) -> str | None:
|
||||
"""Resolve a Hugging Face repo id for Video-MME from CLI args.
|
||||
|
||||
``--dataset-name hf`` auto-detect only recognizes the official
|
||||
``lmms-eval/Video-MME`` id so a custom Hub dataset is not silently treated
|
||||
as Video-MME. Explicit ``--dataset-name videomme`` accepts any ``org/name``
|
||||
Hub id (for ``--videomme-repo`` / ``VLLM_VIDEOMME_REPO`` overrides) and
|
||||
raises when ``--dataset-path`` is neither a local directory nor a Hub id.
|
||||
"""
|
||||
official = {p.lower() for p in VideoMMEDataset.SUPPORTED_DATASET_PATHS}
|
||||
official.add(VIDEOMME_DEFAULT_HF_REPO.lower())
|
||||
candidates: list[str] = []
|
||||
for attr in ("dataset_path", "hf_name"):
|
||||
val = getattr(args, attr, None)
|
||||
if isinstance(val, str) and val.strip():
|
||||
candidates.append(val.strip())
|
||||
for raw in candidates:
|
||||
if resolve_videomme_local_root(raw) is not None:
|
||||
continue
|
||||
if raw.lower() in official:
|
||||
return raw
|
||||
if explicit and _looks_like_hf_dataset_id(raw):
|
||||
return raw
|
||||
if explicit:
|
||||
raise ValueError(
|
||||
f"Unsupported Video-MME --dataset-path={raw!r}. Pass an existing local "
|
||||
"directory, a Hugging Face dataset id (org/name), or omit --dataset-path "
|
||||
f"to use {VIDEOMME_DEFAULT_HF_REPO}."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def get_samples(args, tokenizer):
|
||||
# Daily-Omni: explicit dataset name, or hf + matching path/hf-name
|
||||
is_daily_omni = args.dataset_name == "daily-omni" or (
|
||||
args.dataset_name == "hf" and _daily_omni_repo_from_args(args) is not None
|
||||
)
|
||||
is_videomme = args.dataset_name == "videomme" or (
|
||||
args.dataset_name == "hf" and _videomme_repo_from_args(args) is not None
|
||||
)
|
||||
is_seed_tts = args.dataset_name in (
|
||||
"seed-tts",
|
||||
"seed-tts-text",
|
||||
@@ -449,7 +526,7 @@ def get_samples(args, tokenizer):
|
||||
"openai-realtime-duplex",
|
||||
"daily-omni",
|
||||
]
|
||||
is_omni_dataset = is_daily_omni or is_seed_tts or is_omniinteract or args.dataset_name == "random-mm"
|
||||
is_omni_dataset = is_daily_omni or is_videomme or is_seed_tts or is_omniinteract or args.dataset_name == "random-mm"
|
||||
|
||||
if not is_omni_backend and not is_omni_dataset:
|
||||
# Not an omni-related request, delegate to original implementation
|
||||
@@ -625,6 +702,54 @@ def get_samples(args, tokenizer):
|
||||
)
|
||||
return input_requests
|
||||
|
||||
if is_videomme:
|
||||
if args.backend not in ["openai-chat-omni", "daily-omni"]:
|
||||
raise ValueError(
|
||||
f"Video-MME dataset requires a multimodal backend that supports video. "
|
||||
f"Got backend='{args.backend}'. Please use '--backend openai-chat-omni'"
|
||||
)
|
||||
|
||||
# Resolve the source identity here; the dataset owns loading and extraction.
|
||||
local_root = resolve_videomme_local_root(getattr(args, "dataset_path", None)) or (
|
||||
resolve_videomme_local_root(getattr(args, "hf_name", None))
|
||||
)
|
||||
source = (
|
||||
str(local_root)
|
||||
if local_root is not None
|
||||
else (_videomme_repo_from_args(args, explicit=args.dataset_name == "videomme") or VIDEOMME_DEFAULT_HF_REPO)
|
||||
)
|
||||
dataset = VideoMMEDataset(
|
||||
parquet_path=getattr(args, "videomme_parquet", None),
|
||||
dataset_path=source,
|
||||
dataset_split=getattr(args, "hf_split", None) or "test",
|
||||
dataset_subset=getattr(args, "hf_subset", None),
|
||||
random_seed=args.seed,
|
||||
video_dir=getattr(args, "videomme_video_dir", None),
|
||||
subtitle_dir=getattr(args, "videomme_subtitle_dir", None),
|
||||
pack_mode=getattr(args, "videomme_pack_mode", "minicpm-frames"),
|
||||
max_frames=getattr(args, "videomme_max_frames", None),
|
||||
duration_filter=getattr(args, "videomme_duration", "all"),
|
||||
use_subtitle=getattr(args, "videomme_use_subtitle", False),
|
||||
inline_local_video=getattr(args, "videomme_inline_local_video", False),
|
||||
trust_remote_code=getattr(args, "trust_remote_code", False),
|
||||
no_stream=getattr(args, "no_stream", False),
|
||||
disable_shuffle=getattr(args, "disable_shuffle", False),
|
||||
)
|
||||
|
||||
out_len = getattr(args, "output_len", None)
|
||||
if out_len is None:
|
||||
out_len = getattr(args, "hf_output_len", None)
|
||||
if out_len is None:
|
||||
out_len = VideoMMEDataset.DEFAULT_OUTPUT_LEN
|
||||
|
||||
return dataset.sample(
|
||||
tokenizer=tokenizer,
|
||||
num_requests=args.num_prompts,
|
||||
output_len=out_len,
|
||||
request_id_prefix=args.request_id_prefix,
|
||||
no_oversample=args.no_oversample,
|
||||
)
|
||||
|
||||
if is_seed_tts:
|
||||
if args.backend not in (
|
||||
"openai-audio-speech",
|
||||
@@ -711,7 +836,7 @@ datasets.get_samples = get_samples
|
||||
|
||||
_serve_mod = sys.modules.get("vllm.benchmarks.serve")
|
||||
if _serve_mod is not None:
|
||||
_serve_mod.get_samples = get_samples
|
||||
setattr(_serve_mod, "get_samples", get_samples)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -2637,7 +2762,9 @@ async def async_request_openai_realtime_duplex(
|
||||
output.ttft = (metric_mean(session_metrics.get("ttft_ms")) or 0.0) / 1000.0
|
||||
output.audio_ttfp = (metric_mean(session_metrics.get("ttfp_ms")) or 0.0) / 1000.0
|
||||
output.audio_rtf = metric_mean(session_metrics.get("rtf")) or 0.0
|
||||
output.audio_duration = sum(float(metric.get("audio_duration_ms") or 0.0) for metric in turn_metrics) / 1000.0
|
||||
output.audio_duration = (
|
||||
sum((_as_float(metric.get("audio_duration_ms")) for metric in turn_metrics), start=0.0) / 1000.0
|
||||
)
|
||||
output.audio_frames = int(output.audio_duration * _SEED_TTS_OUTPUT_SAMPLE_RATE_HZ)
|
||||
output.latency = request_finished_at - output.start_time
|
||||
output.tts_turn_pcm_bytes = turn_pcm_bytes
|
||||
@@ -2811,7 +2938,7 @@ async def benchmark(
|
||||
extra_body=test_extra_body,
|
||||
chat_messages=test_chat_messages,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(input_requests[0], test_input)
|
||||
_attach_omni_chat_to_request_func_input(input_requests[0], test_input)
|
||||
_attach_seed_tts_to_request_func_input(input_requests[0], test_input)
|
||||
_attach_omniinteract_to_request_func_input(input_requests[0], test_input)
|
||||
|
||||
@@ -2836,7 +2963,7 @@ async def benchmark(
|
||||
if num_warmups > 0:
|
||||
print(f"Warming up with {num_warmups} requests...")
|
||||
warmup_pbar = None if disable_tqdm else tqdm(total=num_warmups)
|
||||
warmup_semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else contextlib.nullcontext()
|
||||
warmup_semaphore = _async_limiter(max_concurrency)
|
||||
warmup_tasks = []
|
||||
|
||||
async def warmup_limited_request_func():
|
||||
@@ -2854,12 +2981,13 @@ async def benchmark(
|
||||
|
||||
print("Starting main benchmark run...")
|
||||
|
||||
lora_iter: Iterator[str] | None = None
|
||||
if lora_modules:
|
||||
lora_modules_list = list(lora_modules)
|
||||
if lora_assignment == "round-robin":
|
||||
lora_modules = iter([lora_modules_list[i % len(lora_modules_list)] for i in range(len(input_requests))])
|
||||
lora_iter = iter([lora_modules_list[i % len(lora_modules_list)] for i in range(len(input_requests))])
|
||||
else:
|
||||
lora_modules = iter([random.choice(lora_modules_list) for _ in range(len(input_requests))])
|
||||
lora_iter = iter([random.choice(lora_modules_list) for _ in range(len(input_requests))])
|
||||
|
||||
if profile:
|
||||
print("Starting profiler...")
|
||||
@@ -2877,7 +3005,7 @@ async def benchmark(
|
||||
extra_body=test_extra_body,
|
||||
chat_messages=test_chat_messages,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(input_requests[0], profile_input)
|
||||
_attach_omni_chat_to_request_func_input(input_requests[0], profile_input)
|
||||
_attach_seed_tts_to_request_func_input(input_requests[0], profile_input)
|
||||
profile_output = await request_func(request_func_input=profile_input, session=session)
|
||||
if profile_output.success:
|
||||
@@ -2898,7 +3026,7 @@ async def benchmark(
|
||||
|
||||
pbar = None if disable_tqdm else tqdm(total=len(input_requests))
|
||||
|
||||
semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else contextlib.nullcontext()
|
||||
semaphore = _async_limiter(max_concurrency)
|
||||
|
||||
async def limited_request_func(request_func_input, session, pbar):
|
||||
async with semaphore:
|
||||
@@ -2969,8 +3097,8 @@ async def benchmark(
|
||||
)
|
||||
per_request_extra_body = _merge_overrides(extra_body, request.request_overrides)
|
||||
req_model_id, req_model_name = model_id, model_name
|
||||
if lora_modules:
|
||||
req_lora_module = next(lora_modules)
|
||||
if lora_iter is not None:
|
||||
req_lora_module = next(lora_iter)
|
||||
req_model_id, req_model_name = req_lora_module, req_lora_module
|
||||
|
||||
request_func_input = RequestFuncInput(
|
||||
@@ -2988,7 +3116,7 @@ async def benchmark(
|
||||
request_id=request_id,
|
||||
chat_messages=request.chat_messages,
|
||||
)
|
||||
_attach_daily_omni_to_request_func_input(request, request_func_input)
|
||||
_attach_omni_chat_to_request_func_input(request, request_func_input)
|
||||
_attach_seed_tts_to_request_func_input(request, request_func_input)
|
||||
_attach_omniinteract_to_request_func_input(request, request_func_input)
|
||||
tasks.append(
|
||||
@@ -3007,6 +3135,8 @@ async def benchmark(
|
||||
|
||||
omniinteract_summary = _finalize_omniinteract_batch(input_requests, outputs)
|
||||
|
||||
metrics: Any
|
||||
actual_output_lens: list[int] | int
|
||||
if task_type == TaskType.GENERATION:
|
||||
metrics, actual_output_lens = calculate_metrics(
|
||||
input_requests=input_requests,
|
||||
@@ -3031,6 +3161,10 @@ async def benchmark(
|
||||
actual_output_lens = 0
|
||||
|
||||
if isinstance(metrics, MultiModalsBenchmarkMetrics):
|
||||
# ``make_dataclass`` types this class as ``type``, so isinstance()
|
||||
# narrows to ``object`` and attribute access fails. Keep the runtime
|
||||
# check and read fields through ``Any``.
|
||||
mm_metrics: Any = metrics
|
||||
|
||||
def measured_ttft(output: RequestFuncOutput) -> float | None:
|
||||
session_metrics = getattr(output, "duplex_session_metrics", None)
|
||||
@@ -3040,33 +3174,33 @@ async def benchmark(
|
||||
|
||||
result = {
|
||||
"duration": benchmark_duration,
|
||||
"completed": metrics.completed,
|
||||
"failed": metrics.failed,
|
||||
"total_input_tokens": metrics.total_input,
|
||||
"total_output_tokens": metrics.total_output,
|
||||
"request_throughput": metrics.request_throughput,
|
||||
"request_goodput": metrics.request_goodput if goodput_config_dict else None,
|
||||
"output_throughput": metrics.output_throughput,
|
||||
"total_token_throughput": metrics.total_token_throughput,
|
||||
defs.TOTAL_AUDIO_DURATION_S: getattr(metrics, defs.TOTAL_AUDIO_DURATION_S),
|
||||
defs.TOTAL_AUDIO_FRAMES: getattr(metrics, defs.TOTAL_AUDIO_FRAMES),
|
||||
defs.AUDIO_THROUGHPUT: getattr(metrics, defs.AUDIO_THROUGHPUT),
|
||||
defs.TOTAL_IMAGES: getattr(metrics, defs.TOTAL_IMAGES),
|
||||
defs.IMAGE_THROUGHPUT: getattr(metrics, defs.IMAGE_THROUGHPUT),
|
||||
defs.AVERAGE_PIXELS_PER_IMAGE: getattr(metrics, defs.AVERAGE_PIXELS_PER_IMAGE),
|
||||
defs.MEAN_DENOISE_STEP_LATENCY_MS: getattr(metrics, defs.MEAN_DENOISE_STEP_LATENCY_MS),
|
||||
defs.TOTAL_VIDEO_DURATION_S: getattr(metrics, defs.TOTAL_VIDEO_DURATION_S),
|
||||
defs.TOTAL_VIDEO_FRAMES: getattr(metrics, defs.TOTAL_VIDEO_FRAMES),
|
||||
defs.VIDEO_THROUGHPUT: getattr(metrics, defs.VIDEO_THROUGHPUT),
|
||||
defs.MEAN_VIDEO_RTF: getattr(metrics, defs.MEAN_VIDEO_RTF),
|
||||
defs.MEDIAN_VIDEO_RTF: getattr(metrics, defs.MEDIAN_VIDEO_RTF),
|
||||
defs.PERCENTILES_VIDEO_RTF: getattr(metrics, defs.PERCENTILES_VIDEO_RTF),
|
||||
defs.MEAN_VIDEO_GENERATION_MS: getattr(metrics, defs.MEAN_VIDEO_GENERATION_MS),
|
||||
defs.MEDIAN_VIDEO_GENERATION_MS: getattr(metrics, defs.MEDIAN_VIDEO_GENERATION_MS),
|
||||
defs.PERCENTILES_VIDEO_GENERATION_MS: getattr(metrics, defs.PERCENTILES_VIDEO_GENERATION_MS),
|
||||
defs.MEAN_PEAK_MEMORY_MB: getattr(metrics, defs.MEAN_PEAK_MEMORY_MB),
|
||||
defs.MEDIAN_PEAK_MEMORY_MB: getattr(metrics, defs.MEDIAN_PEAK_MEMORY_MB),
|
||||
defs.PERCENTILES_PEAK_MEMORY_MB: getattr(metrics, defs.PERCENTILES_PEAK_MEMORY_MB),
|
||||
"completed": mm_metrics.completed,
|
||||
"failed": mm_metrics.failed,
|
||||
"total_input_tokens": mm_metrics.total_input,
|
||||
"total_output_tokens": mm_metrics.total_output,
|
||||
"request_throughput": mm_metrics.request_throughput,
|
||||
"request_goodput": mm_metrics.request_goodput if goodput_config_dict else None,
|
||||
"output_throughput": mm_metrics.output_throughput,
|
||||
"total_token_throughput": mm_metrics.total_token_throughput,
|
||||
defs.TOTAL_AUDIO_DURATION_S: getattr(mm_metrics, defs.TOTAL_AUDIO_DURATION_S),
|
||||
defs.TOTAL_AUDIO_FRAMES: getattr(mm_metrics, defs.TOTAL_AUDIO_FRAMES),
|
||||
defs.AUDIO_THROUGHPUT: getattr(mm_metrics, defs.AUDIO_THROUGHPUT),
|
||||
defs.TOTAL_IMAGES: getattr(mm_metrics, defs.TOTAL_IMAGES),
|
||||
defs.IMAGE_THROUGHPUT: getattr(mm_metrics, defs.IMAGE_THROUGHPUT),
|
||||
defs.AVERAGE_PIXELS_PER_IMAGE: getattr(mm_metrics, defs.AVERAGE_PIXELS_PER_IMAGE),
|
||||
defs.MEAN_DENOISE_STEP_LATENCY_MS: getattr(mm_metrics, defs.MEAN_DENOISE_STEP_LATENCY_MS),
|
||||
defs.TOTAL_VIDEO_DURATION_S: getattr(mm_metrics, defs.TOTAL_VIDEO_DURATION_S),
|
||||
defs.TOTAL_VIDEO_FRAMES: getattr(mm_metrics, defs.TOTAL_VIDEO_FRAMES),
|
||||
defs.VIDEO_THROUGHPUT: getattr(mm_metrics, defs.VIDEO_THROUGHPUT),
|
||||
defs.MEAN_VIDEO_RTF: getattr(mm_metrics, defs.MEAN_VIDEO_RTF),
|
||||
defs.MEDIAN_VIDEO_RTF: getattr(mm_metrics, defs.MEDIAN_VIDEO_RTF),
|
||||
defs.PERCENTILES_VIDEO_RTF: getattr(mm_metrics, defs.PERCENTILES_VIDEO_RTF),
|
||||
defs.MEAN_VIDEO_GENERATION_MS: getattr(mm_metrics, defs.MEAN_VIDEO_GENERATION_MS),
|
||||
defs.MEDIAN_VIDEO_GENERATION_MS: getattr(mm_metrics, defs.MEDIAN_VIDEO_GENERATION_MS),
|
||||
defs.PERCENTILES_VIDEO_GENERATION_MS: getattr(mm_metrics, defs.PERCENTILES_VIDEO_GENERATION_MS),
|
||||
defs.MEAN_PEAK_MEMORY_MB: getattr(mm_metrics, defs.MEAN_PEAK_MEMORY_MB),
|
||||
defs.MEDIAN_PEAK_MEMORY_MB: getattr(mm_metrics, defs.MEDIAN_PEAK_MEMORY_MB),
|
||||
defs.PERCENTILES_PEAK_MEMORY_MB: getattr(mm_metrics, defs.PERCENTILES_PEAK_MEMORY_MB),
|
||||
"input_lens": [output.prompt_len for output in outputs],
|
||||
"start_times": [output.start_time for output in outputs],
|
||||
"output_lens": actual_output_lens,
|
||||
@@ -3074,10 +3208,18 @@ async def benchmark(
|
||||
"itls": [output.itl for output in outputs],
|
||||
"generated_texts": [output.generated_text for output in outputs],
|
||||
"errors": [output.error for output in outputs],
|
||||
"max_output_tokens_per_s": metrics.max_output_tokens_per_s,
|
||||
"max_concurrent_requests": metrics.max_concurrent_requests,
|
||||
"rtfx": metrics.rtfx,
|
||||
"max_output_tokens_per_s": mm_metrics.max_output_tokens_per_s,
|
||||
"max_concurrent_requests": mm_metrics.max_concurrent_requests,
|
||||
"rtfx": mm_metrics.rtfx,
|
||||
}
|
||||
for sample_count in (
|
||||
"num_ttft_samples",
|
||||
"num_tpot_samples",
|
||||
"num_itl_samples",
|
||||
"num_audio_ttfp_samples",
|
||||
"num_audio_rtf_samples",
|
||||
):
|
||||
result[sample_count] = getattr(metrics, sample_count)
|
||||
else:
|
||||
result = {
|
||||
"duration": benchmark_duration,
|
||||
@@ -3142,6 +3284,21 @@ async def benchmark(
|
||||
result.update(_daily_acc)
|
||||
print_daily_omni_accuracy_summary(_daily_acc)
|
||||
|
||||
from vllm_omni.benchmarks.data_modules.videomme_eval import (
|
||||
compute_videomme_accuracy_metrics,
|
||||
print_videomme_accuracy_summary,
|
||||
)
|
||||
|
||||
_save_vm = os.environ.get("VIDEOMME_SAVE_EVAL_ITEMS", "").lower() in (
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
)
|
||||
_vm_acc = compute_videomme_accuracy_metrics(input_requests, outputs, include_per_item=_save_vm)
|
||||
if _vm_acc is not None:
|
||||
result.update(_vm_acc)
|
||||
print_videomme_accuracy_summary(_vm_acc)
|
||||
|
||||
if _seed_tts_capture_pcm_for_wer():
|
||||
from vllm_omni.benchmarks.data_modules.seed_tts_eval import (
|
||||
compute_seed_tts_wer_metrics,
|
||||
|
||||
@@ -43,7 +43,7 @@ def _normalize_endpoint(endpoint: str | None) -> str | None:
|
||||
|
||||
|
||||
def _use_endpoint_backend_when_implicit(args: argparse.Namespace) -> None:
|
||||
explicit_keys = getattr(args, "explicit_keys", frozenset())
|
||||
explicit_keys: frozenset[str] = getattr(args, "explicit_keys", frozenset())
|
||||
if "backend" in explicit_keys:
|
||||
return
|
||||
# Upstream vLLM defaults --backend to "openai". Treat that non-explicit
|
||||
@@ -63,6 +63,8 @@ def main(args: argparse.Namespace) -> dict[str, Any]:
|
||||
os.environ["SEED_TTS_WER_SAVE_ITEMS"] = "1"
|
||||
if getattr(args, "daily_omni_save_eval_items", False):
|
||||
os.environ["DAILY_OMNI_SAVE_EVAL_ITEMS"] = "1"
|
||||
if getattr(args, "videomme_save_eval_items", False):
|
||||
os.environ["VIDEOMME_SAVE_EVAL_ITEMS"] = "1"
|
||||
request_timeout_s = getattr(args, "omni_request_timeout_s", None)
|
||||
if request_timeout_s is not None:
|
||||
set_request_timeout_s(request_timeout_s)
|
||||
|
||||
@@ -32,8 +32,8 @@ from typing import TYPE_CHECKING
|
||||
from vllm_omni.clients.duplex import DuplexClientBase, DuplexConnectionError, SessionConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.realtime_commands import RealtimeInputDefaults
|
||||
from vllm_omni.entrypoints.duplex_omni import DuplexOmni, DuplexSessionHandle
|
||||
from vllm_omni.protocol.duplex import RealtimeInputDefaults
|
||||
|
||||
__all__ = ["InlineDuplexClient"]
|
||||
|
||||
@@ -71,7 +71,7 @@ class InlineDuplexClient(DuplexClientBase):
|
||||
|
||||
def _input_defaults(self) -> RealtimeInputDefaults:
|
||||
"""Audio format / sample-rate / VAD defaults declared by this session's object."""
|
||||
from vllm_omni.engine.duplex.realtime_commands import RealtimeInputDefaults
|
||||
from vllm_omni.protocol.duplex import RealtimeInputDefaults
|
||||
|
||||
session_payload = self.session_info or self.config.to_session_payload(model=self.model)
|
||||
return RealtimeInputDefaults().with_session_payload(session_payload)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Apply declarative parallel strategies onto merged stage configs.
|
||||
|
||||
This is the *override-after-merge* seam. ``merge_pipeline_deploy`` first fuses
|
||||
@@ -198,10 +198,41 @@ def _check_devices(runtime: dict[str, Any], cfg: OmniParallelConfig, *, role: Ro
|
||||
|
||||
|
||||
def _apply_to_stage(stage: Any, cfg: OmniParallelConfig, *, role: RoleKey) -> None:
|
||||
declared = set(cfg.l1_owners.keys())
|
||||
if hasattr(stage, "parallel_config") and hasattr(stage, "runtime_config"):
|
||||
parallel = stage.parallel_config
|
||||
for kind, field_name in _ENGINE_FIELD_BY_KIND.items():
|
||||
if kind in declared:
|
||||
existing = getattr(parallel, field_name, None)
|
||||
value = getattr(cfg, field_name)
|
||||
if existing not in (None, 1, value):
|
||||
_fail(
|
||||
f"role {role!r}: strategy derives {field_name}={value} "
|
||||
f"but structured config already set {existing}"
|
||||
)
|
||||
setattr(parallel, field_name, value)
|
||||
if "ep" in declared and cfg.enable_expert_parallel:
|
||||
setattr(parallel, "enable_expert_parallel", True)
|
||||
if "stage_replica" in declared:
|
||||
existing = stage.runtime_config.num_replicas
|
||||
if existing not in (None, 1, cfg.stage_replica_size):
|
||||
_fail(
|
||||
f"role {role!r}: strategy derives "
|
||||
f"num_replicas={cfg.stage_replica_size} but structured config already set {existing}"
|
||||
)
|
||||
stage.runtime_config.num_replicas = cfg.stage_replica_size
|
||||
check_device_layout(
|
||||
stage.runtime_config.devices,
|
||||
tensor_parallel_size=cfg.tensor_parallel_size,
|
||||
data_parallel_size=cfg.data_parallel_size,
|
||||
pipeline_parallel_size=cfg.pipeline_parallel_size,
|
||||
num_replicas=int(stage.runtime_config.num_replicas or 1),
|
||||
role=role,
|
||||
)
|
||||
return
|
||||
|
||||
engine_args = stage.yaml_engine_args
|
||||
runtime = stage.yaml_runtime
|
||||
|
||||
declared = set(cfg.l1_owners.keys())
|
||||
for kind, field_name in _ENGINE_FIELD_BY_KIND.items():
|
||||
if kind in declared:
|
||||
_set_explicit(engine_args, field_name, getattr(cfg, field_name), role=role)
|
||||
@@ -209,7 +240,6 @@ def _apply_to_stage(stage: Any, cfg: OmniParallelConfig, *, role: RoleKey) -> No
|
||||
_set_explicit(engine_args, "enable_expert_parallel", True, role=role)
|
||||
if "stage_replica" in declared:
|
||||
_set_num_replicas(runtime, cfg.stage_replica_size, role=role)
|
||||
|
||||
_check_devices(runtime, cfg, role=role)
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from __future__ import annotations
|
||||
import functools
|
||||
import json
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import asdict, dataclass
|
||||
from dataclasses import asdict, dataclass, fields
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -18,13 +18,19 @@ from vllm.transformers_utils.repo_utils import get_hf_file_to_dict
|
||||
from vllm.transformers_utils.runai_utils import ObjectStorageModel, is_runai_obj_uri
|
||||
|
||||
from vllm_omni.config.endpoint_policy import EndpointRestriction
|
||||
from vllm_omni.config.omni_config import VllmOmniConfig
|
||||
from vllm_omni.config.omni_config import (
|
||||
VllmOmniConfig,
|
||||
normalize_and_validate_diffusion_engine_ingress_kwargs,
|
||||
)
|
||||
from vllm_omni.config.pipeline_registry import OMNI_PIPELINES, resolve_pipeline_config
|
||||
from vllm_omni.config.stage_config import (
|
||||
_DEPLOY_DIR,
|
||||
DeployConfig,
|
||||
PipelineConfig,
|
||||
StageConfig,
|
||||
StageDeployConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
StageType,
|
||||
build_stage_runtime_overrides,
|
||||
load_deploy_config,
|
||||
@@ -373,6 +379,7 @@ class StageConfigFactory:
|
||||
trust_remote_code: bool | None,
|
||||
cli_overrides: dict[str, Any],
|
||||
deploy_config_path: str | None,
|
||||
strategy_specs: Mapping[Any, Any] | None = None,
|
||||
) -> VllmOmniConfig | None:
|
||||
"""Build the structured Omni config for a model/deploy pair."""
|
||||
user_deploy_config = cls._load_user_deploy_config(deploy_config_path)
|
||||
@@ -387,6 +394,20 @@ class StageConfigFactory:
|
||||
if pipeline_cfg is None:
|
||||
return None
|
||||
|
||||
# Keep the typed representation's topology in lockstep with the
|
||||
# compatibility launch representation. The aligner is a real extra
|
||||
# stage, not an engine-only setting, so it must be injected before
|
||||
# either representation is built.
|
||||
if user_deploy_config is None:
|
||||
if pipeline_cfg.default_deploy_config_name is not None:
|
||||
default_deploy_path = _DEPLOY_DIR / pipeline_cfg.default_deploy_config_name
|
||||
user_deploy_config = load_deploy_config(default_deploy_path)
|
||||
deploy_config_path = str(default_deploy_path)
|
||||
else:
|
||||
user_deploy_config = DeployConfig()
|
||||
from vllm_omni.utils.forced_aligner import inject_forced_aligner_stage
|
||||
|
||||
pipeline_cfg, user_deploy_config = inject_forced_aligner_stage(pipeline_cfg, user_deploy_config, cli_overrides)
|
||||
registry_cli_overrides = with_trust_remote_code_override(
|
||||
{**cli_overrides, "model": model},
|
||||
trust_remote_code,
|
||||
@@ -396,6 +417,7 @@ class StageConfigFactory:
|
||||
user_deploy_config=user_deploy_config,
|
||||
deploy_config_path=deploy_config_path,
|
||||
cli_overrides=registry_cli_overrides,
|
||||
strategy_specs=strategy_specs,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -621,13 +643,19 @@ class StageConfigFactory:
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_default_diffusion(cls, kwargs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Build the temporary runtime ABI for a generic diffusion stage.
|
||||
|
||||
The terminal diffusion config owns engine defaults and normalization;
|
||||
this compatibility builder only adds Omni stage topology, request
|
||||
defaults, and device placement.
|
||||
"""
|
||||
def _normalize_default_diffusion(
|
||||
cls,
|
||||
kwargs: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], DiffusionParallelConfig, dict[str, Any], str]:
|
||||
"""Normalize inputs shared by typed and compatibility diffusion builders."""
|
||||
# Preserve the default builder's explicit top-level override of model
|
||||
# extras before the strict same-source alias validator runs.
|
||||
if kwargs.get("auxiliary_text_encoder") is not None:
|
||||
kwargs = dict(kwargs)
|
||||
extras = dict(kwargs.get("extras") or {})
|
||||
extras.pop("auxiliary_text_encoder", None)
|
||||
kwargs["extras"] = extras
|
||||
kwargs = normalize_and_validate_diffusion_engine_ingress_kwargs(kwargs, stage_id=0)
|
||||
raw_sampling_params = kwargs.get("default_sampling_params")
|
||||
if isinstance(raw_sampling_params, str):
|
||||
try:
|
||||
@@ -642,9 +670,15 @@ class StageConfigFactory:
|
||||
parallel_config = DiffusionParallelConfig.from_stage_overrides(kwargs)
|
||||
if kwargs.get("num_gpus") is not None:
|
||||
parallel_config.resolve_data_parallel_size(int(kwargs["num_gpus"]))
|
||||
engine_args = OmniDiffusionConfig.normalize_init_kwargs(kwargs)
|
||||
engine_args["parallel_config"] = asdict(parallel_config)
|
||||
engine_args["model_stage"] = "diffusion"
|
||||
# Ingress keeps the engine spelling; canonicalize it before filtering
|
||||
# to terminal diffusion fields. Conflicts were validated at ingress.
|
||||
quantization = kwargs.pop("quantization", None)
|
||||
if quantization is not None:
|
||||
kwargs["quantization_config"] = quantization
|
||||
diffusion_config_fields = frozenset(config_field.name for config_field in fields(OmniDiffusionConfig))
|
||||
engine_args = OmniDiffusionConfig.normalize_init_kwargs(
|
||||
{name: value for name, value in kwargs.items() if name in diffusion_config_fields}
|
||||
)
|
||||
|
||||
extras = dict(engine_args.get("extras") or {})
|
||||
for key, default in (
|
||||
@@ -665,6 +699,21 @@ class StageConfigFactory:
|
||||
final_output_type,
|
||||
model_class_name,
|
||||
)
|
||||
return engine_args, parallel_config, default_sampling_params, final_output_type
|
||||
|
||||
@classmethod
|
||||
def create_default_diffusion(cls, kwargs: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Build the temporary runtime ABI for a generic diffusion stage.
|
||||
|
||||
The terminal diffusion config owns engine defaults and normalization;
|
||||
this compatibility builder only adds Omni stage topology, request
|
||||
defaults, and device placement.
|
||||
"""
|
||||
engine_args, parallel_config, default_sampling_params, final_output_type = cls._normalize_default_diffusion(
|
||||
kwargs
|
||||
)
|
||||
engine_args["parallel_config"] = asdict(parallel_config)
|
||||
engine_args["model_stage"] = "diffusion"
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -681,6 +730,50 @@ class StageConfigFactory:
|
||||
}
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def create_typed_default_diffusion(
|
||||
cls,
|
||||
model: str,
|
||||
kwargs: dict[str, Any],
|
||||
) -> VllmOmniConfig:
|
||||
"""Build generic diffusion directly into the structured runtime config."""
|
||||
engine_overrides, parallel_config, default_sampling_params, final_output_type = (
|
||||
cls._normalize_default_diffusion(kwargs)
|
||||
)
|
||||
engine_overrides.update(asdict(parallel_config))
|
||||
model_class_name = engine_overrides.get("model_class_name")
|
||||
pipeline = PipelineConfig(
|
||||
model_type="generic_diffusion",
|
||||
model_arch=str(model_class_name or ""),
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
model_stage="diffusion",
|
||||
execution_type=StageExecutionType.DIFFUSION,
|
||||
final_output=True,
|
||||
final_output_type=final_output_type,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
# These values have already been normalized for this diffusion stage.
|
||||
# Scope them explicitly so diffusion-only fields such as engine_backend
|
||||
# and extras are not filtered by the global LLM CLI argument surface.
|
||||
stage_overrides = {
|
||||
f"stage_0_{key}": value for key, value in engine_overrides.items() if key not in {"model", "stage_id"}
|
||||
}
|
||||
stage_overrides["stage_0_devices"] = (
|
||||
kwargs.get("stage_0_devices")
|
||||
or kwargs.get("devices")
|
||||
or ",".join(str(i) for i in range(parallel_config.world_size))
|
||||
)
|
||||
# Caller defaults belong to deployment, not immutable pipeline constraints:
|
||||
# explicit request sampling parameters must still be able to override them.
|
||||
deploy = DeployConfig(stages=[StageDeployConfig(stage_id=0, default_sampling_params=default_sampling_params)])
|
||||
return VllmOmniConfig.from_pipeline_config(
|
||||
pipeline, user_deploy_config=deploy, cli_overrides={"model": model, **stage_overrides}
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _merge_cli_overrides(
|
||||
cls,
|
||||
|
||||
@@ -24,6 +24,7 @@ class OmniServingCapability(Enum):
|
||||
"""Serving capabilities that pipelines can shut down."""
|
||||
|
||||
COMPLETIONS = RouteTarget("/v1/completions", frozenset({"POST"}))
|
||||
IMAGE_EDITS = RouteTarget("/v1/images/edits", frozenset({"POST"}))
|
||||
|
||||
@property
|
||||
def path(self) -> str:
|
||||
|
||||
@@ -64,6 +64,7 @@ _PUBLIC_OMNI = (
|
||||
"SPEAKER_MAX_UPLOADED",
|
||||
"SPEAKER_SAMPLES_DIR",
|
||||
"VLLM_OMNI_ABORT_TIMEOUT",
|
||||
"VLLM_OMNI_AR_DIFFUSION_KV_GATHER",
|
||||
"VLLM_OMNI_ASYNC_OUTPUT_TIMEOUT",
|
||||
"VLLM_OMNI_EVENT_DRIVEN_ORCH",
|
||||
"VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS",
|
||||
@@ -145,13 +146,6 @@ _MODEL_PROMOTE = (
|
||||
"COSYVOICE3_ESTIMATOR_ONNX",
|
||||
"COSYVOICE3_TRT",
|
||||
"COSYVOICE3_TRT_CACHE",
|
||||
"DYNIN_CONFIG_PATH",
|
||||
"DYNIN_MAGVIT_REMOTE_CODE_LOCAL_FILES_ONLY",
|
||||
"DYNIN_MAGVIT_REMOTE_CODE_REPO_ID",
|
||||
"DYNIN_MAGVIT_REMOTE_CODE_REVISION",
|
||||
"DYNIN_REMOTE_CODE_LOCAL_FILES_ONLY",
|
||||
"DYNIN_REMOTE_CODE_REPO_ID",
|
||||
"DYNIN_REMOTE_CODE_REVISION",
|
||||
"FASTVIDEO_VSA_SM100A",
|
||||
"HIGGS_AUDIO_TOKENIZER_PATH",
|
||||
"INTERNVLA_A1_COSMOS_DECODER_PATH",
|
||||
@@ -179,7 +173,6 @@ _MODEL_PROMOTE = (
|
||||
)
|
||||
|
||||
_MODEL_REQUEST_SCOPE = (
|
||||
"DOTS_TTS_DIT_NUM_STEPS",
|
||||
"MAGI2_NEGATIVE_PROMPT",
|
||||
"STEP_AUDIO2_DEFAULT_PROMPT_WAV",
|
||||
"VLLM_GEPARD_END_FADE_MS",
|
||||
@@ -194,8 +187,6 @@ _MODEL_EXTERNAL: tuple[str, ...] = ()
|
||||
|
||||
_MODEL_INTERNALIZE = (
|
||||
"COSYVOICE3_BATCH_FLOW_DEBUG",
|
||||
"DOTS_TTS_BETA_TRACE",
|
||||
"DYNIN_S2U_VENDOR_ROOT",
|
||||
"DZ_PHASE_TIMING",
|
||||
"MAGI2_ALLOW_UNSUPPORTED_TOPOLOGY",
|
||||
"MAGI2_ROUTER_BIAS_SOURCE",
|
||||
@@ -203,6 +194,7 @@ _MODEL_INTERNALIZE = (
|
||||
"MOSS_TTS_DEBUG_STOP",
|
||||
"NEMOTRON_VOICECHAT_DEBUG_FUNCTION_TIMELINE",
|
||||
"VLLM_OMNI_BREEZE_GOLDEN_DIR",
|
||||
"VLLM_OMNI_QWEN_VISUAL_DEBUG_DIR",
|
||||
"VLLM_OMNI_QWEN3_CODE2WAV_BATCH_STATS",
|
||||
"VLLM_OMNI_QWEN3_CODE2WAV_BATCH_STATS_LOG_EVERY",
|
||||
"VLLM_OMNI_QWEN3_CODE2WAV_CUDAGRAPH_STATS",
|
||||
@@ -213,6 +205,8 @@ _MODEL_INTERNALIZE = (
|
||||
_MODEL_DEPRECATE_REMOVE = (
|
||||
"HIGGS_AUDIO_V2_TOKENIZER_PATH",
|
||||
"VLLM_OMNI_LINGBOT_ACTION_ROOT",
|
||||
"VLLM_OMNI_VAE_ENCODE_LEGACY_PREP",
|
||||
"VLLM_OMNI_VAE_LEGACY_TEMPORAL",
|
||||
"VLLM_OMNI_VOXCPM_CODE_PATH",
|
||||
"XCODEC1_PATH",
|
||||
"model_stage",
|
||||
@@ -235,6 +229,7 @@ _BENCHMARK_TRANSITIONAL = (
|
||||
"SEED_TTS_WER_EVAL",
|
||||
"SEED_TTS_WER_SAVE_AUDIO_DIR",
|
||||
"SEED_TTS_WER_SAVE_ITEMS",
|
||||
"VIDEOMME_SAVE_EVAL_ITEMS",
|
||||
"VLLM_DAILY_OMNI_MEDIA_REPO",
|
||||
"VLLM_OMNI_BENCH_AUDIO_CHANNELS",
|
||||
"VLLM_OMNI_BENCH_AUDIO_CONTINUITY_THRESHOLD_S",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from dataclasses import MISSING, field
|
||||
from typing import Any
|
||||
|
||||
@@ -124,6 +127,8 @@ class OmniModelConfig(ModelConfig):
|
||||
async_chunk: bool = False
|
||||
session_mode: str = "turn"
|
||||
retains_state_across_chunks: bool = False
|
||||
use_v2_model_runner: bool = False
|
||||
supports_native_mrv2_data_plane: bool = False
|
||||
# Stage-1 active stream slots; 0 keeps legacy chunk-level round-robin.
|
||||
active_stream_window: int = 0
|
||||
duplex_max_sessions: int = 1
|
||||
@@ -134,6 +139,7 @@ class OmniModelConfig(ModelConfig):
|
||||
# Optional dotted path of a per-stage pooling-output decoder applied
|
||||
# worker-side before IPC. Read by the AR scheduler.
|
||||
pooling_output_decoder: str | None = None
|
||||
final_output: bool = False
|
||||
hf_config_name: str | None = None
|
||||
custom_process_next_stage_input_func: str | None = None
|
||||
stage_connector_config: dict[str, Any] = field(
|
||||
|
||||
+365
-30
@@ -18,6 +18,7 @@ from inspect import Parameter, signature
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, TypeAlias, TypedDict, cast
|
||||
|
||||
import regex as re
|
||||
from pydantic import ConfigDict, Field, field_validator, model_validator
|
||||
from typing_extensions import Self
|
||||
from vllm.config import CacheConfig as VllmCacheConfig
|
||||
@@ -29,7 +30,9 @@ from vllm.config import ProfilerConfig as VllmProfilerConfig
|
||||
from vllm.config import SchedulerConfig as VllmSchedulerConfig
|
||||
from vllm.config.utils import config
|
||||
from vllm.engine.arg_utils import EngineArgs as VllmEngineArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.pooling_params import PoolingParams
|
||||
|
||||
from vllm_omni.config.stage_config import (
|
||||
_DEPLOY_DIR,
|
||||
@@ -41,18 +44,25 @@ from vllm_omni.config.stage_config import (
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
StageType,
|
||||
_apply_diffusion_parallel_runtime_overrides,
|
||||
_apply_platform_overrides,
|
||||
_get_recursively_merged_dict,
|
||||
_resolve_scheduler,
|
||||
_scheduler_path,
|
||||
_select_processor_funcs,
|
||||
build_stage_runtime_overrides,
|
||||
load_deploy_config,
|
||||
merge_pipeline_deploy,
|
||||
merge_sampling_constraints,
|
||||
normalize_pipeline_cli_overrides,
|
||||
reconcile_diffusion_attention_overrides,
|
||||
resolve_stage_async_chunk,
|
||||
validate_stage_async_chunk_edges,
|
||||
)
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_EXECUTION_TYPE_TO_STAGE_WORKER: dict[StageExecutionType, tuple[StageType, str | None]] = {
|
||||
StageExecutionType.LLM_AR: (StageType.LLM, "ar"),
|
||||
StageExecutionType.LLM_GENERATION: (StageType.LLM, "generation"),
|
||||
@@ -65,10 +75,14 @@ _NON_STAGE_ENGINE_CLI_FIELDS = frozenset(
|
||||
{
|
||||
"async_chunk",
|
||||
"disable_log_stats",
|
||||
"command",
|
||||
"headless",
|
||||
"model",
|
||||
"model_tag",
|
||||
"omni",
|
||||
"output_modalities",
|
||||
"stage_id",
|
||||
"subparser",
|
||||
"tokenizer",
|
||||
}
|
||||
)
|
||||
@@ -86,6 +100,8 @@ _LEGACY_STAGE_METADATA_EXTRA_FIELDS = frozenset(
|
||||
|
||||
_QuantizationConfigType: TypeAlias = QuantizationConfig | str | Mapping[str, Any] | None
|
||||
|
||||
_DIFFUSION_SHARED_ONLY_ENGINE_FIELDS = frozenset({"kv_cache_dtype", "seed"})
|
||||
|
||||
|
||||
class _QuantizationEngineOverrides(TypedDict, total=False):
|
||||
quantization_config: _QuantizationConfigType
|
||||
@@ -154,7 +170,10 @@ class _ModelEngineOverrides(TypedDict, total=False):
|
||||
limit_mm_per_prompt: dict[str, Any]
|
||||
interleave_mm_strings: bool
|
||||
media_io_kwargs: dict[str, Any]
|
||||
final_output: bool
|
||||
active_stream_window: int
|
||||
use_v2_model_runner: bool
|
||||
supports_native_mrv2_data_plane: bool
|
||||
enable_sleep_mode: bool
|
||||
subtalker_sampling_params: dict[str, Any]
|
||||
silence_ban_frames: int
|
||||
@@ -184,6 +203,11 @@ class _ModelEngineOverrides(TypedDict, total=False):
|
||||
enable_prompt_embeds: bool
|
||||
|
||||
|
||||
class _PoolingEngineOverrides(TypedDict, total=False):
|
||||
runner: str
|
||||
pooling_output_decoder: str
|
||||
|
||||
|
||||
class _LoadEngineOverrides(TypedDict, total=False):
|
||||
tokenizer: str
|
||||
download_dir: str
|
||||
@@ -250,6 +274,7 @@ class _ParallelEngineOverrides(_ParallelConfigEngineOverrides, total=False):
|
||||
|
||||
class _ConnectorEngineOverrides(TypedDict, total=False):
|
||||
omni_kv_config: dict[str, Any]
|
||||
kv_transfer_config: KVTransferConfig | dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -259,6 +284,7 @@ class _StageEngineValues:
|
||||
quantization: _QuantizationEngineOverrides
|
||||
model: _ModelEngineOverrides
|
||||
load: _LoadEngineOverrides
|
||||
pooling: _PoolingEngineOverrides
|
||||
cache: _CacheEngineOverrides
|
||||
scheduler: _SchedulerEngineOverrides
|
||||
connector: _ConnectorEngineOverrides
|
||||
@@ -275,10 +301,6 @@ class _DiffusionEngineOverrides:
|
||||
|
||||
_values: dict[str, Any]
|
||||
|
||||
@classmethod
|
||||
def from_engine(cls, engine: Mapping[str, Any]) -> _DiffusionEngineOverrides:
|
||||
return cls(_select_engine_overrides(engine, _DIFFUSION_STAGE_ENGINE_FIELDS))
|
||||
|
||||
def to_kwargs(self) -> dict[str, Any]:
|
||||
return {name: _copy_value(value) for name, value in self._values.items()}
|
||||
|
||||
@@ -314,6 +336,8 @@ def _first_defined(*values: Any) -> Any:
|
||||
|
||||
def _validate_async_chunk_support(pipeline: PipelineConfig, deploy: DeployConfig) -> None:
|
||||
has_inter_stage_edges = any(stage.input_sources for stage in pipeline.stages)
|
||||
if deploy.async_chunk and any(stage.engine_extras.get("kv_transfer_config") for stage in deploy.stages):
|
||||
raise ValueError("Native AR-to-DiT KV transfer requires async_chunk=False.")
|
||||
if (
|
||||
deploy.async_chunk
|
||||
and has_inter_stage_edges
|
||||
@@ -344,12 +368,32 @@ def _stage_cli_overrides(
|
||||
*,
|
||||
execution_type: StageExecutionType | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if execution_type == StageExecutionType.DIFFUSION:
|
||||
stage_override_pattern = re.compile(r"^stage_\d+_")
|
||||
stage_scoped = {
|
||||
name: _copy_value(value) for name, value in cli_overrides.items() if stage_override_pattern.match(name)
|
||||
}
|
||||
global_inputs = {name: _copy_value(value) for name, value in cli_overrides.items() if name not in stage_scoped}
|
||||
cli_overrides = {
|
||||
**normalize_and_validate_diffusion_engine_ingress_kwargs(
|
||||
global_inputs,
|
||||
stage_id=stage_id,
|
||||
),
|
||||
**stage_scoped,
|
||||
}
|
||||
runtime_overrides = build_stage_runtime_overrides(stage_id, dict(cli_overrides))
|
||||
global_stage_fields = _global_stage_cli_fields()
|
||||
owned_fields = None if execution_type is None else _STAGE_ENGINE_FIELDS_BY_EXECUTION_TYPE[execution_type]
|
||||
result: dict[str, Any] = {}
|
||||
for key, value in runtime_overrides.items():
|
||||
stage_specific = f"stage_{stage_id}_{key}" in cli_overrides
|
||||
stage_key = f"stage_{stage_id}_{key}"
|
||||
stage_specific = stage_key in cli_overrides
|
||||
if (
|
||||
execution_type == StageExecutionType.DIFFUSION
|
||||
and key in _DIFFUSION_SHARED_ONLY_ENGINE_FIELDS
|
||||
and not stage_specific
|
||||
):
|
||||
continue
|
||||
if stage_specific or (key in global_stage_fields and (owned_fields is None or key in owned_fields)):
|
||||
result[key] = _copy_value(value)
|
||||
|
||||
@@ -357,6 +401,19 @@ def _stage_cli_overrides(
|
||||
# argument. Keep global and stage-scoped CLI values off AR/generation stages.
|
||||
if execution_type is not None and execution_type is not StageExecutionType.DIFFUSION:
|
||||
result.pop("step_execution", None)
|
||||
if execution_type == StageExecutionType.DIFFUSION:
|
||||
prefix = f"stage_{stage_id}_"
|
||||
for key, value in cli_overrides.items():
|
||||
if key.startswith(prefix):
|
||||
field_name = key.removeprefix(prefix)
|
||||
if field_name in {"model", "model_arch", "stage_id"}:
|
||||
raise ValueError(f"Diffusion stage {stage_id} cannot override identity field {field_name!r}.")
|
||||
if field_name in _DIFFUSION_SHARED_ONLY_ENGINE_FIELDS:
|
||||
raise ValueError(
|
||||
f"Diffusion stage {stage_id} cannot override shared engine field {field_name!r}; "
|
||||
"it has no diffusion stage-config consumer."
|
||||
)
|
||||
result.setdefault(field_name, _copy_value(value))
|
||||
return result
|
||||
|
||||
|
||||
@@ -372,6 +429,10 @@ def _validate_global_stage_cli_ownership(
|
||||
field for stage in pipeline.stages for field in _STAGE_ENGINE_FIELDS_BY_EXECUTION_TYPE[stage.execution_type]
|
||||
}
|
||||
unowned_fields = explicit_global_fields - owned_fields
|
||||
if any(stage.execution_type == StageExecutionType.DIFFUSION for stage in pipeline.stages):
|
||||
# Mixed engine ingress accepts these shared globals, but diffusion
|
||||
# stages deliberately leave them outside their terminal config.
|
||||
unowned_fields -= _DIFFUSION_SHARED_ONLY_ENGINE_FIELDS
|
||||
if unowned_fields:
|
||||
names = ", ".join(sorted(unowned_fields))
|
||||
raise ValueError(
|
||||
@@ -435,9 +496,12 @@ class OmniStageModelConfig(_TrackExplicitConfigFields):
|
||||
# MiniCPM interleaved AV packing and media decode knobs (Daily-Omni).
|
||||
interleave_mm_strings: bool | None = None
|
||||
media_io_kwargs: dict[str, Any] | None = None
|
||||
final_output: bool = False
|
||||
active_stream_window: int = Field(default=0, ge=0)
|
||||
session_mode: str = "turn"
|
||||
duplex_max_sessions: int = Field(default=1, ge=1)
|
||||
use_v2_model_runner: bool = False
|
||||
supports_native_mrv2_data_plane: bool = False
|
||||
enable_sleep_mode: bool = False
|
||||
default_sampling_params: dict[str, Any] | None = None
|
||||
subtalker_sampling_params: dict[str, Any] | None = None
|
||||
@@ -474,6 +538,15 @@ class OmniStageModelConfig(_TrackExplicitConfigFields):
|
||||
enable_prompt_embeds: bool | None = None
|
||||
|
||||
|
||||
@config(config=ConfigDict(arbitrary_types_allowed=True))
|
||||
class OmniStagePoolingConfig:
|
||||
"""Typed inputs owned by vLLM pooling stages."""
|
||||
|
||||
runner: str | None = None
|
||||
pooling_output_decoder: str | None = None
|
||||
default_pooling_params: PoolingParams | None = None
|
||||
|
||||
|
||||
@_enforce_keyword_only_init
|
||||
@config(kw_only=True)
|
||||
class OmniStageLoadConfig(_TrackExplicitConfigFields, VllmLoadConfig):
|
||||
@@ -541,6 +614,7 @@ class OmniStageConnectorConfig:
|
||||
|
||||
async_chunk: bool = False
|
||||
omni_kv_config: dict[str, Any] | None = None
|
||||
kv_transfer_config: KVTransferConfig | None = None
|
||||
stage_connector: dict[str, Any] = field(
|
||||
default_factory=lambda: {
|
||||
"name": "SharedMemoryConnector",
|
||||
@@ -712,7 +786,7 @@ class OmniStageDiffusionParallelConfig(OmniStageParallelConfig):
|
||||
self.world_size = other_parallel_world_size
|
||||
|
||||
|
||||
@config(config=ConfigDict(arbitrary_types_allowed=True))
|
||||
@config(config=ConfigDict(arbitrary_types_allowed=True, extra="forbid"))
|
||||
class _DiffusionConfigProjection:
|
||||
"""Diffusion-specific per-stage settings.
|
||||
|
||||
@@ -815,6 +889,8 @@ class _DiffusionConfigProjection:
|
||||
enable_stage_verification: bool = True
|
||||
prompt_file_path: str | None = None
|
||||
quantization_config: _QuantizationConfigType = None
|
||||
# Internal provenance, retained across config projection and worker transport.
|
||||
quantization_config_is_auto_detected: bool = False
|
||||
extras: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
@field_validator("kv_transfer_config", mode="before")
|
||||
@@ -826,15 +902,19 @@ class _DiffusionConfigProjection:
|
||||
|
||||
@classmethod
|
||||
def from_kwargs(cls, **kwargs: Any) -> _DiffusionConfigProjection:
|
||||
from vllm_omni.diffusion.data import normalize_omni_diffusion_kwargs
|
||||
from vllm_omni.diffusion.data import (
|
||||
normalize_omni_diffusion_kwargs,
|
||||
validate_omni_diffusion_kwargs,
|
||||
)
|
||||
from vllm_omni.diffusion.offloader.config import parse_diffusion_offload_config
|
||||
|
||||
normalized_kwargs = normalize_omni_diffusion_kwargs(kwargs)
|
||||
valid_fields = frozenset(f.name for f in fields(cast(Any, cls)))
|
||||
normalized = normalize_omni_diffusion_kwargs(kwargs)
|
||||
validate_omni_diffusion_kwargs(normalized, valid_fields)
|
||||
# Validate before stage construction while retaining the raw mapping
|
||||
# needed by dataclass/config serialization across process boundaries.
|
||||
parse_diffusion_offload_config(normalized_kwargs.get("diffusion_offload_config"))
|
||||
valid_fields = {f.name for f in fields(cast(Any, cls))}
|
||||
return cls(**{k: v for k, v in normalized_kwargs.items() if k in valid_fields})
|
||||
parse_diffusion_offload_config(normalized.get("diffusion_offload_config"))
|
||||
return cls(**{name: value for name, value in normalized.items() if value is not None})
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Keep diffusion imports lazy so importing vllm_omni.config does not
|
||||
@@ -962,6 +1042,8 @@ class _DiffusionConfigProjection:
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
if self.quantization_config is None:
|
||||
self.quantization_config_is_auto_detected = True
|
||||
self.quantization_config = quant_config
|
||||
if quant_method is not None:
|
||||
self.additional_config.setdefault("auto_detected_quant_method", quant_method)
|
||||
@@ -1067,20 +1149,7 @@ _DIFFUSION_MOVED_SHARED_FIELDS = frozenset(
|
||||
|
||||
_STAGE_DEPLOY_ENGINE_FIELDS: tuple[str, ...] = tuple(_STAGE_DEPLOY_FIELDS)
|
||||
|
||||
_DIFFUSION_BACKCOMPAT_ENGINE_FIELDS = frozenset(
|
||||
{
|
||||
"diffusion_attention_backend",
|
||||
"fastvideo_vsa_topk",
|
||||
"kv_cache_dtype",
|
||||
"kv_cache_skip_layers",
|
||||
"kv_cache_skip_steps",
|
||||
"static_lora_scale",
|
||||
}
|
||||
)
|
||||
_DIFFUSION_STAGE_ENGINE_FIELDS = (_DIFFUSION_CONFIG_FIELDS | _DIFFUSION_BACKCOMPAT_ENGINE_FIELDS) - {
|
||||
"model",
|
||||
"stage_id",
|
||||
}
|
||||
_DIFFUSION_STAGE_ENGINE_FIELDS = _DIFFUSION_CONFIG_FIELDS - {"model", "stage_id"}
|
||||
|
||||
|
||||
def _upstream_engine_field_map(
|
||||
@@ -1139,6 +1208,7 @@ _MODEL_ENGINE_FIELDS = frozenset(_ModelEngineOverrides.__annotations__)
|
||||
_LOAD_ENGINE_FIELDS = frozenset(_LoadEngineOverrides.__annotations__)
|
||||
_CACHE_ENGINE_FIELDS = frozenset(_CacheEngineOverrides.__annotations__)
|
||||
_SCHEDULER_ENGINE_FIELDS = frozenset(_SchedulerEngineOverrides.__annotations__)
|
||||
_POOLING_ENGINE_FIELDS = frozenset(_PoolingEngineOverrides.__annotations__)
|
||||
_CONNECTOR_ENGINE_FIELDS = frozenset(_ConnectorEngineOverrides.__annotations__)
|
||||
_RUNTIME_ENGINE_FIELDS = frozenset(_RuntimeEngineOverrides.__annotations__)
|
||||
_DIRECT_VLLM_CONFIG_ENGINE_FIELDS = frozenset({"compilation_config", "profiler_config"})
|
||||
@@ -1169,6 +1239,7 @@ _LLM_STAGE_ENGINE_FIELDS = (
|
||||
| _LLM_CACHE_ENGINE_FIELDS
|
||||
| _LLM_SCHEDULER_ENGINE_FIELDS
|
||||
| _LLM_PARALLEL_CONFIG_ENGINE_FIELDS
|
||||
| _POOLING_ENGINE_FIELDS
|
||||
| {"parallel_config"}
|
||||
)
|
||||
_DIFFUSION_OWNED_STAGE_ENGINE_FIELDS = (
|
||||
@@ -1218,6 +1289,8 @@ def _validate_stage_engine_override_ownership(
|
||||
stage_id: int,
|
||||
execution_type: StageExecutionType,
|
||||
overrides: Mapping[str, Any],
|
||||
*,
|
||||
validate_top_level: bool = True,
|
||||
) -> None:
|
||||
try:
|
||||
owner_fields = _STAGE_ENGINE_FIELDS_BY_EXECUTION_TYPE[execution_type]
|
||||
@@ -1226,7 +1299,7 @@ def _validate_stage_engine_override_ownership(
|
||||
except KeyError as exc:
|
||||
raise ValueError(f"Unsupported stage execution type: {execution_type!r}") from exc
|
||||
|
||||
unowned_fields = set(overrides) - owner_fields
|
||||
unowned_fields = set(overrides) - owner_fields if validate_top_level else set()
|
||||
parallel_config = overrides.get("parallel_config")
|
||||
if isinstance(parallel_config, Mapping):
|
||||
# Nested values traditionally use upstream config names, while flat
|
||||
@@ -1243,6 +1316,144 @@ def _validate_stage_engine_override_ownership(
|
||||
)
|
||||
|
||||
|
||||
_DIFFUSION_STAGE_METADATA_FIELDS = frozenset(
|
||||
{
|
||||
"async_chunk",
|
||||
"custom_process_next_stage_input_func",
|
||||
"engine_output_type",
|
||||
"has_sampling_extra_args",
|
||||
"hf_config_name",
|
||||
"model_arch",
|
||||
"model_stage",
|
||||
"retains_state_across_chunks",
|
||||
"scheduler_cls",
|
||||
"stage_connector_spec",
|
||||
"worker_type",
|
||||
}
|
||||
)
|
||||
|
||||
_DIFFUSION_ENGINE_ADAPTER_METADATA_FIELDS = frozenset(
|
||||
{
|
||||
# Serialized shared model settings are consumed outside the terminal
|
||||
# diffusion config; accepting them here does not widen raw ingress.
|
||||
"duplex_max_sessions",
|
||||
"has_sampling_extra_args",
|
||||
"inline_diffusion",
|
||||
"requires_full_payload_input",
|
||||
"sampling_extra_args_keys",
|
||||
"session_mode",
|
||||
}
|
||||
)
|
||||
_DIFFUSION_DEFAULT_FACTORY_FIELDS = frozenset(
|
||||
{"default_llama_model_id", "default_sampling_params", "devices", "stage_0_devices"}
|
||||
)
|
||||
|
||||
|
||||
def _frontend_cli_fields() -> frozenset[str]:
|
||||
"""Return vLLM server fields that are consumed before stage startup."""
|
||||
from vllm.entrypoints.launchers.cli_args import FrontendArgs
|
||||
|
||||
return frozenset(config_field.name for config_field in fields(FrontendArgs))
|
||||
|
||||
|
||||
def normalize_and_validate_diffusion_engine_ingress_kwargs(
|
||||
kwargs: Mapping[str, Any],
|
||||
*,
|
||||
stage_id: int | str,
|
||||
) -> dict[str, Any]:
|
||||
"""Normalize and validate raw diffusion input without inserting defaults."""
|
||||
from vllm_omni.diffusion.data import (
|
||||
OmniDiffusionConfig,
|
||||
normalize_omni_diffusion_kwargs,
|
||||
validate_omni_diffusion_kwargs,
|
||||
)
|
||||
from vllm_omni.engine.arg_utils import orchestrator_field_names
|
||||
|
||||
mixed_kwargs = {name: _copy_value(value) for name, value in kwargs.items()}
|
||||
engine_owned = {
|
||||
name: mixed_kwargs.pop(name)
|
||||
for name in _DIFFUSION_SHARED_ONLY_ENGINE_FIELDS | {"quantization"}
|
||||
if name in mixed_kwargs
|
||||
}
|
||||
normalized = normalize_omni_diffusion_kwargs(mixed_kwargs, apply_defaults=False)
|
||||
if engine_owned.get("quantization") is not None and normalized.get("quantization_config") is not None:
|
||||
raise ValueError("Diffusion config fields 'quantization' and 'quantization_config' cannot both be provided.")
|
||||
normalized.update(engine_owned)
|
||||
|
||||
diffusion_fields = frozenset(config_field.name for config_field in fields(OmniDiffusionConfig))
|
||||
stage_consumed_fields = (
|
||||
diffusion_fields
|
||||
| _DIFFUSION_OWNED_STAGE_ENGINE_FIELDS
|
||||
| frozenset(_STAGE_DEPLOY_ENGINE_FIELDS)
|
||||
| frozenset(_PIPELINE_DEPLOY_CLI_FIELDS)
|
||||
| _DIFFUSION_STAGE_METADATA_FIELDS
|
||||
| _DIFFUSION_DEFAULT_FACTORY_FIELDS
|
||||
) - _DIFFUSION_SHARED_ONLY_ENGINE_FIELDS
|
||||
externally_consumed_fields = (
|
||||
_DIFFUSION_SHARED_ONLY_ENGINE_FIELDS
|
||||
| _NON_STAGE_ENGINE_CLI_FIELDS
|
||||
| _frontend_cli_fields()
|
||||
| orchestrator_field_names()
|
||||
# Coordination fields also live on the typed orchestrator config, not
|
||||
# all of them are present on the CLI-only OrchestratorArgs dataclass.
|
||||
| frozenset(config_field.name for config_field in fields(cast(Any, VllmOmniOrchestratorConfig)))
|
||||
)
|
||||
allowed_fields = stage_consumed_fields | externally_consumed_fields
|
||||
validate_omni_diffusion_kwargs(normalized, allowed_fields, stage_id=stage_id)
|
||||
return {name: value for name, value in normalized.items() if name in stage_consumed_fields}
|
||||
|
||||
|
||||
def extract_diffusion_stage_config_kwargs(
|
||||
kwargs: Mapping[str, Any],
|
||||
*,
|
||||
stage_id: int | str,
|
||||
include_engine_adapter_metadata: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Take the diffusion-owned payload from resolved mixed stage arguments."""
|
||||
from vllm_omni.diffusion.data import (
|
||||
OmniDiffusionConfig,
|
||||
normalize_omni_diffusion_kwargs,
|
||||
validate_omni_diffusion_kwargs,
|
||||
)
|
||||
|
||||
shared_only_fields = sorted(_DIFFUSION_SHARED_ONLY_ENGINE_FIELDS.intersection(kwargs))
|
||||
if shared_only_fields:
|
||||
field_names = ", ".join(repr(name) for name in shared_only_fields)
|
||||
raise ValueError(
|
||||
f"Diffusion stage {stage_id} cannot consume shared engine field(s) {field_names}; "
|
||||
"use diffusion-owned fields or request sampling parameters instead."
|
||||
)
|
||||
|
||||
diffusion_fields = frozenset(config_field.name for config_field in fields(OmniDiffusionConfig))
|
||||
fields_owned_elsewhere = (
|
||||
frozenset(_STAGE_DEPLOY_ENGINE_FIELDS)
|
||||
| frozenset(_PIPELINE_DEPLOY_CLI_FIELDS)
|
||||
| _DIFFUSION_OWNED_STAGE_ENGINE_FIELDS
|
||||
| _DIFFUSION_STAGE_METADATA_FIELDS
|
||||
)
|
||||
if include_engine_adapter_metadata:
|
||||
fields_owned_elsewhere |= _DIFFUSION_ENGINE_ADAPTER_METADATA_FIELDS
|
||||
|
||||
# ``quantization`` is canonical in the mixed engine namespace. Hand it to
|
||||
# the compatibility adapter without treating it as a deprecated alias.
|
||||
mixed_kwargs = {name: _copy_value(value) for name, value in kwargs.items()}
|
||||
engine_quantization = mixed_kwargs.pop("quantization", None)
|
||||
normalized = normalize_omni_diffusion_kwargs(mixed_kwargs)
|
||||
if engine_quantization is not None:
|
||||
if normalized.get("quantization_config") is not None:
|
||||
raise ValueError(
|
||||
"Diffusion config fields 'quantization' and 'quantization_config' cannot both be provided."
|
||||
)
|
||||
normalized["quantization_config"] = engine_quantization
|
||||
|
||||
validate_omni_diffusion_kwargs(
|
||||
normalized,
|
||||
diffusion_fields | fields_owned_elsewhere,
|
||||
stage_id=stage_id,
|
||||
)
|
||||
return {name: _copy_value(value) for name, value in normalized.items() if name in diffusion_fields}
|
||||
|
||||
|
||||
def _global_stage_cli_fields() -> frozenset[str]:
|
||||
# Lazy import avoids vllm_omni.config -> omni_config -> engine.arg_utils ->
|
||||
# vllm_omni.config during package-level config imports.
|
||||
@@ -1255,6 +1466,7 @@ def _global_stage_cli_fields() -> frozenset[str]:
|
||||
)
|
||||
externally_consumed = (
|
||||
_NON_STAGE_ENGINE_CLI_FIELDS
|
||||
| _frontend_cli_fields()
|
||||
| frozenset(f.name for f in fields(cast(Any, VllmOmniOrchestratorConfig)))
|
||||
| (orchestrator_field_names() - _STAGE_ENGINE_FIELDS)
|
||||
)
|
||||
@@ -1299,14 +1511,29 @@ def _stage_engine_values(
|
||||
if topology.omni_kv_config:
|
||||
engine["omni_kv_config"] = _copy_value(topology.omni_kv_config)
|
||||
if stage_cli_overrides:
|
||||
stage_cli_overrides = dict(stage_cli_overrides)
|
||||
if topology.execution_type == StageExecutionType.DIFFUSION:
|
||||
# Mirror StageConfig.to_omegaconf so both projections resolve alike.
|
||||
# CLI parallel fields move into the nested ``parallel_config`` dict,
|
||||
# otherwise the deploy YAML's nested values would win over flat CLI
|
||||
# flags when ``_build_parallel_config`` merges nested over flat.
|
||||
_apply_diffusion_parallel_runtime_overrides(engine, stage_cli_overrides)
|
||||
reconcile_diffusion_attention_overrides(engine, stage_cli_overrides)
|
||||
engine.update(_copy_value(stage_cli_overrides))
|
||||
for key, value in stage_cli_overrides.items():
|
||||
existing = engine.get(key)
|
||||
if key != "omni_kv_config" and isinstance(existing, dict) and isinstance(value, Mapping):
|
||||
engine[key] = _get_recursively_merged_dict(existing, dict(value))
|
||||
else:
|
||||
engine[key] = _copy_value(value)
|
||||
if topology.execution_type == StageExecutionType.DIFFUSION:
|
||||
diffusion_kwargs = extract_diffusion_stage_config_kwargs(engine, stage_id=topology.stage_id)
|
||||
else:
|
||||
diffusion_kwargs = {}
|
||||
_validate_stage_engine_override_ownership(
|
||||
topology.stage_id,
|
||||
topology.execution_type,
|
||||
engine,
|
||||
validate_top_level=topology.execution_type != StageExecutionType.DIFFUSION,
|
||||
)
|
||||
if topology.execution_type in {
|
||||
StageExecutionType.LLM_AR,
|
||||
@@ -1328,6 +1555,10 @@ def _stage_engine_values(
|
||||
),
|
||||
model=cast(_ModelEngineOverrides, _select_engine_overrides(engine, _MODEL_ENGINE_FIELDS)),
|
||||
load=cast(_LoadEngineOverrides, _select_engine_overrides(engine, load_engine_fields)),
|
||||
pooling=cast(
|
||||
_PoolingEngineOverrides,
|
||||
_select_engine_overrides(engine, _POOLING_ENGINE_FIELDS),
|
||||
),
|
||||
cache=cast(_CacheEngineOverrides, _select_engine_overrides(engine, cache_engine_fields)),
|
||||
scheduler=cast(
|
||||
_SchedulerEngineOverrides,
|
||||
@@ -1339,7 +1570,7 @@ def _stage_engine_values(
|
||||
),
|
||||
runtime=cast(_RuntimeEngineOverrides, _select_engine_overrides(engine, runtime_engine_fields)),
|
||||
parallel=cast(_ParallelEngineOverrides, _select_engine_overrides(engine, _PARALLEL_ENGINE_FIELDS)),
|
||||
diffusion=_DiffusionEngineOverrides.from_engine(engine),
|
||||
diffusion=_DiffusionEngineOverrides(_select_engine_overrides(diffusion_kwargs, _DIFFUSION_STAGE_ENGINE_FIELDS)),
|
||||
compilation_config=_copy_value(engine.get("compilation_config")),
|
||||
profiler_config=_copy_value(engine.get("profiler_config")),
|
||||
)
|
||||
@@ -1400,6 +1631,7 @@ class BaseVllmOmniStageConfig:
|
||||
cache_config: OmniStageCacheConfig = field(default_factory=OmniStageCacheConfig)
|
||||
scheduler_config: OmniStageSchedulerConfig = field(default_factory=OmniStageSchedulerConfig)
|
||||
connector_config: OmniStageConnectorConfig = field(default_factory=OmniStageConnectorConfig)
|
||||
pooling_config: OmniStagePoolingConfig = field(default_factory=OmniStagePoolingConfig)
|
||||
runtime_config: OmniStageRuntimeConfig = field(default_factory=OmniStageRuntimeConfig)
|
||||
parallel_config: OmniStageParallelConfig = field(default_factory=OmniStageParallelConfig)
|
||||
compilation_config: VllmCompilationConfig | None = None
|
||||
@@ -1484,6 +1716,10 @@ class BaseVllmOmniStageConfig:
|
||||
def prompt_transform_func(self) -> str | None:
|
||||
return self.stage_pipeline_config.prompt_transform_func
|
||||
|
||||
@property
|
||||
def sampling_constraints(self) -> dict[str, Any]:
|
||||
return dict(self.stage_pipeline_config.sampling_constraints)
|
||||
|
||||
@property
|
||||
def cfg_kv_collect_func(self) -> str | None:
|
||||
return self.stage_pipeline_config.cfg_kv_collect_func
|
||||
@@ -1520,7 +1756,7 @@ def _build_common_stage_config_kwargs(
|
||||
*,
|
||||
model: str | None,
|
||||
) -> tuple[dict[str, Any], str | None, str | None]:
|
||||
input_proc, next_stage_proc = _select_processor_funcs(topology, bool(deploy.async_chunk))
|
||||
input_proc, next_stage_proc = _select_processor_funcs(topology, resolve_stage_async_chunk(deploy, stage_deploy))
|
||||
quantization_config = _build_quantization_config(deploy, engine.quantization)
|
||||
parallel_config = _build_parallel_config(deploy, engine.parallel, parallel_config_cls)
|
||||
|
||||
@@ -1537,6 +1773,7 @@ def _build_common_stage_config_kwargs(
|
||||
model=model,
|
||||
),
|
||||
"load_config": _build_load_config(topology, engine.load),
|
||||
"pooling_config": _build_pooling_config(stage_deploy, engine.pooling),
|
||||
"cache_config": _build_cache_config(
|
||||
deploy,
|
||||
engine.cache,
|
||||
@@ -1734,8 +1971,14 @@ def _build_model_config(
|
||||
kwargs["dtype"] = _copy_value(deploy.dtype)
|
||||
if "active_stream_window" not in kwargs:
|
||||
kwargs["active_stream_window"] = _copy_value(deploy.active_stream_window)
|
||||
kwargs["final_output"] = topology.final_output
|
||||
if "custom_voice_dir" not in kwargs and deploy.custom_voice_dir is not None:
|
||||
kwargs["custom_voice_dir"] = _copy_value(deploy.custom_voice_dir)
|
||||
kwargs.setdefault("use_v2_model_runner", deploy.model_runner == "v2")
|
||||
kwargs.setdefault(
|
||||
"supports_native_mrv2_data_plane",
|
||||
topology.supports_native_mrv2_data_plane,
|
||||
)
|
||||
if "has_sampling_extra_args" not in kwargs:
|
||||
kwargs["has_sampling_extra_args"] = bool((default_sampling_params or {}).get("extra_args"))
|
||||
if "model_subdir" not in kwargs and topology.model_subdir is not None:
|
||||
@@ -1750,6 +1993,20 @@ def _build_model_config(
|
||||
)
|
||||
|
||||
|
||||
def _build_pooling_config(
|
||||
stage_deploy: StageDeployConfig | None,
|
||||
engine: _PoolingEngineOverrides,
|
||||
) -> OmniStagePoolingConfig:
|
||||
default_pooling_params = None
|
||||
if stage_deploy is not None and stage_deploy.default_pooling_params:
|
||||
default_pooling_params = PoolingParams(**dict(stage_deploy.default_pooling_params))
|
||||
return cast(Any, OmniStagePoolingConfig)(
|
||||
runner=_copy_value(engine.get("runner")),
|
||||
pooling_output_decoder=_copy_value(engine.get("pooling_output_decoder")),
|
||||
default_pooling_params=default_pooling_params,
|
||||
)
|
||||
|
||||
|
||||
def _build_load_config(
|
||||
topology: StagePipelineConfig,
|
||||
engine: _LoadEngineOverrides,
|
||||
@@ -1835,8 +2092,9 @@ def _build_connector_config(
|
||||
output_connectors = stage_deploy.output_connectors if stage_deploy is not None else None
|
||||
input_connectors = stage_deploy.input_connectors if stage_deploy is not None else None
|
||||
return cast(Any, OmniStageConnectorConfig)(
|
||||
async_chunk=bool(deploy.async_chunk),
|
||||
async_chunk=resolve_stage_async_chunk(deploy, stage_deploy),
|
||||
omni_kv_config=_copy_value(engine.get("omni_kv_config")),
|
||||
kv_transfer_config=_copy_value(engine.get("kv_transfer_config")),
|
||||
output_connectors=_copy_value(output_connectors) if output_connectors else None,
|
||||
input_connectors=_copy_value(input_connectors) if input_connectors else None,
|
||||
)
|
||||
@@ -1928,6 +2186,10 @@ class VllmOmniConfig:
|
||||
pipeline_config: PipelineConfig
|
||||
stage_configs: tuple[StageConfigType, ...]
|
||||
orchestrator_config: VllmOmniOrchestratorConfig = field(default_factory=VllmOmniOrchestratorConfig)
|
||||
# Keep strategy provenance separate from the effective orchestrator value:
|
||||
# an explicit CLI policy may be present even when the strategy declares no
|
||||
# stage-replica axis.
|
||||
strategy_omni_lb_policy: str | None = None
|
||||
|
||||
def stage_by_id(self, stage_id: int) -> StageConfigType:
|
||||
for stage in self.stage_configs:
|
||||
@@ -1943,6 +2205,7 @@ class VllmOmniConfig:
|
||||
user_deploy_config: DeployConfig | None = None,
|
||||
deploy_config_path: str | None = None,
|
||||
cli_overrides: dict[str, Any] | None = None,
|
||||
strategy_specs: Mapping[Any, Any] | None = None,
|
||||
) -> VllmOmniConfig:
|
||||
"""Create a structured config from a resolved pipeline and deploy YAML."""
|
||||
if cli_overrides is None:
|
||||
@@ -1966,6 +2229,63 @@ class VllmOmniConfig:
|
||||
if len(pipeline_cfg.stages) <= 1:
|
||||
deploy.async_chunk = False
|
||||
_validate_async_chunk_support(pipeline_cfg, deploy)
|
||||
validate_stage_async_chunk_edges(pipeline_cfg, deploy)
|
||||
|
||||
strategy_result = None
|
||||
if strategy_specs:
|
||||
from vllm_omni.config.composable_parallel import apply_strategy_specs
|
||||
|
||||
strategy_stages = merge_pipeline_deploy(pipeline_cfg, copy.deepcopy(deploy), {})
|
||||
strategy_result = apply_strategy_specs(strategy_stages, strategy_specs)
|
||||
strategy_overrides: dict[str, Any] = {}
|
||||
axis_fields = {
|
||||
"tp": "tensor_parallel_size",
|
||||
"dp": "data_parallel_size",
|
||||
"pp": "pipeline_parallel_size",
|
||||
}
|
||||
for stage_id, parallel in strategy_result.per_stage_config.items():
|
||||
declared = set(parallel.l1_owners)
|
||||
explicit = build_stage_runtime_overrides(stage_id, cli_overrides)
|
||||
for axis, field_name in axis_fields.items():
|
||||
if axis not in declared:
|
||||
continue
|
||||
derived = getattr(parallel, field_name)
|
||||
value = explicit.get(field_name)
|
||||
if value is None:
|
||||
value = derived
|
||||
elif value != derived:
|
||||
logger.warning(
|
||||
"[composable_parallel] stage %s: CLI %s=%s overrides the "
|
||||
"strategy-derived %s=%s. The CLI value wins; remove one to avoid ambiguity.",
|
||||
stage_id,
|
||||
field_name,
|
||||
value,
|
||||
field_name,
|
||||
derived,
|
||||
)
|
||||
strategy_overrides[f"stage_{stage_id}_{field_name}"] = value
|
||||
if "ep" in declared and parallel.enable_expert_parallel:
|
||||
strategy_overrides[f"stage_{stage_id}_enable_expert_parallel"] = bool(
|
||||
explicit.get("enable_expert_parallel", True)
|
||||
)
|
||||
if "stage_replica" in declared:
|
||||
derived = parallel.stage_replica_size
|
||||
value = explicit.get("num_replicas")
|
||||
if value is None:
|
||||
value = derived
|
||||
elif value != derived:
|
||||
logger.warning(
|
||||
"[composable_parallel] stage %s: CLI num_replicas=%s overrides the "
|
||||
"strategy-derived num_replicas=%s. The CLI value wins; remove one to avoid ambiguity.",
|
||||
stage_id,
|
||||
value,
|
||||
derived,
|
||||
)
|
||||
strategy_overrides[f"stage_{stage_id}_num_replicas"] = value
|
||||
cli_overrides = {**strategy_overrides, **cli_overrides}
|
||||
if strategy_result.omni_lb_policy is not None and cli_overrides.get("omni_lb_policy") is None:
|
||||
cli_overrides["omni_lb_policy"] = strategy_result.omni_lb_policy
|
||||
|
||||
deploy_by_id = {stage.stage_id: stage for stage in deploy.stages}
|
||||
model = cli_overrides.get("model")
|
||||
|
||||
@@ -1988,6 +2308,20 @@ class VllmOmniConfig:
|
||||
)
|
||||
for topology in pipeline_cfg.stages
|
||||
)
|
||||
if strategy_result is not None:
|
||||
from vllm_omni.config.composable_parallel import check_device_layout
|
||||
|
||||
by_id = {stage.stage_id: stage for stage in stage_configs}
|
||||
for stage_id in strategy_result.per_stage_config:
|
||||
stage = by_id[stage_id]
|
||||
check_device_layout(
|
||||
stage.runtime_config.devices,
|
||||
tensor_parallel_size=stage.parallel_config.tensor_parallel_size,
|
||||
data_parallel_size=stage.parallel_config.data_parallel_size,
|
||||
pipeline_parallel_size=stage.parallel_config.pipeline_parallel_size,
|
||||
num_replicas=stage.runtime_config.num_replicas,
|
||||
role=stage.model_stage,
|
||||
)
|
||||
|
||||
orchestrator_config = cast(Any, VllmOmniOrchestratorConfig)(
|
||||
deploy_config_path=loaded_deploy_config_path,
|
||||
@@ -1997,6 +2331,7 @@ class VllmOmniConfig:
|
||||
pipeline_config=pipeline_cfg,
|
||||
stage_configs=stage_configs,
|
||||
orchestrator_config=orchestrator_config,
|
||||
strategy_omni_lb_policy=(strategy_result.omni_lb_policy if strategy_result is not None else None),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ from vllm_omni.config.stage_config import (
|
||||
PipelineConfig,
|
||||
)
|
||||
from vllm_omni.diffusion.models.pi0_pipeline_config import PI0_PIPELINE
|
||||
from vllm_omni.diffusion.models.pi05_pipeline_config import PI05_PIPELINE
|
||||
from vllm_omni.model_executor.models.audex.pipeline import (
|
||||
AUDEX_S2S_PIPELINE,
|
||||
AUDEX_THINKER_ONLY_PIPELINE,
|
||||
@@ -51,9 +52,7 @@ from vllm_omni.model_executor.models.breeze_tts_2.pipeline import BREEZE_TTS_2_P
|
||||
from vllm_omni.model_executor.models.cosmos3.pipeline import COSMOS3_POLICY_PIPELINE
|
||||
from vllm_omni.model_executor.models.cosyvoice3.pipeline import COSYVOICE3_PIPELINE
|
||||
from vllm_omni.model_executor.models.covo_audio.pipeline import COVO_AUDIO_PIPELINE
|
||||
from vllm_omni.model_executor.models.dots_tts.pipeline import DOTS_TTS_PIPELINE
|
||||
from vllm_omni.model_executor.models.dreamzero.pipeline import DREAMZERO_PIPELINE
|
||||
from vllm_omni.model_executor.models.dynin_omni.pipeline import DYNIN_OMNI_PIPELINE
|
||||
from vllm_omni.model_executor.models.fish_speech.pipeline import FISH_SPEECH_PIPELINE
|
||||
from vllm_omni.model_executor.models.gepard.pipeline import GEPARD_PIPELINE
|
||||
from vllm_omni.model_executor.models.glm_image.pipeline import GLM_IMAGE_PIPELINE
|
||||
@@ -153,6 +152,7 @@ OMNI_PIPELINES: dict[str, PipelineConfig | PipelineResolverFunc] = {
|
||||
"lingbot_world": LINGBOT_WORLD_PIPELINE,
|
||||
"Gr00tN1d7": GR00T_N1D7_PIPELINE,
|
||||
"pi0": PI0_PIPELINE,
|
||||
"pi05": PI05_PIPELINE,
|
||||
# Cosmos3 policy checkpoints share HF metadata with the T2I/video Cosmos3
|
||||
# checkpoints (which stay on the single-stage diffusion fallback), so this
|
||||
# entry is only reachable through a deploy yaml's ``pipeline:`` key
|
||||
@@ -166,7 +166,6 @@ OMNI_PIPELINES: dict[str, PipelineConfig | PipelineResolverFunc] = {
|
||||
"hunyuan_video_15": HUNYUAN_VIDEO_15_PIPELINE,
|
||||
"wan2_2_ti2v": WAN2_2_TI2V_PIPELINE,
|
||||
"voxcpm2": VOXCPM2_PIPELINE,
|
||||
"dots_tts": DOTS_TTS_PIPELINE,
|
||||
"auk": AUK_PIPELINE,
|
||||
"cosyvoice3": COSYVOICE3_PIPELINE,
|
||||
"audex_tts": AUDEX_TTS_PIPELINE,
|
||||
@@ -200,7 +199,6 @@ OMNI_PIPELINES: dict[str, PipelineConfig | PipelineResolverFunc] = {
|
||||
"minimax_music3": MINIMAX_MUSIC3_PIPELINE,
|
||||
"higgs_audio_v2": HIGGS_AUDIO_V2_PIPELINE,
|
||||
"higgs_multimodal_qwen3": HIGGS_AUDIO_V3_PIPELINE,
|
||||
"dynin_omni": DYNIN_OMNI_PIPELINE,
|
||||
"indextts2": INDEXTTS2_PIPELINE,
|
||||
"indextts2_5": INDEXTTS25_PIPELINE,
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, fields, is_dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
@@ -14,9 +15,8 @@ from vllm_omni.config.config_factory import StageConfigFactory, with_trust_remot
|
||||
from vllm_omni.config.endpoint_policy import EndpointRestriction
|
||||
from vllm_omni.config.omni_config import VllmOmniConfig
|
||||
from vllm_omni.config.stage_config import PipelineConfig
|
||||
from vllm_omni.config.yaml_util import create_config
|
||||
from vllm_omni.diffusion.data import resolve_model_class_name
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry, resolve_native_single_file
|
||||
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -24,19 +24,10 @@ logger = init_logger(__name__)
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OmniConfigResolution:
|
||||
"""Migration envelope returned by the production config resolver.
|
||||
|
||||
``stage_configs`` intentionally carries the current OmegaConf-compatible
|
||||
runtime ABI only until stage startup consumes ``VllmOmniConfig`` directly.
|
||||
``pipeline_config`` is the effective topology after runtime stage injection,
|
||||
so both fields always describe the same set of stages.
|
||||
It is not a stable authoring or extension API; new production callers
|
||||
should resolve through :func:`resolve_omni_config` and must not construct or
|
||||
merge this compatibility shape themselves.
|
||||
"""
|
||||
"""Canonical typed result returned by the production config resolver."""
|
||||
|
||||
config_path: str | None
|
||||
stage_configs: tuple[Any, ...] # Temporary StageConfig/OmegaConf bridge.
|
||||
stage_configs: tuple[Any, ...]
|
||||
pipeline_config: PipelineConfig | None = None
|
||||
omni_lb_policy: str | None = None
|
||||
|
||||
@@ -176,27 +167,13 @@ def _load_strategy_specs(strategy_config_path: str | None) -> Mapping[Any, Any]
|
||||
|
||||
def _build_registered_resolution(
|
||||
structured_config: VllmOmniConfig,
|
||||
*,
|
||||
cli_overrides: dict[str, Any],
|
||||
strategy_config_path: str | None,
|
||||
) -> OmniConfigResolution:
|
||||
"""Build the temporary runtime view for an already-resolved pipeline."""
|
||||
# Runtime consumers have not yet moved to typed per-stage configs. Use the
|
||||
# factory-owned compatibility bridge instead of reimplementing legacy YAML
|
||||
# discovery and merging in this resolver.
|
||||
effective_deploy_path = structured_config.orchestrator_config.deploy_config_path
|
||||
legacy_resolution = StageConfigFactory._resolve_legacy_from_registry(
|
||||
structured_config.pipeline_config,
|
||||
cli_overrides,
|
||||
effective_deploy_path,
|
||||
strategy_specs=_load_strategy_specs(strategy_config_path),
|
||||
)
|
||||
|
||||
"""Return the canonical structured runtime view for a resolved pipeline."""
|
||||
return OmniConfigResolution(
|
||||
config_path=effective_deploy_path,
|
||||
stage_configs=tuple(stage.to_omegaconf() for stage in legacy_resolution.stage_configs),
|
||||
pipeline_config=legacy_resolution.pipeline_config,
|
||||
omni_lb_policy=legacy_resolution.omni_lb_policy,
|
||||
config_path=structured_config.orchestrator_config.deploy_config_path,
|
||||
stage_configs=tuple(structured_config.stage_configs),
|
||||
pipeline_config=structured_config.pipeline_config,
|
||||
omni_lb_policy=getattr(structured_config, "strategy_omni_lb_policy", None),
|
||||
)
|
||||
|
||||
|
||||
@@ -228,21 +205,26 @@ def resolve_omni_config(
|
||||
"""Resolve registry/deploy inputs through the single public entrypoint."""
|
||||
normalized_overrides = _convert_dataclasses_to_dict(dict(cli_overrides or {}))
|
||||
normalized_overrides = with_trust_remote_code_override(normalized_overrides, trust_remote_code)
|
||||
native_single_file_model = resolve_native_single_file(normalized_overrides.get("model_class_name"))
|
||||
is_native_single_file = native_single_file_model is not None and Path(model).is_file()
|
||||
if is_native_single_file:
|
||||
normalized_overrides["model_class_name"] = native_single_file_model
|
||||
registry_overrides = dict(normalized_overrides)
|
||||
_flatten_stage_overrides(registry_overrides, stage_overrides)
|
||||
|
||||
structured_config = StageConfigFactory.create_from_model(
|
||||
model,
|
||||
trust_remote_code=trust_remote_code,
|
||||
cli_overrides=registry_overrides,
|
||||
deploy_config_path=deploy_config_path,
|
||||
)
|
||||
if structured_config is not None:
|
||||
return _build_registered_resolution(
|
||||
structured_config,
|
||||
strategy_specs = _load_strategy_specs(strategy_config_path)
|
||||
structured_config = None
|
||||
# Native checkpoint files have no HF config or pipeline index to discover.
|
||||
if deploy_config_path is not None or not is_native_single_file:
|
||||
structured_config = StageConfigFactory.create_from_model(
|
||||
model,
|
||||
trust_remote_code=trust_remote_code,
|
||||
cli_overrides=registry_overrides,
|
||||
strategy_config_path=strategy_config_path,
|
||||
deploy_config_path=deploy_config_path,
|
||||
strategy_specs=strategy_specs,
|
||||
)
|
||||
if structured_config is not None:
|
||||
return _build_registered_resolution(structured_config)
|
||||
|
||||
_apply_generic_stage_overrides(normalized_overrides, stage_overrides)
|
||||
supported, model_class_name = _resolve_generic_diffusion_model_class(model, normalized_overrides)
|
||||
@@ -252,11 +234,12 @@ def resolve_omni_config(
|
||||
)
|
||||
if model_class_name is not None:
|
||||
normalized_overrides.setdefault("model_class_name", model_class_name)
|
||||
default_stages = StageConfigFactory.create_default_diffusion(normalized_overrides)
|
||||
default_config = StageConfigFactory.create_typed_default_diffusion(model, normalized_overrides)
|
||||
|
||||
return OmniConfigResolution(
|
||||
config_path=deploy_config_path,
|
||||
stage_configs=tuple(create_config(_convert_dataclasses_to_dict(default_stages))),
|
||||
stage_configs=tuple(default_config.stage_configs),
|
||||
pipeline_config=default_config.pipeline_config,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ from collections.abc import Callable, Mapping
|
||||
from dataclasses import asdict, dataclass, field, fields
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, NamedTuple
|
||||
from typing import Any, Literal, NamedTuple
|
||||
|
||||
from transformers import PretrainedConfig
|
||||
from vllm.logger import init_logger
|
||||
@@ -250,6 +250,7 @@ class StagePipelineConfig:
|
||||
# Alternates picked by ``merge_pipeline_deploy`` based on ``deploy.async_chunk``.
|
||||
async_chunk_process_next_stage_input_func: str | None = None
|
||||
sync_process_input_func: str | None = None
|
||||
supports_native_mrv2_data_plane: bool = False
|
||||
# Rewrites the Stage-0 view of a raw prompt before vLLM input processing.
|
||||
# The callable receives ``(prompt, sampling_params_list)``; downstream
|
||||
# stages continue to receive the original prompt.
|
||||
@@ -309,11 +310,11 @@ class PipelineConfig:
|
||||
diffusers_class_name: str | None = None
|
||||
diffusers_class_aliases: tuple[str, ...] = ()
|
||||
endpoint_restrictions: tuple[EndpointRestriction, ...] = ()
|
||||
# Dotted path of the model's ``DuplexModelPlugin``. A pipeline is a duplex
|
||||
# model iff this is set: ``vllm-omni serve`` then always runs it through
|
||||
# ``DuplexOmni`` (every served surface runs on a duplex session) and the engine hosts one
|
||||
# ``DuplexOrchestrator`` with the plugin loaded.
|
||||
# Dotted path of the model's ``DuplexModelPlugin``. Online serving uses
|
||||
# DuplexOmni only when the deploy configuration selects session_mode: duplex.
|
||||
duplex_plugin: str | None = None
|
||||
# Preserve legacy turn deployments when adding an optional duplex plugin.
|
||||
default_session_mode: str | None = None
|
||||
# Legacy duplex wiring of the models that are not ported to the plugin
|
||||
# framework yet (PersonaPlex, Nemotron VoiceChat). Nothing reads them: a
|
||||
# pipeline that only declares these is served turn-based. Each field goes
|
||||
@@ -390,6 +391,9 @@ class StageDeployConfig:
|
||||
num_replicas: int = 1
|
||||
env: dict[str, Any] | None = None
|
||||
|
||||
# False opts this stage out of pipeline-wide async chunking.
|
||||
async_chunk: bool | None = None
|
||||
|
||||
# Inter-stage connector wiring and request defaults.
|
||||
output_connectors: dict[str, str] | None = None
|
||||
input_connectors: dict[str, str] | None = None
|
||||
@@ -563,6 +567,7 @@ class DeployConfig:
|
||||
|
||||
async_chunk: bool = True
|
||||
session_mode: str = "turn"
|
||||
model_runner: Literal["v1", "v2"] = "v1"
|
||||
# Stage-1 active stream slots; 0 preserves legacy all-stream cycling.
|
||||
active_stream_window: int = 0
|
||||
duplex_session: DuplexSessionRuntimeConfig = field(default_factory=DuplexSessionRuntimeConfig)
|
||||
@@ -587,6 +592,7 @@ class DeployConfig:
|
||||
|
||||
_STAGE_RESERVED_KEYS = frozenset(
|
||||
{
|
||||
"async_chunk",
|
||||
"stage_id",
|
||||
"devices",
|
||||
"num_replicas",
|
||||
@@ -645,6 +651,7 @@ def _parse_stage_deploy(stage_data: dict[str, Any]) -> StageDeployConfig:
|
||||
if name in flat_args:
|
||||
kwargs[name] = flat_args.pop(name)
|
||||
|
||||
kwargs["async_chunk"] = stage_data.get("async_chunk")
|
||||
kwargs["output_connectors"] = stage_data.get("output_connectors")
|
||||
kwargs["input_connectors"] = stage_data.get("input_connectors")
|
||||
kwargs["default_sampling_params"] = stage_data.get("default_sampling_params")
|
||||
@@ -731,6 +738,16 @@ def _merge_platforms(
|
||||
return merged
|
||||
|
||||
|
||||
def _merge_connectors(
|
||||
base: dict[str, Any] | None,
|
||||
overlay: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Deep-merge named connector definitions from a deploy overlay."""
|
||||
if not base and not overlay:
|
||||
return None
|
||||
return _get_recursively_merged_dict(base or {}, overlay or {})
|
||||
|
||||
|
||||
def resolve_deploy_yaml(path: str | Path) -> dict[str, Any]:
|
||||
"""Load a deploy YAML with optional ``base_config`` inheritance."""
|
||||
raw_dict = to_dict(load_yaml_config(path))
|
||||
@@ -743,12 +760,15 @@ def resolve_deploy_yaml(path: str | Path) -> dict[str, Any]:
|
||||
base_path = Path(path).parent / base_path
|
||||
base_dict = resolve_deploy_yaml(base_path)
|
||||
|
||||
# Merge top-level scalars: overlay wins. ``stages:`` and ``platforms:``
|
||||
# are deep-merged below so an overlay can layer on top of the base.
|
||||
# Merge top-level scalars: overlay wins. Structured sections are merged
|
||||
# below so a thin overlay does not discard inherited runtime contracts.
|
||||
merged = {
|
||||
**base_dict,
|
||||
**{k: v for k, v in raw_dict.items() if k not in ("stages", "platforms")},
|
||||
**{k: v for k, v in raw_dict.items() if k not in ("connectors", "stages", "platforms")},
|
||||
}
|
||||
merged_connectors = _merge_connectors(base_dict.get("connectors"), raw_dict.get("connectors"))
|
||||
if merged_connectors is not None:
|
||||
merged["connectors"] = merged_connectors
|
||||
merged["stages"] = _merge_stage_lists(base_dict.get("stages"), raw_dict.get("stages"))
|
||||
merged_platforms = _merge_platforms(base_dict.get("platforms"), raw_dict.get("platforms"))
|
||||
if merged_platforms is not None:
|
||||
@@ -768,9 +788,14 @@ def load_deploy_config(path: str | Path) -> DeployConfig:
|
||||
|
||||
stages = [_parse_stage_deploy(s) for s in raw_dict.get("stages", [])]
|
||||
|
||||
model_runner = raw_dict.get("model_runner", "v1")
|
||||
if model_runner not in ("v1", "v2"):
|
||||
raise ValueError(f"model_runner must be one of ('v1', 'v2'), got {model_runner!r}")
|
||||
|
||||
kwargs: dict[str, Any] = {
|
||||
"async_chunk": raw_dict.get("async_chunk", True),
|
||||
"session_mode": raw_dict.get("session_mode", "turn"),
|
||||
"model_runner": model_runner,
|
||||
"active_stream_window": int(raw_dict.get("active_stream_window", 0) or 0),
|
||||
"duplex_session": DuplexSessionRuntimeConfig(**(raw_dict.get("duplex_session") or {})),
|
||||
"connectors": raw_dict.get("connectors", None),
|
||||
@@ -823,15 +848,25 @@ def _apply_platform_overrides(
|
||||
deploy: DeployConfig,
|
||||
platform: str | None = None,
|
||||
) -> DeployConfig:
|
||||
"""Merge platform-specific stage overrides into deploy config."""
|
||||
"""Merge platform-specific runner and stage overrides into deploy config."""
|
||||
if platform is None:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
device_name = current_omni_platform.device_name
|
||||
platform = device_name.lower() if device_name is not None else None
|
||||
platform_section = (deploy.platforms or {}).get(platform) if platform is not None else None
|
||||
if platform_section is not None and "model_runner" in platform_section:
|
||||
model_runner = platform_section["model_runner"]
|
||||
if model_runner not in ("v1", "v2"):
|
||||
raise ValueError(f"platform model_runner must be one of ('v1', 'v2'), got {model_runner!r}")
|
||||
deploy.model_runner = model_runner
|
||||
if deploy.model_runner == "v2" and platform in {"npu", "xpu"}:
|
||||
raise NotImplementedError(
|
||||
f"Model Runner V2 is not supported on {platform.upper()}: "
|
||||
"the platform worker still uses the legacy chunk-transfer data plane."
|
||||
)
|
||||
if platform is None or deploy.platforms is None:
|
||||
return deploy
|
||||
platform_section = deploy.platforms.get(platform)
|
||||
if platform_section is None:
|
||||
return deploy
|
||||
|
||||
@@ -888,6 +923,28 @@ def _resolve_execution_mode(
|
||||
return _EXECUTION_TYPE_TO_STAGE_WORKER.get(execution_type, (StageType.LLM, None))
|
||||
|
||||
|
||||
def resolve_stage_async_chunk(deploy: DeployConfig, stage: StageDeployConfig | None) -> bool:
|
||||
return bool(deploy.async_chunk and (stage is None or stage.async_chunk is not False))
|
||||
|
||||
|
||||
def validate_stage_async_chunk_edges(pipeline: PipelineConfig, deploy: DeployConfig) -> None:
|
||||
stages = {stage.stage_id: stage for stage in pipeline.stages}
|
||||
deploy_by_id = {stage.stage_id: stage for stage in deploy.stages}
|
||||
for consumer in pipeline.stages:
|
||||
for source_id in consumer.input_sources:
|
||||
producer = stages[source_id]
|
||||
if not producer.async_chunk_process_next_stage_input_func:
|
||||
continue
|
||||
producer_async = resolve_stage_async_chunk(deploy, deploy_by_id.get(source_id))
|
||||
consumer_async = resolve_stage_async_chunk(deploy, deploy_by_id.get(consumer.stage_id))
|
||||
if producer_async != consumer_async:
|
||||
raise ValueError(
|
||||
f"Pipeline {pipeline.model_type!r} has incompatible async_chunk settings on "
|
||||
f"connector edge {source_id} -> {consumer.stage_id}. "
|
||||
"Set the same async_chunk mode on both stages or disable pipeline-wide async_chunk."
|
||||
)
|
||||
|
||||
|
||||
def _select_processor_funcs(
|
||||
ps: StagePipelineConfig,
|
||||
async_chunk: bool,
|
||||
@@ -964,15 +1021,35 @@ def _build_engine_args(
|
||||
continue
|
||||
engine_args[k] = v
|
||||
engine_args.update(ds.engine_extras)
|
||||
# Materialize the resolved pipeline-wide async_chunk value into every
|
||||
# stage so explicit False overrides do not get lost downstream.
|
||||
engine_args["async_chunk"] = bool(deploy.async_chunk)
|
||||
engine_args["async_chunk"] = resolve_stage_async_chunk(deploy, ds)
|
||||
engine_args["session_mode"] = deploy.session_mode
|
||||
if deploy.session_mode == "duplex":
|
||||
# The engine admission limit is also the authoritative capacity for
|
||||
# model-owned streaming state. Propagate it to every stage instead of
|
||||
# making individual models duplicate the value in connector extras.
|
||||
engine_args["duplex_max_sessions"] = deploy.duplex_session.max_sessions
|
||||
# The runner selection is a deploy-topology decision owned by the
|
||||
# ``model_runner`` field; do not let an opaque ``engine_extras`` entry
|
||||
# silently veto or force it per stage.
|
||||
if ds is not None:
|
||||
for reserved in ("use_v2_model_runner", "supports_native_mrv2_data_plane"):
|
||||
if reserved in ds.engine_extras:
|
||||
raise ValueError(
|
||||
f"stage {ds.stage_id}: {reserved!r} must not be set via engine_extras; "
|
||||
"it is derived from the deploy-level `model_runner` field and the "
|
||||
"pipeline's `supports_native_mrv2_data_plane` declaration."
|
||||
)
|
||||
engine_args["use_v2_model_runner"] = deploy.model_runner == "v2"
|
||||
engine_args["supports_native_mrv2_data_plane"] = bool(ps.supports_native_mrv2_data_plane)
|
||||
if deploy.model_runner == "v2" and not ps.supports_native_mrv2_data_plane:
|
||||
logger.warning(
|
||||
"Stage %s (%s) selects model_runner=v2 without declaring "
|
||||
"supports_native_mrv2_data_plane. It will use the legacy transport path; "
|
||||
"MRV2 support for this pipeline has not been validated. Use model_runner=v1 "
|
||||
"unless you are validating a new MRV2 integration.",
|
||||
ps.stage_id,
|
||||
ps.model_arch or pipeline.model_arch or pipeline.model_type,
|
||||
)
|
||||
if ps.omni_kv_config:
|
||||
engine_args["omni_kv_config"] = dict(ps.omni_kv_config)
|
||||
engine_args["requires_full_payload_input"] = ps.requires_full_payload_input
|
||||
@@ -1060,11 +1137,12 @@ def merge_pipeline_deploy(
|
||||
"Either set async_chunk=False or implement an async-chunk producer on the pipeline."
|
||||
)
|
||||
|
||||
validate_stage_async_chunk_edges(pipeline, deploy)
|
||||
result: list[StageConfig] = []
|
||||
for ps in pipeline.stages:
|
||||
ds = deploy_by_id.get(ps.stage_id)
|
||||
stage_type, worker_type = _resolve_execution_mode(ps.execution_type)
|
||||
input_proc, next_stage_proc = _select_processor_funcs(ps, deploy.async_chunk)
|
||||
input_proc, next_stage_proc = _select_processor_funcs(ps, resolve_stage_async_chunk(deploy, ds))
|
||||
engine_args = _build_engine_args(ps, ds, pipeline, deploy, next_stage_proc)
|
||||
# Downstream stages may share a multimodal wrapper class without owning
|
||||
# an encoder. Do not make vLLM profile dummy multimodal inputs for them.
|
||||
@@ -1170,6 +1248,9 @@ class StageConfig:
|
||||
else:
|
||||
engine_args[key] = value
|
||||
|
||||
# Terminal-stage ownership comes from topology, not engine overrides.
|
||||
engine_args["final_output"] = self.final_output
|
||||
|
||||
# Build runtime config from YAML defaults + CLI overrides
|
||||
runtime: dict[str, Any] = dict(self.yaml_runtime)
|
||||
runtime.setdefault("process", True)
|
||||
|
||||
@@ -1,737 +0,0 @@
|
||||
"""
|
||||
Utilities for Prefix Caching in Omni models.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.worker.gpu_input_batch import InputBatch
|
||||
|
||||
from vllm_omni.utils.mm_outputs import build_mm_cpu, to_payload_element
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingAsyncWrite:
|
||||
"""One in-flight async write into the prefix cache.
|
||||
|
||||
Holds the CPU tensors that PyTorch implicitly allocated via
|
||||
``.to("cpu", non_blocking=True)`` together with a CUDA event recorded
|
||||
on the copy stream. The consumer calls ``event.synchronize()`` once
|
||||
(blocking) to guarantee the D2H has completed before reading.
|
||||
"""
|
||||
|
||||
event: "torch.cuda.Event"
|
||||
num_tokens: int
|
||||
slots_cpu: torch.Tensor
|
||||
hidden_cpu: torch.Tensor | None
|
||||
mm_cpu: dict[str, torch.Tensor] = field(default_factory=dict)
|
||||
|
||||
|
||||
class OmniTensorPrefixCache:
|
||||
"""Prefix cache for hidden states (model outputs) and model specific
|
||||
multimodal outputs.
|
||||
|
||||
This class implements prefix caching in a non-invasive way on top of
|
||||
vLLM by leveraging the same slot mappings that the vLLM scheduler uses
|
||||
for the KV Cache.
|
||||
|
||||
Conceptually, this means we are mapping vLLM's cache mapping:
|
||||
(num_blocks, block_size)
|
||||
|
||||
to 3D tensors of shape:
|
||||
(num_blocks, block_size, feature_size)
|
||||
|
||||
Note that feature_size may vary across multimodal_outputs.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_blocks: int,
|
||||
block_size: int,
|
||||
hidden_size: int,
|
||||
hs_dtype: torch.dtype,
|
||||
):
|
||||
self.num_blocks = num_blocks
|
||||
self.block_size = block_size
|
||||
self.default_hidden_size = hidden_size
|
||||
|
||||
# Initialize the hidden states cache immediately
|
||||
self.hidden_states_cache = self._get_cache_tensor(dtype=hs_dtype)
|
||||
|
||||
# Defer initialization of the mm_outputs_cache until we
|
||||
# actually see mm output tensors dependent on num tokens.
|
||||
self.mm_outputs_cache = {}
|
||||
self.mm_cache_keys = set()
|
||||
self._new_req_cache_hit_ids: set[str] = set()
|
||||
self._deferred_mm_outputs: dict[str, dict[str, list[tuple[int, torch.Tensor]]]] = {}
|
||||
|
||||
# Async write pipeline state:
|
||||
# - one dedicated copy stream
|
||||
# - one in-flight pending write at a time (the producer is exactly
|
||||
# one forward step ahead of the consumer)
|
||||
# - schedule_async_write() consumes the *previous* pending write
|
||||
# (via event.synchronize() + scatter) before kicking off the new
|
||||
# D2H. By the time we hit synchronize, the previous step's GPU
|
||||
# work has been done for ~one forward step, so the sync is
|
||||
# near-zero wall-clock.
|
||||
self._async_initialized: bool = False
|
||||
self._async_copy_stream: torch.cuda.Stream | None = None
|
||||
self._pending_write: _PendingAsyncWrite | None = None
|
||||
|
||||
def maybe_init_missing_mm_cache_keys(self, multimodal_outputs: dict, seq_len: int):
|
||||
"""Given multimodal outputs from executing the model, dynamically
|
||||
determine which multimodal outputs are tensors depending on sequence
|
||||
length and should be cached, and initialize the cache tensors
|
||||
accordingly.
|
||||
|
||||
NOTE: This is done to avoid the need for explicit specification of
|
||||
cache keys for every model/stage and aligns with the current way
|
||||
that we slice the multimodal outputs based on the first dimension.
|
||||
|
||||
This will usually be called by the first forward pass, i.e.,
|
||||
determined by the warmup.
|
||||
"""
|
||||
for key, val in multimodal_outputs.items():
|
||||
# Only cache per-token feature tensors: 2D+ with first dim == seq_len.
|
||||
# A 1D tensor of shape (seq_len,) is a broadcast scalar (per-request
|
||||
# metadata such as ref_code_len / codec_streaming), not per-token data;
|
||||
# caching it by slot causes a shape mismatch when a later request has a
|
||||
# different scheduled seq length.
|
||||
if (
|
||||
isinstance(val, torch.Tensor)
|
||||
and val.ndim >= 2
|
||||
and val.shape[0] == seq_len
|
||||
and key not in self.mm_cache_keys
|
||||
):
|
||||
feat_dim = val.shape[-1]
|
||||
self.mm_outputs_cache[key] = self._get_cache_tensor(
|
||||
dtype=val.dtype,
|
||||
hidden_size=feat_dim,
|
||||
)
|
||||
self.mm_cache_keys.add(key)
|
||||
new_tensor_shape = self.mm_outputs_cache[key].shape
|
||||
logger.info("Initializing multimodal output cache of size %s for key: %s", list(new_tensor_shape), key)
|
||||
|
||||
def _get_cache_tensor(self, dtype: torch.dtype, hidden_size: int | None = None) -> torch.Tensor:
|
||||
"""Allocate a CPU cache tensor for a specific key.
|
||||
|
||||
When CUDA is available the tensor is pinned: this is what lets the
|
||||
async-write pipeline ride the GPU->CPU copy on the dedicated copy
|
||||
stream as a true async ``cudaMemcpyAsync`` and lets the post-copy CPU
|
||||
scatter avoid page-resolution stalls. On CPU-only builds pinning is
|
||||
unsupported (``torch.zeros(pin_memory=True)`` raises), and the async
|
||||
pipeline is disabled anyway (``schedule_async_write`` early-returns
|
||||
when ``torch.cuda.is_available()`` is False), so we fall back to a
|
||||
plain pageable allocation with no behavioral change.
|
||||
"""
|
||||
actual_hidden_size = hidden_size if hidden_size is not None else self.default_hidden_size
|
||||
return torch.zeros(
|
||||
(self.num_blocks, self.block_size, actual_hidden_size),
|
||||
dtype=dtype,
|
||||
device="cpu",
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
|
||||
# =====================================================================
|
||||
# Async write pipeline:
|
||||
# schedule_async_write : called per forward step, enqueues a
|
||||
# non-blocking D2H + records a CUDA event
|
||||
# drain_ready_async_writes : non-blocking poll, applies any writes
|
||||
# whose D2H has completed
|
||||
# =====================================================================
|
||||
|
||||
def _ensure_async_resources(self) -> None:
|
||||
"""Lazily allocate the dedicated copy stream.
|
||||
|
||||
The per-step CPU staging tensors are allocated by PyTorch on demand
|
||||
inside ``.to("cpu", non_blocking=True)``, which gives them
|
||||
implicitly-pinned memory and lets PyTorch's allocator amortize /
|
||||
reuse them.
|
||||
"""
|
||||
if self._async_initialized:
|
||||
return
|
||||
if not torch.cuda.is_available():
|
||||
return
|
||||
self._async_copy_stream = torch.cuda.Stream()
|
||||
self._async_initialized = True
|
||||
logger.info("Omni prefix cache async-write copy stream initialized.")
|
||||
|
||||
def schedule_async_write(
|
||||
self,
|
||||
hidden_states_gpu: torch.Tensor | None,
|
||||
multimodal_outputs_gpu: dict[str, torch.Tensor] | None,
|
||||
slot_mapping_gpu: torch.Tensor,
|
||||
num_tokens_unpadded: int,
|
||||
num_tokens_padded: int,
|
||||
skip_mm_cache_keys: set[str] | None = None,
|
||||
) -> None:
|
||||
"""Kick off a non-blocking GPU->CPU copy for this step's writes.
|
||||
|
||||
1. **Consume the previous step's write** (if any): block on its
|
||||
event and scatter the CPU tensors into the cache. By the time we
|
||||
reach this point, the previous step's GPU work has been done for
|
||||
~one forward step, so the synchronize is near-zero wall-clock.
|
||||
2. **Schedule THIS step's D2H** on a dedicated copy stream using
|
||||
``.to("cpu", non_blocking=True)``. PyTorch allocates the pinned
|
||||
destination implicitly.
|
||||
3. **Record an event** and stash everything for the next step's
|
||||
consume.
|
||||
|
||||
Holding exactly one in-flight write at a time keeps the design
|
||||
simple: no ring, no event-polling, no driver-mutex pressure from
|
||||
repeated event.query() calls.
|
||||
"""
|
||||
if not torch.cuda.is_available():
|
||||
return
|
||||
|
||||
self._ensure_async_resources()
|
||||
if not self._async_initialized:
|
||||
return
|
||||
|
||||
# Decide which mm keys we'll cache. Init the dest cache tensors
|
||||
# before scheduling the copies so the apply step has somewhere
|
||||
# to scatter into.
|
||||
skip = skip_mm_cache_keys or set()
|
||||
cacheable_mm_keys: list[str] = []
|
||||
if multimodal_outputs_gpu:
|
||||
self.maybe_init_missing_mm_cache_keys(multimodal_outputs_gpu, seq_len=num_tokens_padded)
|
||||
for k in self.mm_cache_keys:
|
||||
if k in skip:
|
||||
continue
|
||||
v = multimodal_outputs_gpu.get(k)
|
||||
if not isinstance(v, torch.Tensor) or v.ndim < 2:
|
||||
continue
|
||||
if v.shape[0] < num_tokens_unpadded:
|
||||
continue
|
||||
cacheable_mm_keys.append(k)
|
||||
|
||||
# Step 1: consume the previous step's write FIRST. The previous
|
||||
# step's event was recorded ~one forward step ago, so
|
||||
# synchronize() is effectively a no-op cost-wise; the scatter
|
||||
# into pinned CPU caches is also fast.
|
||||
self._consume_pending_write()
|
||||
|
||||
if hidden_states_gpu is None and not cacheable_mm_keys:
|
||||
return # nothing to schedule this step
|
||||
|
||||
# Step 2: schedule the D2H on the copy stream. PyTorch implicitly
|
||||
# allocates pinned host destinations for the ``.to("cpu",
|
||||
# non_blocking=True)`` results.
|
||||
copy_stream = self._async_copy_stream
|
||||
default_stream = torch.cuda.current_stream()
|
||||
with torch.cuda.stream(copy_stream):
|
||||
copy_stream.wait_stream(default_stream)
|
||||
|
||||
# slot_mapping: copy as-is; the int64 cast required by
|
||||
# ``index_copy_`` is deferred to ``_consume_pending_write``
|
||||
# so we avoid launching an extra GPU kernel here that would
|
||||
# contend the driver mutex with the compute stream.
|
||||
slots_cpu = slot_mapping_gpu[:num_tokens_unpadded].to("cpu", non_blocking=True)
|
||||
hidden_cpu: torch.Tensor | None = None
|
||||
if hidden_states_gpu is not None:
|
||||
hidden_cpu = hidden_states_gpu[:num_tokens_unpadded].to("cpu", non_blocking=True)
|
||||
mm_cpu: dict[str, torch.Tensor] = {}
|
||||
for k in cacheable_mm_keys:
|
||||
mm_cpu[k] = multimodal_outputs_gpu[k][:num_tokens_unpadded].to("cpu", non_blocking=True)
|
||||
|
||||
event = torch.cuda.Event()
|
||||
event.record()
|
||||
|
||||
# Step 3: stash for next step's consume.
|
||||
self._pending_write = _PendingAsyncWrite(
|
||||
event=event,
|
||||
num_tokens=num_tokens_unpadded,
|
||||
slots_cpu=slots_cpu,
|
||||
hidden_cpu=hidden_cpu,
|
||||
mm_cpu=mm_cpu,
|
||||
)
|
||||
|
||||
def drain_ready_async_writes(self) -> int:
|
||||
"""Consume one in-flight write if it has finished (non-blocking).
|
||||
|
||||
Exposed so the model runner can drain at the top of
|
||||
``execute_model`` regardless of whether a new write will be
|
||||
scheduled this step.
|
||||
"""
|
||||
if self._pending_write is None:
|
||||
return 0
|
||||
if not self._pending_write.event.query():
|
||||
return 0
|
||||
self._consume_pending_write()
|
||||
return 1
|
||||
|
||||
def _consume_pending_write(self) -> None:
|
||||
"""Synchronize on the pending event and scatter the CPU tensors
|
||||
into the destination caches. Drops state on completion.
|
||||
"""
|
||||
entry = self._pending_write
|
||||
if entry is None:
|
||||
return
|
||||
self._pending_write = None
|
||||
entry.event.synchronize()
|
||||
n = entry.num_tokens
|
||||
if n <= 0:
|
||||
return
|
||||
|
||||
slots = entry.slots_cpu
|
||||
if slots.dtype != torch.int64:
|
||||
slots = slots.to(torch.int64)
|
||||
|
||||
# NOTE: ``index_copy_(0, idx, src)`` is the row-scatter primitive in
|
||||
# PyTorch. It's semantically identical to ``flat[idx] = src`` but
|
||||
# dispatches to a much simpler CPU implementation (single dim,
|
||||
# no broadcasting, no accumulate), which on pinned memory at large
|
||||
# row sizes is observed to be much faster than the generic
|
||||
# ``aten::index_put_`` path used by advanced-indexing assignment.
|
||||
if entry.hidden_cpu is not None:
|
||||
flat = self.hidden_states_cache.view(-1, self.hidden_states_cache.shape[-1])
|
||||
flat.index_copy_(0, slots, entry.hidden_cpu)
|
||||
for k, src_cpu in entry.mm_cpu.items():
|
||||
mm_cache = self.mm_outputs_cache.get(k)
|
||||
if mm_cache is None:
|
||||
continue
|
||||
flat = mm_cache.view(-1, mm_cache.shape[-1])
|
||||
flat.index_copy_(0, slots, src_cpu)
|
||||
|
||||
def add_prefix_cached_new_req_id(self, req_id: str):
|
||||
"""Adds a new request ID to the set of prefix cache hits on the batch."""
|
||||
self._new_req_cache_hit_ids.add(req_id)
|
||||
|
||||
def reset_prefix_cached_new_req_ids(self):
|
||||
"""Clears the cache hit IDs to prepare for a new engine step."""
|
||||
self._new_req_cache_hit_ids.clear()
|
||||
|
||||
def has_prefix_cached_new_req_ids(self) -> bool:
|
||||
"""Return True when this step contains a newly scheduled prefix hit."""
|
||||
return bool(self._new_req_cache_hit_ids)
|
||||
|
||||
@staticmethod
|
||||
def _coerce_to_cpu_tensor(maybe_gpu_tensor: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert GPU tensors -> contiguous CPU tensors if needed."""
|
||||
return maybe_gpu_tensor.detach().cpu().contiguous()
|
||||
|
||||
@staticmethod
|
||||
def _resolve_hidden_states_cpu(
|
||||
hidden_states: torch.Tensor,
|
||||
num_tokens: int,
|
||||
hidden_states_cpu: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
if hidden_states_cpu is None:
|
||||
return OmniTensorPrefixCache._coerce_to_cpu_tensor(hidden_states[:num_tokens])
|
||||
if hidden_states_cpu.device.type != "cpu":
|
||||
raise RuntimeError("hidden_states_cpu must be a CPU tensor.")
|
||||
if not hidden_states_cpu.is_contiguous():
|
||||
raise RuntimeError("hidden_states_cpu must be contiguous.")
|
||||
if hidden_states_cpu.dtype != hidden_states.dtype:
|
||||
raise RuntimeError(
|
||||
"hidden_states_cpu has an incompatible dtype: "
|
||||
f"got {hidden_states_cpu.dtype}, expected {hidden_states.dtype}."
|
||||
)
|
||||
if hidden_states_cpu.shape[1:] != hidden_states.shape[1:]:
|
||||
raise RuntimeError(
|
||||
"hidden_states_cpu has an incompatible feature shape: "
|
||||
f"got {tuple(hidden_states_cpu.shape[1:])}, expected {tuple(hidden_states.shape[1:])}."
|
||||
)
|
||||
if hidden_states_cpu.shape[0] < num_tokens:
|
||||
raise RuntimeError(
|
||||
"hidden_states_cpu does not cover the requested hidden states "
|
||||
f"slice: got {hidden_states_cpu.shape[0]} tokens, need {num_tokens}."
|
||||
)
|
||||
return hidden_states_cpu[:num_tokens]
|
||||
|
||||
def update_omni_tensor_prefix_cache(
|
||||
self,
|
||||
hidden_states: torch.Tensor | None,
|
||||
multimodal_outputs: dict[str, torch.Tensor] | None,
|
||||
num_tokens_unpadded: int,
|
||||
slot_mapping: torch.Tensor,
|
||||
num_tokens_padded: int | None = None,
|
||||
skip_mm_cache_keys: set[str] | None = None,
|
||||
hidden_states_cpu: torch.Tensor | None = None,
|
||||
):
|
||||
"""Updates the hidden cache state for the provided hidden states and multimodal outputs.
|
||||
|
||||
Args:
|
||||
hidden_states: Hidden states tensor to cache (if any)
|
||||
multimodal_outputs: Multimodal dict whose tensors may be cached
|
||||
num_tokens_unpadded: Number of tokens without padding
|
||||
slot_mapping: Slot mapping for the input sequence
|
||||
num_tokens_padded: Total number of tokens including padding
|
||||
skip_mm_cache_keys: Multimodal keys whose CPU cache writes are deferred
|
||||
hidden_states_cpu: Optional pre-staged CPU view of hidden_states.
|
||||
When provided, it must be contiguous, live on CPU, match the
|
||||
feature shape of hidden_states, and cover num_tokens_unpadded.
|
||||
"""
|
||||
unpadded_slot_mapping = slot_mapping[:num_tokens_unpadded]
|
||||
if num_tokens_padded is None:
|
||||
num_tokens_padded = num_tokens_unpadded
|
||||
skip_mm_cache_keys = skip_mm_cache_keys or set()
|
||||
|
||||
if hidden_states is not None:
|
||||
# Slice to unpadded portion before caching
|
||||
hidden_states = OmniTensorPrefixCache._resolve_hidden_states_cpu(
|
||||
hidden_states,
|
||||
num_tokens_unpadded,
|
||||
hidden_states_cpu,
|
||||
)
|
||||
# View the cache as 2D so that we can treat our slots as row indices.
|
||||
# ``index_copy_`` is the row-scatter primitive — it's semantically
|
||||
# ``cache[idx] = src`` but dispatches to a faster CPU path than the
|
||||
# generic advanced-indexing assignment (which goes through
|
||||
# ``aten::index_put_`` and is dominated by per-row dispatch
|
||||
# overhead on large feature widths).
|
||||
flat_cache = self.hidden_states_cache.view(-1, self.hidden_states_cache.shape[-1])
|
||||
slot_idx = unpadded_slot_mapping
|
||||
if slot_idx.dtype != torch.int64:
|
||||
slot_idx = slot_idx.to(torch.int64)
|
||||
flat_cache.index_copy_(0, slot_idx, hidden_states)
|
||||
logger.debug("Writing to hidden states for %s tokens", num_tokens_unpadded)
|
||||
|
||||
# Do the same for the stage's cached multimodal outputs
|
||||
if multimodal_outputs is not None:
|
||||
# If we haven't initialized the keys already, do it now
|
||||
# We check against the padded token count since we haven't sliced yet
|
||||
self.maybe_init_missing_mm_cache_keys(
|
||||
multimodal_outputs,
|
||||
seq_len=num_tokens_padded,
|
||||
)
|
||||
|
||||
for mm_out_key, mm_cache in self.mm_outputs_cache.items():
|
||||
if mm_out_key in multimodal_outputs:
|
||||
if mm_out_key in skip_mm_cache_keys:
|
||||
continue
|
||||
# Slice to unpadded portion before caching
|
||||
mm_state = multimodal_outputs[mm_out_key][:num_tokens_unpadded]
|
||||
mm_state = OmniTensorPrefixCache._coerce_to_cpu_tensor(mm_state)
|
||||
flat_cache = mm_cache.view(-1, mm_cache.shape[-1])
|
||||
slot_idx = unpadded_slot_mapping
|
||||
if slot_idx.dtype != torch.int64:
|
||||
slot_idx = slot_idx.to(torch.int64)
|
||||
flat_cache.index_copy_(0, slot_idx, mm_state)
|
||||
logger.debug("Writing to mm output cache for %s tokens", num_tokens_unpadded)
|
||||
|
||||
def stage_deferred_mm_outputs(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
multimodal_outputs: dict[str, torch.Tensor] | None,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
deferred_mm_cache_keys: set[str],
|
||||
) -> None:
|
||||
"""Keep GPU multimodal chunks until a request finishes.
|
||||
|
||||
The normal prefix-cache write path copies every cached multimodal tensor
|
||||
to CPU on every step. For model outputs that are only needed by future
|
||||
full-block prefix hits, we can keep detached GPU chunks and materialize
|
||||
the CPU cache once when the request completes.
|
||||
"""
|
||||
if not multimodal_outputs or not deferred_mm_cache_keys:
|
||||
return
|
||||
|
||||
for mm_key in deferred_mm_cache_keys:
|
||||
mm_state = multimodal_outputs.get(mm_key)
|
||||
if not isinstance(mm_state, torch.Tensor) or mm_state.ndim < 2:
|
||||
continue
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
sched = int(num_scheduled_tokens.get(req_id, 0))
|
||||
if sched <= 0:
|
||||
continue
|
||||
start = int(query_start_loc[req_idx])
|
||||
end = start + sched
|
||||
if start >= int(mm_state.shape[0]):
|
||||
continue
|
||||
end = min(end, int(mm_state.shape[0]))
|
||||
if end <= start:
|
||||
continue
|
||||
|
||||
computed_end = int(input_batch.num_computed_tokens_cpu[req_idx])
|
||||
token_start = max(0, computed_end - sched)
|
||||
chunk = mm_state[start:end].detach()
|
||||
self._deferred_mm_outputs.setdefault(req_id, {}).setdefault(mm_key, []).append((token_start, chunk))
|
||||
|
||||
def commit_deferred_mm_outputs(
|
||||
self,
|
||||
finished_req_ids: set[str] | list[str],
|
||||
input_batch: InputBatch,
|
||||
) -> None:
|
||||
"""Write deferred multimodal chunks into the CPU prefix cache.
|
||||
|
||||
This must run before finished requests are removed from ``input_batch``,
|
||||
because the block table is needed to map logical token positions to KV
|
||||
cache slots.
|
||||
"""
|
||||
if not finished_req_ids or not self._deferred_mm_outputs:
|
||||
return
|
||||
|
||||
for req_id in tuple(finished_req_ids):
|
||||
per_key = self._deferred_mm_outputs.pop(req_id, None)
|
||||
if not per_key:
|
||||
continue
|
||||
req_idx = input_batch.req_id_to_index.get(req_id)
|
||||
if req_idx is None:
|
||||
continue
|
||||
for mm_key, chunks in per_key.items():
|
||||
self._commit_deferred_mm_key(req_idx, input_batch, mm_key, chunks)
|
||||
|
||||
def discard_deferred_mm_outputs(self, req_id: str) -> None:
|
||||
"""Drop deferred chunks for requests that leave without a cache commit."""
|
||||
self._deferred_mm_outputs.pop(req_id, None)
|
||||
|
||||
def _commit_deferred_mm_key(
|
||||
self,
|
||||
req_idx: int,
|
||||
input_batch: InputBatch,
|
||||
mm_key: str,
|
||||
chunks: list[tuple[int, torch.Tensor]],
|
||||
) -> None:
|
||||
if not chunks:
|
||||
return
|
||||
|
||||
chunks = sorted(chunks, key=lambda item: item[0])
|
||||
first_start = chunks[0][0]
|
||||
expected_start = first_start
|
||||
tensors: list[torch.Tensor] = []
|
||||
for token_start, tensor in chunks:
|
||||
if tensor.numel() == 0:
|
||||
continue
|
||||
if token_start != expected_start:
|
||||
if tensors:
|
||||
self._write_deferred_mm_tensor(req_idx, input_batch, mm_key, tensors, first_start)
|
||||
first_start = token_start
|
||||
expected_start = token_start
|
||||
tensors = []
|
||||
tensors.append(tensor)
|
||||
expected_start += int(tensor.shape[0])
|
||||
|
||||
if tensors:
|
||||
self._write_deferred_mm_tensor(req_idx, input_batch, mm_key, tensors, first_start)
|
||||
|
||||
def _write_deferred_mm_tensor(
|
||||
self,
|
||||
req_idx: int,
|
||||
input_batch: InputBatch,
|
||||
mm_key: str,
|
||||
tensors: list[torch.Tensor],
|
||||
token_start: int,
|
||||
) -> None:
|
||||
mm_state = tensors[0] if len(tensors) == 1 else torch.cat(tensors, dim=0)
|
||||
if mm_state.ndim < 2 or mm_state.shape[0] == 0:
|
||||
return
|
||||
|
||||
if mm_key not in self.mm_cache_keys:
|
||||
self.mm_outputs_cache[mm_key] = self._get_cache_tensor(
|
||||
dtype=mm_state.dtype,
|
||||
hidden_size=int(mm_state.shape[-1]),
|
||||
)
|
||||
self.mm_cache_keys.add(mm_key)
|
||||
logger.info(
|
||||
"Initializing deferred multimodal output cache of size %s for key: %s",
|
||||
list(self.mm_outputs_cache[mm_key].shape),
|
||||
mm_key,
|
||||
)
|
||||
|
||||
slots = self._get_slot_ids_for_token_range(
|
||||
req_idx=req_idx,
|
||||
input_batch=input_batch,
|
||||
token_start=token_start,
|
||||
num_tokens=int(mm_state.shape[0]),
|
||||
)
|
||||
if slots.numel() == 0:
|
||||
return
|
||||
|
||||
mm_state_cpu = OmniTensorPrefixCache._coerce_to_cpu_tensor(mm_state[: slots.numel()])
|
||||
mm_cache = self.mm_outputs_cache[mm_key]
|
||||
flat_cache = mm_cache.view(-1, mm_cache.shape[-1])
|
||||
if slots.dtype != torch.int64:
|
||||
slots = slots.to(torch.int64)
|
||||
flat_cache.index_copy_(0, slots, mm_state_cpu)
|
||||
|
||||
def _get_slot_ids_for_token_range(
|
||||
self,
|
||||
req_idx: int,
|
||||
input_batch: InputBatch,
|
||||
token_start: int,
|
||||
num_tokens: int,
|
||||
) -> torch.Tensor:
|
||||
if num_tokens <= 0:
|
||||
return torch.empty((0,), dtype=torch.long)
|
||||
|
||||
block_table = input_batch.block_table[0].block_table.cpu
|
||||
token_positions = torch.arange(token_start, token_start + num_tokens, dtype=torch.long)
|
||||
block_offsets = token_positions // self.block_size
|
||||
max_blocks = int(block_table.shape[1])
|
||||
valid = block_offsets < max_blocks
|
||||
if not bool(valid.all()):
|
||||
token_positions = token_positions[valid]
|
||||
block_offsets = block_offsets[valid]
|
||||
if token_positions.numel() == 0:
|
||||
return torch.empty((0,), dtype=torch.long)
|
||||
|
||||
block_ids = block_table[req_idx, block_offsets].to(torch.long)
|
||||
return block_ids * self.block_size + (token_positions % self.block_size)
|
||||
|
||||
def _coerce_to_payload_dict(
|
||||
self,
|
||||
element: object,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
) -> dict[str, object]:
|
||||
"""Build the multimodal passthrough data per request for
|
||||
the object under consideration. This mirrors the no-prefix-cache
|
||||
path: a tensor whose first dimension matches the total scheduled
|
||||
token count is sliced per request, so 1D (seq_len,) metadata that
|
||||
is intentionally not cached (e.g. ref_code_len, codec_streaming)
|
||||
is still split per request instead of leaking the whole batch.
|
||||
"""
|
||||
total_scheduled_tokens = sum(int(num_scheduled_tokens[r]) for r in input_batch.req_ids)
|
||||
elem_dict = {}
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
start = query_start_loc[req_idx]
|
||||
end = start + num_scheduled_tokens[req_id]
|
||||
elem_dict[req_id] = to_payload_element(
|
||||
element,
|
||||
req_idx,
|
||||
start=start,
|
||||
end=end,
|
||||
pass_lists_through=True,
|
||||
seq_len=total_scheduled_tokens,
|
||||
)
|
||||
return elem_dict
|
||||
|
||||
def get_merged_multimodal_states(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
multimodal_outputs: dict | None,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
):
|
||||
"""Get the merged multimodal states if hidden state prefix caching is enabled."""
|
||||
combined_multimodal_outputs = {}
|
||||
# Talkers that produce multimodal outputs only at decode (e.g. Higgs
|
||||
# Audio v3's audio codes) have ``multimodal_outputs is None`` at the
|
||||
# initial prefill step. Treat it as an empty mapping so the merger
|
||||
# short-circuits cleanly and the cache merge still runs once codes
|
||||
# start arriving.
|
||||
mm_outputs = multimodal_outputs if multimodal_outputs is not None else {}
|
||||
# First get the prefix cached tensors that are present in the mm data
|
||||
for mm_key in self.mm_cache_keys:
|
||||
if mm_key in mm_outputs:
|
||||
combined_multimodal_outputs[mm_key] = self._get_merged_tensors(
|
||||
query_start_loc=query_start_loc,
|
||||
input_batch=input_batch,
|
||||
cache=self.mm_outputs_cache[mm_key],
|
||||
hidden_states=mm_outputs[mm_key],
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
)
|
||||
|
||||
# Then, get everything else (passthrough data); first, convert to CPU
|
||||
# tensors similarly to the non prefix cached path, and then populate
|
||||
# the subdicts mapping request IDs -> payload objects
|
||||
passthrough_keys = set(mm_outputs.keys()) - self.mm_cache_keys
|
||||
passthrough_mm_data = {k: v for k, v in mm_outputs.items() if k in passthrough_keys}
|
||||
mm_cpu = build_mm_cpu(multimodal_outputs=passthrough_mm_data)
|
||||
|
||||
for mm_key, mm_val in mm_cpu.items():
|
||||
combined_multimodal_outputs[mm_key] = self._coerce_to_payload_dict(
|
||||
element=mm_val,
|
||||
query_start_loc=query_start_loc,
|
||||
input_batch=input_batch,
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
)
|
||||
return combined_multimodal_outputs
|
||||
|
||||
def get_merged_hidden_states(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
hidden_states: torch.Tensor,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
hidden_states_cpu: torch.Tensor | None = None,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Get merged hidden states, optionally reusing pre-staged CPU states.
|
||||
|
||||
When provided, hidden_states_cpu follows the same contract as
|
||||
update_omni_tensor_prefix_cache: CPU, contiguous, same dtype and feature
|
||||
shape as hidden_states, and covering every scheduled-token span derived
|
||||
from query_start_loc and num_scheduled_tokens.
|
||||
"""
|
||||
return self._get_merged_tensors(
|
||||
query_start_loc=query_start_loc,
|
||||
input_batch=input_batch,
|
||||
hidden_states=hidden_states,
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
staged_cpu_tensor=hidden_states_cpu,
|
||||
cache=self.hidden_states_cache,
|
||||
)
|
||||
|
||||
def _get_merged_tensors(
|
||||
self,
|
||||
query_start_loc: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
cache: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
num_scheduled_tokens: dict[str, int],
|
||||
staged_cpu_tensor: torch.Tensor | None = None,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""When hidden state caching is enabled, takes the input hidden_states,
|
||||
which only correspond to the scheduled tokens, and returns a mapping
|
||||
from request IDs to their full hidden states. This is accomplished by
|
||||
looking up the block IDs & scheduled token counts to split the
|
||||
hidden_states. staged_cpu_tensor can supply the already materialized CPU
|
||||
scheduled-token view; None preserves the legacy per-call CPU conversion.
|
||||
"""
|
||||
# We do not support hybrid caches at the moment.
|
||||
if len(input_batch.block_table.block_tables) > 1:
|
||||
logger.warning_once(
|
||||
"Omni prefix caching is enabled, but the batch block table appears to"
|
||||
" have multiple kv groups; only the first group will be used!"
|
||||
)
|
||||
|
||||
combined_hidden_states = {}
|
||||
required_tokens = 0
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
start = query_start_loc[req_idx]
|
||||
end = start + num_scheduled_tokens[req_id]
|
||||
required_tokens = max(required_tokens, int(end))
|
||||
hidden_states = OmniTensorPrefixCache._resolve_hidden_states_cpu(
|
||||
hidden_states,
|
||||
required_tokens,
|
||||
staged_cpu_tensor,
|
||||
)
|
||||
for req_id in input_batch.req_ids:
|
||||
req_idx = input_batch.req_id_to_index[req_id]
|
||||
|
||||
if req_id in self._new_req_cache_hit_ids:
|
||||
block_ids = self._get_cached_block_ids(req_idx, input_batch)
|
||||
cached_hs = cache[block_ids].reshape(-1, cache.shape[-1])
|
||||
|
||||
# Slice the hidden states corresponding to this request;
|
||||
# we do this by using the query start
|
||||
start = query_start_loc[req_idx]
|
||||
new_hs = hidden_states[start : start + num_scheduled_tokens[req_id]]
|
||||
combined_hidden_states[req_id] = torch.cat([cached_hs, new_hs], dim=0)
|
||||
else:
|
||||
# cache miss for this request, pass through normally
|
||||
start = query_start_loc[req_idx]
|
||||
new_hs = hidden_states[start : start + num_scheduled_tokens[req_id]]
|
||||
combined_hidden_states[req_id] = new_hs
|
||||
|
||||
return combined_hidden_states
|
||||
|
||||
def _get_cached_block_ids(self, req_idx: int, input_batch: InputBatch) -> torch.Tensor:
|
||||
"""Given an input batch and request index in the batch (not ID), get the
|
||||
block IDs corresponding to the cache hit.
|
||||
"""
|
||||
num_computed = input_batch.num_computed_tokens_cpu[req_idx]
|
||||
# NOTE: vLLM only caches full blocks
|
||||
num_cached_blocks = num_computed // self.block_size
|
||||
# Get the block IDs attached to this cache hit and reindex into
|
||||
# the flattened cached hidden states (i.e., 1 row per token).
|
||||
return input_batch.block_table[0].block_table.cpu[req_idx, :num_cached_blocks]
|
||||
@@ -0,0 +1,58 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Omni prefix cache.
|
||||
|
||||
Structure mirrors vllm/v1/core.
|
||||
|
||||
Import invariant: this package must not import ``vllm`` at module
|
||||
scope (``TYPE_CHECKING`` and function-body imports are fine).
|
||||
``tests/core/test_prefix_cache.py`` loads these modules without a
|
||||
vllm install; a top-level ``from vllm...`` turns that suite red.
|
||||
|
||||
That is also why these files use ``logging.getLogger`` instead of
|
||||
the repo-wide ``init_logger`` — ``init_logger`` comes from
|
||||
``vllm.logger``. The deviation is required, not an oversight.
|
||||
|
||||
``_merge_uncached_mm`` is the exception at *call* time: it lazily
|
||||
imports ``vllm_omni.utils.mm_outputs``, which pulls in vllm. Import
|
||||
of this package still succeeds without vllm; materialize of leftover
|
||||
mm does not.
|
||||
"""
|
||||
|
||||
from vllm_omni.core.prefix_cache.block_pool import PrefixBlockPool
|
||||
from vllm_omni.core.prefix_cache.controller import OmniPrefixCacheController
|
||||
from vllm_omni.core.prefix_cache.group_view import (
|
||||
FullAttentionGroupView,
|
||||
check_prefix_cache_kv_groups,
|
||||
check_prefix_cache_kv_transfer,
|
||||
get_prefix_cache_group_view,
|
||||
stage_prefix_cache_config,
|
||||
)
|
||||
from vllm_omni.core.prefix_cache.interface import (
|
||||
HIDDEN_KEY,
|
||||
ModelCachePolicy,
|
||||
OmniPrefixCacheStagingTimeoutError,
|
||||
OmniPrefixCacheUnmatchError,
|
||||
PrefixCacheConfig,
|
||||
StageCacheOutputs,
|
||||
WriteSchedule,
|
||||
)
|
||||
from vllm_omni.core.prefix_cache.manager import OmniPrefixCacheManager
|
||||
|
||||
__all__ = [
|
||||
"HIDDEN_KEY",
|
||||
"FullAttentionGroupView",
|
||||
"ModelCachePolicy",
|
||||
"OmniPrefixCacheController",
|
||||
"OmniPrefixCacheManager",
|
||||
"OmniPrefixCacheStagingTimeoutError",
|
||||
"OmniPrefixCacheUnmatchError",
|
||||
"StageCacheOutputs",
|
||||
"PrefixBlockPool",
|
||||
"PrefixCacheConfig",
|
||||
"WriteSchedule",
|
||||
"check_prefix_cache_kv_groups",
|
||||
"check_prefix_cache_kv_transfer",
|
||||
"get_prefix_cache_group_view",
|
||||
"stage_prefix_cache_config",
|
||||
]
|
||||
@@ -0,0 +1,84 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Pinned CPU block mirror (mirrors vLLM BlockPool)."""
|
||||
|
||||
import logging
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.core.prefix_cache.interface import PrefixCacheConfig, TensorName
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PrefixBlockPool:
|
||||
"""Durable CPU mirror of vLLM KV slots, one tensor per name.
|
||||
|
||||
Storage is ``(num_blocks, block_size, feat)`` per key, viewed flat as
|
||||
``(num_slots, feat)`` so vLLM slot ids index rows directly. Write
|
||||
access is single-writer (the controller committer thread); readers
|
||||
take row views.
|
||||
|
||||
``_caches`` is not an unbounded store and has no LRU. Dict keys are
|
||||
tensor names (``__hidden_states__`` plus mm whose first dim is tokens),
|
||||
opened once by ``ensure_key`` and never dropped — a model emits a
|
||||
handful of those names, not a per-request set. Each value is a
|
||||
fixed tensor sized to the same ``num_blocks`` as the upstream KV
|
||||
pool. Rows *are* those kv slots: when vLLM recycles a block, the
|
||||
next pool write overwrites that row. Slot reuse is the eviction.
|
||||
"""
|
||||
|
||||
def __init__(self, config: PrefixCacheConfig):
|
||||
self._config = config
|
||||
self._caches: dict[TensorName, torch.Tensor] = {}
|
||||
|
||||
def _alloc(self, dtype: torch.dtype, feat: int) -> torch.Tensor:
|
||||
return torch.zeros(
|
||||
(self._config.num_blocks, self._config.block_size, feat),
|
||||
dtype=dtype,
|
||||
device="cpu",
|
||||
# Pinning lets device→host overlap compute; unsupported on
|
||||
# CPU-only builds where that overlap is off anyway.
|
||||
pin_memory=torch.cuda.is_available(),
|
||||
)
|
||||
|
||||
def alloc_key(self, key: str, dtype: torch.dtype, feat: int) -> torch.Tensor | None:
|
||||
"""Allocate storage for a new ``key`` without publishing it (None if
|
||||
already open). Pinned allocation is slow; run this unlocked and
|
||||
hand the tensor to ``install_key`` under the manager's state lock."""
|
||||
if key in self._caches:
|
||||
return None
|
||||
return self._alloc(dtype, feat)
|
||||
|
||||
def install_key(self, key: str, storage: torch.Tensor) -> None:
|
||||
if key in self._caches:
|
||||
return
|
||||
self._caches[key] = storage
|
||||
logger.info("prefix_cache: initialized mirror %s for key %s", list(storage.shape), key)
|
||||
|
||||
def ensure_key(self, key: str, dtype: torch.dtype, feat: int) -> None:
|
||||
storage = self.alloc_key(key, dtype, feat)
|
||||
if storage is not None:
|
||||
self.install_key(key, storage)
|
||||
|
||||
def has_key(self, key: str) -> bool:
|
||||
return key in self._caches
|
||||
|
||||
def keys(self) -> set[TensorName]:
|
||||
return set(self._caches.keys())
|
||||
|
||||
def _flat(self, key: str) -> torch.Tensor:
|
||||
cache = self._caches[key]
|
||||
return cache.view(-1, cache.shape[-1])
|
||||
|
||||
def rows(self, key: str, slots: torch.Tensor) -> torch.Tensor:
|
||||
"""Gather rows for non-contiguous slots (returns a copy)."""
|
||||
return self._flat(key).index_select(0, slots)
|
||||
|
||||
def write(self, key: str, slots: torch.Tensor, src_cpu: torch.Tensor) -> None:
|
||||
"""Write rows into the pool; caller (committer thread) is the single writer."""
|
||||
if slots.dtype != torch.int64:
|
||||
slots = slots.to(torch.int64)
|
||||
# index_copy_ dispatches to a faster single-dim CPU path than
|
||||
# advanced-indexing assignment (aten::index_put_).
|
||||
self._flat(key).index_copy_(0, slots, src_cpu)
|
||||
@@ -0,0 +1,976 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Runs WriteTasks and the step device→host staging pool.
|
||||
|
||||
The manager owns request/slot identity and when to submit. This class
|
||||
owns the staging pool, the GPU-byte budget, the copy queues, and the
|
||||
single committer that writes into the CPU block pool.
|
||||
|
||||
Two device→host paths — the step path does not write `chunk.host` in
|
||||
the committer:
|
||||
|
||||
JOIN_NEXT_STEP save already launched a whole-step device→host into
|
||||
a staging slot and set `chunk.host` as views.
|
||||
Committer waits that `step_d2h_event`, then writes
|
||||
the pool.
|
||||
JOIN_ON_FINISH committer copies the device clone → owned host
|
||||
tensors, then writes the pool.
|
||||
|
||||
Async: high-priority then low-priority queues, then pool write.
|
||||
Eager: submit() does wait+write inline (CPU tests / no CUDA).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum, auto
|
||||
from typing import Literal, NamedTuple
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.core.prefix_cache.block_pool import PrefixBlockPool
|
||||
from vllm_omni.core.prefix_cache.interface import (
|
||||
OmniPrefixCacheStagingTimeoutError,
|
||||
OmniPrefixCacheUnmatchError,
|
||||
PrefixCacheConfig,
|
||||
ReqId,
|
||||
TensorName,
|
||||
Tid,
|
||||
WriteSchedule,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StagingBufferHolder(NamedTuple):
|
||||
"""One owner of a staging-buffer slot. The slot is free when none remain.
|
||||
|
||||
Not a buffer state — concurrent owners share the same slot:
|
||||
- for_step: claimed at save, released when materialize/discard consumes the ctx
|
||||
- for_task: bound before WriteTask submit, released when that task completes
|
||||
"""
|
||||
|
||||
kind: Literal["step", "task"]
|
||||
owner_id: int
|
||||
|
||||
@classmethod
|
||||
def for_step(cls, step_id: int) -> StagingBufferHolder:
|
||||
return cls("step", step_id)
|
||||
|
||||
@classmethod
|
||||
def for_task(cls, tid: int) -> StagingBufferHolder:
|
||||
return cls("task", tid)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _BudgetTicket:
|
||||
"""GPU-byte-budget charge for one device clone shared by several writes.
|
||||
|
||||
Charged once at ``reserve()``; freed when the last pinned tid releases.
|
||||
Immediate: the whole-step clone, pinned by that step's JOIN_NEXT_STEP
|
||||
tasks. Deferred: the shared deferred clone, pinned by every task a
|
||||
chunk of it was appended to. Does not store tensors.
|
||||
"""
|
||||
|
||||
nbytes: int
|
||||
tids: set[Tid] = field(default_factory=set)
|
||||
_freed: bool = False
|
||||
|
||||
def release(self, tid: Tid) -> int:
|
||||
"""Drop `tid`; return the bytes to uncharge (nbytes once, when the
|
||||
last holder leaves; 0 otherwise). Idempotent per tid."""
|
||||
self.tids.discard(tid)
|
||||
if self.tids or self._freed:
|
||||
return 0
|
||||
self._freed = True
|
||||
return self.nbytes
|
||||
|
||||
|
||||
@dataclass
|
||||
class _WriteChunk:
|
||||
"""One save's slots + tensors appended onto a WriteTask.
|
||||
|
||||
Controller identity is the parent ``tid``, not a request. Deferred
|
||||
writes grow by appending one chunk per save.
|
||||
"""
|
||||
|
||||
slots_cpu: torch.Tensor # int64 flat row ids, in token order
|
||||
tensors: dict[TensorName, torch.Tensor] # freeze (device or eager CPU)
|
||||
host: dict[TensorName, torch.Tensor] = field(default_factory=dict) # host view of rows [0:n)
|
||||
# GPU-byte charge of the clone these tensors view; shared across the
|
||||
# chunks cut from one save. None for chunks with no device clone.
|
||||
budget: _BudgetTicket | None = None
|
||||
|
||||
|
||||
class TaskState(Enum):
|
||||
"""WriteTask lifecycle: a strict chain, plus FAILED from any non-terminal.
|
||||
|
||||
PENDING -> QUEUED -> COPYING -> HOST_READY -> WRITTEN
|
||||
|
||||
PENDING registered, not on a copy queue (deferred: waiting for
|
||||
finish / budget pressure)
|
||||
QUEUED on a copy queue
|
||||
COPYING one thread owns the copy stage (staging: waits the step
|
||||
device→host; deferred: copies the device clone)
|
||||
HOST_READY host rows ready (`host_ready` set); device clone dropped
|
||||
WRITTEN in the CPU pool (`done` set)
|
||||
FAILED committer could not finish (`host_ready` + `done` set;
|
||||
manager raises from every later entry)
|
||||
|
||||
Moves only through `WriteTask.transition`; skipping a step is illegal.
|
||||
"""
|
||||
|
||||
PENDING = auto()
|
||||
QUEUED = auto()
|
||||
COPYING = auto()
|
||||
HOST_READY = auto()
|
||||
WRITTEN = auto()
|
||||
FAILED = auto()
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return self in (TaskState.WRITTEN, TaskState.FAILED)
|
||||
|
||||
|
||||
# The one legal forward move from each non-terminal state.
|
||||
_CHAIN: dict[TaskState, TaskState] = {
|
||||
TaskState.PENDING: TaskState.QUEUED,
|
||||
TaskState.QUEUED: TaskState.COPYING,
|
||||
TaskState.COPYING: TaskState.HOST_READY,
|
||||
TaskState.HOST_READY: TaskState.WRITTEN,
|
||||
}
|
||||
_NOT_YET_COPYING = frozenset({TaskState.PENDING, TaskState.QUEUED})
|
||||
|
||||
|
||||
def _is_legal_move(frm: TaskState, to: TaskState) -> bool:
|
||||
return (to is TaskState.FAILED and not frm.is_terminal) or _CHAIN.get(frm) is to
|
||||
|
||||
|
||||
@dataclass
|
||||
class WriteTask:
|
||||
"""One write of (slot, key) rows for a single request.
|
||||
|
||||
Identity: `tid` is the handle in the manager's (slot, key) tables.
|
||||
`req_id` + `write_n` mark whose write this is and the nth time that
|
||||
request opened a write. One write may cover several keys.
|
||||
|
||||
`state` is the single source of truth for where the write is (see
|
||||
`TaskState`). `host_ready` / `done` are wait primitives set by the
|
||||
transitions into HOST_READY / WRITTEN / FAILED, never directly.
|
||||
|
||||
How HOST_READY is reached:
|
||||
- JOIN_NEXT_STEP: `chunk.host` is a staging view set at save; the
|
||||
copy stage only waits `step_d2h_event`.
|
||||
- JOIN_ON_FINISH: the copy stage copies device→host into `chunk.host`.
|
||||
|
||||
`JOIN_NEXT_STEP` is queued at submit. `JOIN_ON_FINISH` stays
|
||||
PENDING until finish or GPU-byte-budget pressure escalates it;
|
||||
budget flush takes the unfinished task with the oldest `enqueued_time`.
|
||||
|
||||
Concurrent readers/writers:
|
||||
- Staging readers (materialize clone, committer pool write) all wait
|
||||
the same `step_d2h_event` before touching the view.
|
||||
- A later task taking the same (slot, key) records those rows in
|
||||
`reassigned`; the old pool write skips them.
|
||||
- `append_chunk` is refused once the copy stage is claimed; the caller
|
||||
opens a fresh task rather than mutating a closed one.
|
||||
- `lock` covers `state` / `reassigned` / `append_chunk` / host↔freeze /
|
||||
`slot_to_row`. `scatter_rows` snapshots `reassigned`.
|
||||
"""
|
||||
|
||||
tid: Tid
|
||||
req_id: ReqId
|
||||
write_n: int # 1-based: nth write opened by this request
|
||||
schedule: WriteSchedule
|
||||
chunks: list[_WriteChunk]
|
||||
# On-device clone finished on the compute stream. Copy/read streams
|
||||
# must wait this before touching `chunks[].tensors`, or they can read
|
||||
# the next CUDA-graph static-buffer overwrite.
|
||||
freeze_event: torch.cuda.Event | None = None
|
||||
state: TaskState = TaskState.PENDING
|
||||
# Slots this write no longer owns (a newer write took them over).
|
||||
reassigned: dict[TensorName, torch.Tensor] = field(default_factory=dict)
|
||||
# Set on entering HOST_READY (or FAILED): this write's host rows are ready.
|
||||
host_ready: threading.Event = field(default_factory=threading.Event)
|
||||
# Set on entering WRITTEN (or FAILED): the CPU-pool write is over.
|
||||
done: threading.Event = field(default_factory=threading.Event)
|
||||
# Guards state / reassigned / append / host↔freeze.
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
# time.monotonic() at submit; GPU-byte flush picks the oldest of these.
|
||||
enqueued_time: float = field(default_factory=time.monotonic)
|
||||
# Immediate path: this write's view into the shared step staging page.
|
||||
staging_slot: int | None = None
|
||||
# Immediate path: this step's CUDA device→host event (shared). None if deferred.
|
||||
step_d2h_event: torch.cuda.Event | None = None
|
||||
# slot -> (which chunk, row in that tensor). Built on demand
|
||||
# when a write has more than one `_WriteChunk`; pool write uses slot, the tensor uses row.
|
||||
_slot_to_row: dict[int, tuple[int, int]] | None = None
|
||||
|
||||
def add_reassigned(self, key: str, slots: torch.Tensor) -> None:
|
||||
with self.lock:
|
||||
prev = self.reassigned.get(key)
|
||||
self.reassigned[key] = slots.clone() if prev is None else torch.cat([prev, slots])
|
||||
|
||||
def reassigned_intersects(self, chunk: _WriteChunk) -> bool:
|
||||
"""True if this write already lost ownership of any (key, slot) the
|
||||
chunk would add; the caller opens a fresh WriteTask instead."""
|
||||
with self.lock:
|
||||
if not self.reassigned:
|
||||
return False
|
||||
for key in chunk.tensors:
|
||||
taken = self.reassigned.get(key)
|
||||
if taken is not None and taken.numel() and bool(torch.isin(chunk.slots_cpu, taken).any()):
|
||||
return True
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------ lifecycle
|
||||
|
||||
def transition(self, to: TaskState) -> None:
|
||||
"""Move to `to`; raises unless it is the next chain step or FAILED."""
|
||||
with self.lock:
|
||||
self._transition_locked(to)
|
||||
|
||||
def try_transition(self, to: TaskState) -> bool:
|
||||
"""Move to `to` if legal from the current state. True if moved."""
|
||||
with self.lock:
|
||||
if not _is_legal_move(self.state, to):
|
||||
return False
|
||||
self._transition_locked(to)
|
||||
return True
|
||||
|
||||
def _transition_locked(self, to: TaskState, wake: bool = True) -> None:
|
||||
if not _is_legal_move(self.state, to):
|
||||
raise OmniPrefixCacheUnmatchError(f"task {self.tid}: illegal transition {self.state.name} -> {to.name}")
|
||||
self.state = to
|
||||
if not wake:
|
||||
return
|
||||
if to is TaskState.HOST_READY:
|
||||
self.host_ready.set()
|
||||
elif to is TaskState.WRITTEN:
|
||||
self.done.set()
|
||||
elif to is TaskState.FAILED:
|
||||
self.host_ready.set()
|
||||
self.done.set()
|
||||
|
||||
def claim_copy(self) -> bool:
|
||||
"""QUEUED -> COPYING. Only one thread may run the copy stage; True if this caller won."""
|
||||
return self.try_transition(TaskState.COPYING)
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return self.state.is_terminal
|
||||
|
||||
def append_chunk(self, chunk: _WriteChunk, freeze_event: torch.cuda.Event | None = None) -> TaskState | None:
|
||||
"""Grow this write with one save's rows. Returns None when appended,
|
||||
else the state that closed the task (COPYING or later).
|
||||
|
||||
`freeze_event` is stored in the same snapshot: events on one compute
|
||||
stream are ordered, so the newest also covers every earlier clone.
|
||||
"""
|
||||
with self.lock:
|
||||
if self.state not in _NOT_YET_COPYING:
|
||||
return self.state
|
||||
self.chunks.append(chunk)
|
||||
self._slot_to_row = None
|
||||
if freeze_event is not None:
|
||||
self.freeze_event = freeze_event
|
||||
return None
|
||||
|
||||
def get_host_tensor(self, si: int, key: str) -> torch.Tensor | None:
|
||||
"""`chunks[si]` host if written, else device freeze. One snapshot."""
|
||||
with self.lock:
|
||||
chunk = self.chunks[si]
|
||||
src = chunk.host.get(key)
|
||||
if src is None:
|
||||
src = chunk.tensors.get(key)
|
||||
return src
|
||||
|
||||
def set_host_tensor(self, rows: list[tuple[_WriteChunk, str, torch.Tensor]]) -> None:
|
||||
"""COPYING -> HOST_READY: write these host tensors, drop the device freeze."""
|
||||
with self.lock:
|
||||
for chunk, key, tensor in rows:
|
||||
chunk.host[key] = tensor
|
||||
self._clear_tensors()
|
||||
self._transition_locked(TaskState.HOST_READY)
|
||||
|
||||
def mark_host_ready(self) -> None:
|
||||
"""COPYING -> HOST_READY for staging views: wait the step device→host, drop freeze."""
|
||||
if self.step_d2h_event is not None:
|
||||
self.step_d2h_event.synchronize()
|
||||
with self.lock:
|
||||
self._clear_tensors()
|
||||
self._transition_locked(TaskState.HOST_READY)
|
||||
|
||||
def mark_failed(self, *, defer_wake: bool = False) -> bool:
|
||||
"""-> FAILED from any non-terminal state; unblocks joiners. False if
|
||||
already terminal. ``defer_wake``: the caller publishes the failure
|
||||
record first, then calls ``wake_failed_waiters``."""
|
||||
with self.lock:
|
||||
if self.state.is_terminal:
|
||||
return False
|
||||
self._clear_tensors()
|
||||
self._transition_locked(TaskState.FAILED, wake=not defer_wake)
|
||||
return True
|
||||
|
||||
def wake_failed_waiters(self) -> None:
|
||||
"""Set the events after the failure record is published (see
|
||||
``mark_failed(defer_wake=True)``): a woken joiner must find it."""
|
||||
self.host_ready.set()
|
||||
self.done.set()
|
||||
|
||||
def mark_done(self) -> None:
|
||||
"""HOST_READY -> WRITTEN."""
|
||||
self.transition(TaskState.WRITTEN)
|
||||
|
||||
def scatter_rows(self) -> list[tuple[TensorName, torch.Tensor, torch.Tensor]]:
|
||||
"""`(key, slots, host)` to write, one entry per key. Omits slots in
|
||||
`reassigned`. A slot written twice by this task (preempt + resume
|
||||
onto the same block) keeps the later chunk's row.
|
||||
"""
|
||||
with self.lock:
|
||||
reassigned = {k: s.clone() for k, s in self.reassigned.items()}
|
||||
by_key: dict[TensorName, tuple[list[torch.Tensor], list[torch.Tensor]]] = {}
|
||||
for chunk in self.chunks:
|
||||
for k, host in chunk.host.items():
|
||||
s, h = by_key.setdefault(k, ([], []))
|
||||
s.append(chunk.slots_cpu)
|
||||
h.append(host)
|
||||
out: list[tuple[TensorName, torch.Tensor, torch.Tensor]] = []
|
||||
for k, (s, h) in by_key.items():
|
||||
slots = s[0] if len(s) == 1 else torch.cat(s)
|
||||
host = h[0] if len(h) == 1 else torch.cat(h, dim=0)
|
||||
if len(s) > 1 and torch.unique(slots).numel() != slots.numel():
|
||||
last_pos = {int(slot): i for i, slot in enumerate(slots.tolist())}
|
||||
keep_idx = torch.tensor(sorted(last_pos.values()), dtype=torch.int64)
|
||||
slots, host = slots[keep_idx], host[keep_idx]
|
||||
taken = reassigned.get(k)
|
||||
if taken is not None and taken.numel():
|
||||
keep = ~torch.isin(slots, taken)
|
||||
if not bool(keep.any()):
|
||||
continue
|
||||
slots, host = slots[keep], host[keep]
|
||||
out.append((k, slots, host))
|
||||
return out
|
||||
|
||||
def clear_tensors(self) -> None:
|
||||
"""Drop the device freeze. Host is unchanged (staging wait / fail)."""
|
||||
with self.lock:
|
||||
self._clear_tensors()
|
||||
|
||||
def _clear_tensors(self) -> None:
|
||||
for chunk in self.chunks:
|
||||
chunk.tensors = {}
|
||||
|
||||
def budget_tickets(self) -> list[_BudgetTicket]:
|
||||
"""Distinct tickets across this task's chunks (by identity; one per save)."""
|
||||
out: dict[int, _BudgetTicket] = {}
|
||||
for chunk in self.chunks:
|
||||
if chunk.budget is not None:
|
||||
out.setdefault(id(chunk.budget), chunk.budget)
|
||||
return list(out.values())
|
||||
|
||||
def slot_to_row(self) -> dict[int, tuple[int, int]]:
|
||||
with self.lock:
|
||||
if self._slot_to_row is None:
|
||||
m: dict[int, tuple[int, int]] = {}
|
||||
for si, chunk in enumerate(self.chunks):
|
||||
for ri, slot in enumerate(chunk.slots_cpu.tolist()):
|
||||
m[slot] = (si, ri)
|
||||
self._slot_to_row = m
|
||||
return self._slot_to_row
|
||||
|
||||
|
||||
class StagingBufferPool:
|
||||
"""Reusable pinned landing zone for ONE whole-step device→host at save.
|
||||
|
||||
Per-task `chunk.host` is a row-range view into a slot, so the committer
|
||||
skips a per-task device→host. Slots recycle; this is not the CPU block pool.
|
||||
|
||||
A slot stays busy while anyone still holds it: the step (until
|
||||
materialize/discard) and each immediate write that views the page
|
||||
(until its pool write). Prefix hits do not hold a slot —
|
||||
they wait for the pool write and read the durable pool.
|
||||
|
||||
Saves with only leftover mm still claim a slot (empty views) so
|
||||
every step id shares this bound. A full pool waits; timeout then errors.
|
||||
"""
|
||||
|
||||
def __init__(self, depth: int, capacity: int):
|
||||
self.depth = depth
|
||||
self.capacity = capacity # rows per slot; a larger step raises
|
||||
self._bufs: dict[TensorName, torch.Tensor] = {} # [depth*capacity, width]
|
||||
self._busy: list[set[StagingBufferHolder]] = [set() for _ in range(depth)]
|
||||
self._slot_free_condition = threading.Condition()
|
||||
self._closed = False
|
||||
|
||||
def _buf(self, key: str, width: int, dtype: torch.dtype, pin: bool) -> torch.Tensor:
|
||||
buf = self._bufs.get(key)
|
||||
if buf is None or buf.shape[-1] != width or buf.dtype != dtype:
|
||||
buf = torch.empty((self.depth * self.capacity, width), dtype=dtype, pin_memory=pin)
|
||||
self._bufs[key] = buf
|
||||
return buf
|
||||
|
||||
def claim(self, holder: StagingBufferHolder, timeout: float) -> int:
|
||||
"""Grab a free slot for `holder`. Waits until one is free, then
|
||||
times out. ``timeout<=0`` fails immediately if none are free.
|
||||
"""
|
||||
deadline = time.monotonic() + max(0.0, timeout)
|
||||
with self._slot_free_condition:
|
||||
while True:
|
||||
if self._closed:
|
||||
raise OmniPrefixCacheUnmatchError("staging pool shut down while waiting for a slot")
|
||||
for slot in range(self.depth):
|
||||
if not self._busy[slot]:
|
||||
self._busy[slot].add(holder)
|
||||
return slot
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise OmniPrefixCacheStagingTimeoutError(f"timed out waiting for a staging slot after {timeout}s")
|
||||
self._slot_free_condition.wait(timeout=remaining)
|
||||
|
||||
def bind(self, slot: int, holder: StagingBufferHolder) -> None:
|
||||
with self._slot_free_condition:
|
||||
self._busy[slot].add(holder)
|
||||
|
||||
def release(self, slot: int, holder: StagingBufferHolder) -> None:
|
||||
with self._slot_free_condition:
|
||||
self._busy[slot].discard(holder)
|
||||
if not self._busy[slot]:
|
||||
self._slot_free_condition.notify()
|
||||
|
||||
def close(self) -> None:
|
||||
with self._slot_free_condition:
|
||||
self._closed = True
|
||||
self._slot_free_condition.notify_all()
|
||||
|
||||
def views(self, slot: int, key: str, n: int, width: int, dtype: torch.dtype, pin: bool) -> torch.Tensor:
|
||||
base = slot * self.capacity
|
||||
return self._buf(key, width, dtype, pin)[base : base + n]
|
||||
|
||||
|
||||
@dataclass
|
||||
class StepD2HClaim:
|
||||
"""One whole-step landing in StagingBufferPool.
|
||||
|
||||
Return of ``stage_step_host``. The manager stores this on
|
||||
``_StepContext`` until materialize/discard releases the step holder.
|
||||
"""
|
||||
|
||||
staging_slot: int # StagingBufferPool index
|
||||
views: dict[TensorName, torch.Tensor] # host rows [0:n)
|
||||
event: torch.cuda.Event | None = None # torch.cuda.Event; None on eager/CPU
|
||||
|
||||
|
||||
class OmniPrefixCacheController:
|
||||
"""Staging pool + committer. Step device→host is launched at save;
|
||||
this thread waits that event (JOIN_NEXT_STEP) or copies deferred
|
||||
rows (JOIN_ON_FINISH), then writes into the CPU pool.
|
||||
"""
|
||||
|
||||
def __init__(self, pool: PrefixBlockPool, config: PrefixCacheConfig, eager: bool | None = None):
|
||||
self._pool = pool
|
||||
self._config = config
|
||||
self._eager = (not torch.cuda.is_available()) if eager is None else eager
|
||||
self._tasks: dict[Tid, WriteTask] = {}
|
||||
self._completed: deque[Tid] = deque() # pool write done, awaiting manager drain
|
||||
self._failed: deque[Tid] = deque() # write failed; manager raises from every later entry (sticky)
|
||||
self._staged_bytes = 0
|
||||
self._lock = threading.Lock()
|
||||
self._wake = threading.Condition(self._lock)
|
||||
self._queue_hi: deque[Tid] = deque() # JOIN_NEXT_STEP + forced JOIN_ON_FINISH
|
||||
self._queue_lo: deque[Tid] = deque() # JOIN_ON_FINISH waiting for finish/budget
|
||||
self._blocked: list[Tid] = [] # host copy done, awaiting pool write
|
||||
self._shutdown = False
|
||||
self._copy_stream: torch.cuda.Stream | None = None
|
||||
self._read_stream: torch.cuda.Stream | None = None
|
||||
self._worker: threading.Thread | None = None
|
||||
self._staging_pool = StagingBufferPool(config.staging_depth, config.staging_capacity_tokens)
|
||||
if not self._eager:
|
||||
self._copy_stream = torch.cuda.Stream()
|
||||
self._read_stream = torch.cuda.Stream()
|
||||
self._worker = threading.Thread(target=self._worker_loop, name="omni-prefix-cache-committer", daemon=True)
|
||||
self._worker.start()
|
||||
|
||||
# --------------------------------------------------------- step device→host staging
|
||||
|
||||
def _d2h_on_stream(
|
||||
self,
|
||||
stream: torch.cuda.Stream,
|
||||
freeze_event: torch.cuda.Event | None,
|
||||
copy: Callable[[], None],
|
||||
) -> torch.cuda.Event:
|
||||
"""Issue device→host on `stream` after freeze; return the done event."""
|
||||
with torch.cuda.stream(stream):
|
||||
if freeze_event is not None:
|
||||
stream.wait_event(freeze_event)
|
||||
copy()
|
||||
ev = torch.cuda.Event()
|
||||
ev.record()
|
||||
return ev
|
||||
|
||||
def stage_step_host(
|
||||
self,
|
||||
tensors: dict[str, torch.Tensor],
|
||||
n: int,
|
||||
freeze_event: torch.cuda.Event | None,
|
||||
step_holder: StagingBufferHolder,
|
||||
) -> StepD2HClaim:
|
||||
"""Claim a staging slot and, when `tensors` is non-empty, launch
|
||||
ONE whole-step device→host into it.
|
||||
|
||||
Leftover-only saves pass empty `tensors` and still take a slot
|
||||
(empty views) so every step id shares this bound. A full pool
|
||||
waits for materialize/discard; timeout then errors. A step
|
||||
larger than the page overflows the next slot — that is a config
|
||||
break. The caller binds tasks after submit; `step_holder` is
|
||||
released by materialize/discard via staging_release.
|
||||
"""
|
||||
if tensors and n > self._staging_pool.capacity:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
f"step has {n} tokens; staging capacity is {self._staging_pool.capacity} "
|
||||
"(size staging_capacity_tokens to max_num_batched_tokens)"
|
||||
)
|
||||
slot = self._staging_pool.claim(step_holder, self._config.staging_claim_timeout_s)
|
||||
try:
|
||||
pin = not self._eager
|
||||
views: dict[str, torch.Tensor] = {}
|
||||
event: torch.cuda.Event | None = None
|
||||
if self._eager or all(t.device.type == "cpu" for t in tensors.values()):
|
||||
for key, src in tensors.items():
|
||||
v = self._staging_pool.views(slot, key, n, int(src.shape[-1]), src.dtype, pin)
|
||||
v.copy_(src)
|
||||
views[key] = v
|
||||
else:
|
||||
|
||||
def _copy_to_staging() -> None:
|
||||
for key, src in tensors.items():
|
||||
v = self._staging_pool.views(slot, key, n, int(src.shape[-1]), src.dtype, pin)
|
||||
v.copy_(src, non_blocking=True)
|
||||
views[key] = v
|
||||
|
||||
event = self._d2h_on_stream(self._copy_stream, freeze_event, _copy_to_staging)
|
||||
return StepD2HClaim(staging_slot=slot, views=views, event=event)
|
||||
except Exception:
|
||||
self._staging_pool.release(slot, step_holder)
|
||||
raise
|
||||
|
||||
def staging_bind(self, slot: int, holder: StagingBufferHolder) -> None:
|
||||
self._staging_pool.bind(slot, holder)
|
||||
|
||||
def staging_release(self, slot: int, holder: StagingBufferHolder) -> None:
|
||||
self._staging_pool.release(slot, holder)
|
||||
|
||||
def _release_task_slot(self, task: WriteTask) -> None:
|
||||
"""Drop the task's staging hold at a terminal state (pool write or failure)."""
|
||||
if task.staging_slot is not None:
|
||||
self._staging_pool.release(task.staging_slot, StagingBufferHolder.for_task(task.tid))
|
||||
|
||||
def in_flight_tasks(self) -> int:
|
||||
"""Registered tasks not yet drained (diagnostics only)."""
|
||||
return len(self._tasks)
|
||||
|
||||
# ------------------------------------------------------------------ submit
|
||||
|
||||
def register(self, task: WriteTask, queued: bool = True) -> None:
|
||||
"""Make a task visible (registry + QUEUED) without running anything;
|
||||
safe under the manager's state lock. queued=False (deferred tasks)
|
||||
stays PENDING on the GPU clone until finish/abort or the GPU-byte
|
||||
budget forces a copy. Queued tasks must then go through
|
||||
``dispatch``.
|
||||
|
||||
Caller must reserve() the task bytes first (budget flush can
|
||||
block; the manager does that outside the state lock) and pin the
|
||||
task on its budget ticket(s) before register.
|
||||
"""
|
||||
task.enqueued_time = time.monotonic()
|
||||
with self._lock:
|
||||
self._tasks[task.tid] = task
|
||||
if queued:
|
||||
task.transition(TaskState.QUEUED)
|
||||
|
||||
def dispatch(self, tasks: list[WriteTask]) -> None:
|
||||
"""Hand registered, queued tasks to the copy path. Threaded: enqueue.
|
||||
Eager: the copy + pool write run here, inline — never call this
|
||||
under the manager's state lock."""
|
||||
if not tasks:
|
||||
return
|
||||
if self._eager:
|
||||
try:
|
||||
for task in tasks:
|
||||
self._run_eager(task)
|
||||
except Exception:
|
||||
# Later tasks were registered but will never be dispatched.
|
||||
# Fail them too so shared budget owners and waiters release.
|
||||
for task in tasks:
|
||||
self._fail_task(task.tid)
|
||||
raise
|
||||
return
|
||||
with self._wake:
|
||||
for task in tasks:
|
||||
(self._queue_hi if task.schedule is WriteSchedule.JOIN_NEXT_STEP else self._queue_lo).append(task.tid)
|
||||
self._wake.notify_all()
|
||||
|
||||
def submit(self, task: WriteTask, queued: bool = True) -> None:
|
||||
"""register + dispatch in one call (callers not holding the state lock)."""
|
||||
self.register(task, queued)
|
||||
if queued:
|
||||
self.dispatch([task])
|
||||
|
||||
def append_chunk(
|
||||
self, task: WriteTask, chunk: _WriteChunk, freeze_event: torch.cuda.Event | None = None
|
||||
) -> TaskState | None:
|
||||
"""Append to a pending task. None when appended, else the closing state."""
|
||||
return task.append_chunk(chunk, freeze_event)
|
||||
|
||||
def pin_budget(self, ticket: _BudgetTicket, tid: int) -> None:
|
||||
"""Record that ``tid`` holds a view of the clone ``ticket`` charges."""
|
||||
with self._lock:
|
||||
ticket.tids.add(tid)
|
||||
|
||||
def reserve(self, nbytes: int) -> None:
|
||||
"""Reserve GPU-clone bytes; blocking flush happens here, so callers
|
||||
must not hold the manager's state lock."""
|
||||
self._reserve_bytes(nbytes)
|
||||
|
||||
def _release_staged_bytes(self, task: WriteTask) -> None:
|
||||
"""Drop this task's hold on its budget ticket(s). Idempotent; a
|
||||
ticket uncharges once, when its last holder leaves."""
|
||||
tickets = task.budget_tickets()
|
||||
with self._wake:
|
||||
for ticket in tickets:
|
||||
self._staged_bytes -= ticket.release(task.tid)
|
||||
|
||||
def _reserve_bytes(self, nbytes: int) -> None:
|
||||
# GPU-byte budget: force-copy oldest pending tasks until under
|
||||
# budget. Bounded wait: their device→host has usually long completed.
|
||||
while True:
|
||||
with self._lock:
|
||||
pending = [tid for tid, t in self._tasks.items() if not t.is_terminal]
|
||||
if self._staged_bytes + nbytes <= self._config.gpu_staging_bytes or not pending:
|
||||
# Under budget or no pending tasks; admit reservation.
|
||||
self._staged_bytes += nbytes
|
||||
return
|
||||
oldest = min(pending, key=lambda tid: self._tasks[tid].enqueued_time)
|
||||
logger.warning("omni prefix cache: staging cap hit, force-flushing task %d", oldest)
|
||||
self.escalate([oldest])
|
||||
self.join([oldest])
|
||||
|
||||
# ------------------------------------------------------------- lifecycle
|
||||
|
||||
def escalate(self, tids: list[int]) -> None:
|
||||
"""Move pending tasks to the front of the high-priority queue.
|
||||
|
||||
PENDING -> QUEUED at the head; QUEUED on the low-priority queue
|
||||
moves up; QUEUED already high-priority is a no-op. COPYING and later
|
||||
belong to the worker and are untouched: the worker claims under
|
||||
`_wake` too, so a task cannot be popped and re-queued behind its back.
|
||||
"""
|
||||
if self._eager:
|
||||
self.dispatch([task for tid in tids if (task := self._tasks.get(tid)) is not None and not task.is_terminal])
|
||||
return
|
||||
with self._wake:
|
||||
for tid in tids:
|
||||
task = self._tasks.get(tid)
|
||||
if task is None:
|
||||
continue
|
||||
if task.try_transition(TaskState.QUEUED):
|
||||
self._queue_hi.appendleft(tid)
|
||||
elif task.state is TaskState.QUEUED and tid in self._queue_lo:
|
||||
self._queue_lo.remove(tid)
|
||||
self._queue_hi.appendleft(tid)
|
||||
self._wake.notify_all()
|
||||
|
||||
def join(self, tids: list[int]) -> None:
|
||||
"""Block until each task has finished the CPU-pool write (or failed)."""
|
||||
self._wait_tasks(tids, "done")
|
||||
|
||||
def join_host_ready(self, tids: list[int]) -> None:
|
||||
"""Block until each task's device→host is complete (`host_ready`).
|
||||
|
||||
Staging: committer has waited `step_d2h_event`. Deferred: committer
|
||||
has written `chunk.host`. Does not wait for the CPU-pool write.
|
||||
"""
|
||||
self._wait_tasks(tids, "host_ready")
|
||||
|
||||
def _wait_tasks(self, tids: list[int], event: Literal["done", "host_ready"]) -> None:
|
||||
timeout = self._config.staging_claim_timeout_s
|
||||
deadline = time.monotonic() + timeout
|
||||
for tid in tids:
|
||||
task = self._tasks.get(tid)
|
||||
if task is None:
|
||||
continue
|
||||
if not getattr(task, event).wait(max(0.0, deadline - time.monotonic())):
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
f"task {tid} ({task.schedule.value}) did not reach {event} within {timeout:g}s "
|
||||
f"(state={task.state.name}, in_flight_tasks={len(self._tasks)})"
|
||||
)
|
||||
if task.state is TaskState.FAILED:
|
||||
# FAILED sets both events; success here would read rows the
|
||||
# write never produced. The one-shot failure record may have
|
||||
# been drained by another thread — do not rely on it.
|
||||
raise OmniPrefixCacheUnmatchError(f"task {tid} ({task.schedule.value}) write failed before {event}")
|
||||
|
||||
def drain_completed(self) -> list[int]:
|
||||
"""Pop pool-written tasks from `_completed` and drop them from `_tasks`.
|
||||
Staging holders were already released at the pool write."""
|
||||
out: list[int] = []
|
||||
with self._lock:
|
||||
while self._completed:
|
||||
out.append(self._completed.popleft())
|
||||
for tid in out:
|
||||
self._tasks.pop(tid, None)
|
||||
return out
|
||||
|
||||
def drain_failed(self) -> list[int]:
|
||||
"""Pop failed task ids from `_failed`. Does not drop `_tasks`."""
|
||||
out: list[int] = []
|
||||
with self._lock:
|
||||
while self._failed:
|
||||
out.append(self._failed.popleft())
|
||||
return out
|
||||
|
||||
def get_task(self, tid: int) -> WriteTask | None:
|
||||
return self._tasks.get(tid)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self._staging_pool.close()
|
||||
with self._wake:
|
||||
self._shutdown = True
|
||||
self._wake.notify_all()
|
||||
if self._worker is not None:
|
||||
self._worker.join(timeout=5.0)
|
||||
|
||||
# ------------------------------------------------------------ fetch_host
|
||||
|
||||
@torch.inference_mode()
|
||||
def fetch_host(self, task: WriteTask, slots: torch.Tensor, key: str) -> torch.Tensor:
|
||||
"""Rows for `slots` of one not-yet-done JOIN_ON_FINISH task.
|
||||
|
||||
`_slot_ref` puts JOIN_NEXT_STEP tids in `join_tids` (wait then
|
||||
pool). This path reads committer-written `chunk.host`, or the
|
||||
device clone if that device→host has not landed.
|
||||
"""
|
||||
if task.step_d2h_event is not None:
|
||||
task.step_d2h_event.synchronize()
|
||||
return self._rows_from(task, slots, key)
|
||||
|
||||
def _rows_from(self, task: WriteTask, slots: torch.Tensor, key: str) -> torch.Tensor:
|
||||
"""Map `slots` to rows across one or more `_WriteChunk`s; preserve caller order."""
|
||||
s2r = task.slot_to_row()
|
||||
idx = [s2r[int(s)] for s in slots.tolist()]
|
||||
parts: list[torch.Tensor] = []
|
||||
order: list[int] = []
|
||||
pos = 0
|
||||
rows_groups: dict[int, list[tuple[int, int]]] = {}
|
||||
for si, ri in idx:
|
||||
rows_groups.setdefault(si, []).append((pos, ri))
|
||||
pos += 1
|
||||
for si, items in rows_groups.items():
|
||||
src = task.get_host_tensor(si, key)
|
||||
if src is None:
|
||||
continue
|
||||
rows_idx = torch.tensor([ri for _, ri in items], dtype=torch.long)
|
||||
picked = self._slice_rows(task, src, rows_idx, host=(src.device.type == "cpu"))
|
||||
parts.append(picked)
|
||||
order.extend(p for p, _ in items)
|
||||
if not parts:
|
||||
raise KeyError(f"key {key} not present in task {task.tid}")
|
||||
cat = torch.cat(parts, dim=0)
|
||||
out = torch.empty_like(cat)
|
||||
out[torch.tensor(order, dtype=torch.long)] = cat
|
||||
return out
|
||||
|
||||
def _slice_rows(self, task: WriteTask, src: torch.Tensor, rows_idx: torch.Tensor, host: bool) -> torch.Tensor:
|
||||
n = int(rows_idx.numel())
|
||||
# Ascending-run check without materializing an arange: endpoints plus
|
||||
# a monotonic diff are enough, and the common case is one long run.
|
||||
contiguous = (
|
||||
n > 0 and int(rows_idx[-1]) - int(rows_idx[0]) == n - 1 and (n < 2 or bool((rows_idx.diff() == 1).all()))
|
||||
)
|
||||
|
||||
def _pick() -> torch.Tensor:
|
||||
return src[rows_idx[0] : rows_idx[0] + n] if contiguous else src.index_select(0, rows_idx)
|
||||
|
||||
if host or src.device.type == "cpu":
|
||||
return _pick()
|
||||
if self._read_stream is None:
|
||||
return _pick().detach().cpu()
|
||||
copied: list[torch.Tensor] = []
|
||||
|
||||
def _copy_to_cpu() -> None:
|
||||
copied.append(_pick().to("cpu", non_blocking=True))
|
||||
|
||||
ev = self._d2h_on_stream(self._read_stream, task.freeze_event, _copy_to_cpu)
|
||||
ev.synchronize()
|
||||
return copied[0]
|
||||
|
||||
# ------------------------------------------------------------ eager mode
|
||||
|
||||
@torch.inference_mode()
|
||||
def _run_eager(self, task: WriteTask) -> None:
|
||||
"""Eager stand-in for queue + worker: walk the whole chain inline."""
|
||||
task.try_transition(TaskState.QUEUED) # no-op if submit already queued it
|
||||
if not task.claim_copy():
|
||||
# Copy stage already ran (a held stub, or a prior escalate); finish the write.
|
||||
if task.state is TaskState.HOST_READY:
|
||||
self._scatter(task)
|
||||
return
|
||||
if task.schedule is WriteSchedule.JOIN_NEXT_STEP:
|
||||
# Host is already a staging view (copied at save). Drop freeze.
|
||||
# `step_d2h_event` is None on CPU; `mark_host_ready` skips wait.
|
||||
task.mark_host_ready()
|
||||
else:
|
||||
# JOIN_ON_FINISH: no copy stream; freeze → owned host inline.
|
||||
task.set_host_tensor(
|
||||
[
|
||||
(chunk, k, t.detach().cpu() if t.device.type != "cpu" else t.clone())
|
||||
for chunk in task.chunks
|
||||
for k, t in chunk.tensors.items()
|
||||
]
|
||||
)
|
||||
self._release_staged_bytes(task)
|
||||
self._scatter(task)
|
||||
|
||||
# ---------------------------------------------------------- worker loop
|
||||
|
||||
def _worker_loop(self) -> None:
|
||||
# A dying committer would strand every join() forever, so the loop
|
||||
# never propagates: it fails the offending task and keeps serving.
|
||||
while True:
|
||||
tid = None
|
||||
try:
|
||||
task: WriteTask | None = None
|
||||
with self._wake:
|
||||
while not self._shutdown and not self._queue_hi and not self._queue_lo:
|
||||
if self._blocked:
|
||||
break
|
||||
# submit / escalate / shutdown all notify.
|
||||
self._wake.wait()
|
||||
if self._shutdown and not self._queue_hi and not self._queue_lo and not self._blocked:
|
||||
return
|
||||
if self._queue_hi:
|
||||
tid = self._queue_hi.popleft()
|
||||
elif self._queue_lo:
|
||||
tid = self._queue_lo.popleft()
|
||||
if tid is not None:
|
||||
task = self._tasks.get(tid)
|
||||
if task is not None:
|
||||
# Claim in the same critical section as the pop:
|
||||
# escalate holds `_wake` and sees COPYING.
|
||||
task.transition(TaskState.COPYING)
|
||||
if task is not None:
|
||||
self._copy_task(task)
|
||||
with self._wake:
|
||||
assert task.tid not in self._blocked, f"task {task.tid} reached HOST_READY twice"
|
||||
self._blocked.append(task.tid)
|
||||
self._scatter_host_ready()
|
||||
except BaseException:
|
||||
logger.exception("omni prefix cache committer failed on task %s; releasing waiters", tid)
|
||||
self._fail_task(tid)
|
||||
|
||||
@torch.inference_mode()
|
||||
def _copy_task(self, task: WriteTask) -> None:
|
||||
"""COPYING -> HOST_READY. Staging: wait the save-time device→host event.
|
||||
Deferred: this is the device→host into owned `chunk.host` tensors.
|
||||
"""
|
||||
if task.schedule is WriteSchedule.JOIN_NEXT_STEP:
|
||||
# `chunk.host` is already a staging view; device→host ran at save.
|
||||
# `mark_host_ready` waits `step_d2h_event` if one was recorded.
|
||||
# No per-task copy. Pool write is `_scatter_host_ready`.
|
||||
task.mark_host_ready()
|
||||
self._release_staged_bytes(task)
|
||||
return
|
||||
# One device cat + one device→host per key, not one per chunk (a
|
||||
# long request has one chunk per step).
|
||||
chunk_bytes = self._config.copy_chunk_bytes
|
||||
by_key: dict[str, list[_WriteChunk]] = {}
|
||||
for chunk in task.chunks:
|
||||
for k in chunk.tensors:
|
||||
by_key.setdefault(k, []).append(chunk)
|
||||
pending: list[tuple[str, list[_WriteChunk], list[torch.Tensor]]] = []
|
||||
if self._copy_stream is None:
|
||||
raise OmniPrefixCacheUnmatchError("deferred prefix cache copy requires a CUDA copy stream")
|
||||
with torch.cuda.stream(self._copy_stream):
|
||||
if task.freeze_event is not None:
|
||||
self._copy_stream.wait_event(task.freeze_event)
|
||||
for k, chunks in by_key.items():
|
||||
srcs = [c.tensors[k] for c in chunks]
|
||||
src = srcs[0] if len(srcs) == 1 else torch.cat(srcs, dim=0)
|
||||
rows = int(src.shape[0])
|
||||
row_bytes = max(1, src[:1].numel() * src.element_size())
|
||||
step = max(1, rows if rows * row_bytes <= chunk_bytes else chunk_bytes // row_bytes)
|
||||
parts = [src[s : s + step].to("cpu", non_blocking=True) for s in range(0, max(rows, 1), step)]
|
||||
pending.append((k, chunks, parts))
|
||||
ev = torch.cuda.Event()
|
||||
ev.record()
|
||||
ev.synchronize()
|
||||
rows_out: list[tuple[_WriteChunk, str, torch.Tensor]] = []
|
||||
for k, chunks, parts in pending:
|
||||
host = parts[0] if len(parts) == 1 else torch.cat(parts, dim=0)
|
||||
if len(chunks) == 1:
|
||||
rows_out.append((chunks[0], k, host))
|
||||
continue
|
||||
for chunk, view in zip(chunks, torch.split(host, [int(c.tensors[k].shape[0]) for c in chunks], dim=0)):
|
||||
rows_out.append((chunk, k, view))
|
||||
task.set_host_tensor(rows_out)
|
||||
self._release_staged_bytes(task)
|
||||
|
||||
def _fail_task(self, tid: int | None) -> None:
|
||||
"""-> FAILED: release waiters for a task the committer could not complete.
|
||||
|
||||
No-op once the task is terminal. Budget release is idempotent, so a
|
||||
raise after a successful copy stage does not uncharge twice.
|
||||
"""
|
||||
task = self._tasks.get(tid) if tid is not None else None
|
||||
if task is None or not task.mark_failed(defer_wake=True):
|
||||
return
|
||||
self._release_staged_bytes(task)
|
||||
with self._wake:
|
||||
if tid in self._blocked:
|
||||
self._blocked.remove(tid)
|
||||
self._release_task_slot(task)
|
||||
with self._lock:
|
||||
# Publish the failure: rows behind already-published block hashes
|
||||
# never landed, which the manager must raise on (hiding it would
|
||||
# crash on every future hit that touches these slots).
|
||||
self._failed.append(task.tid)
|
||||
# Events last: a joiner woken by them must find the record on drain,
|
||||
# not read never-written pool rows in a done-but-unpublished window.
|
||||
task.wake_failed_waiters()
|
||||
|
||||
@torch.inference_mode()
|
||||
def _scatter_host_ready(self) -> None:
|
||||
"""HOST_READY -> WRITTEN for every `_blocked` task that has reached HOST_READY."""
|
||||
with self._wake:
|
||||
ready = [tid for tid in self._blocked if (t := self._tasks.get(tid)) and t.state is TaskState.HOST_READY]
|
||||
for tid in ready:
|
||||
self._blocked.remove(tid)
|
||||
for tid in ready:
|
||||
task = self._tasks[tid]
|
||||
try:
|
||||
self._scatter(task)
|
||||
except BaseException:
|
||||
# Attribute the failure to THIS task: letting it propagate
|
||||
# would fail whichever entry the worker loop happened to be
|
||||
# copying, double-release its bytes, and strand this one's
|
||||
# join() forever.
|
||||
logger.exception("omni prefix cache scatter failed on task %s; releasing waiters", tid)
|
||||
self._fail_task(tid)
|
||||
|
||||
@torch.inference_mode()
|
||||
def _scatter(self, task: WriteTask) -> None:
|
||||
for key, slots, host in task.scatter_rows():
|
||||
self._pool.write(key, slots, host)
|
||||
# `done` is set LAST: a join(done) waiter (the save barrier) must find
|
||||
# the completion record on its next drain and the staging slot free —
|
||||
# a done-but-undrained window would leave occupancy IN_TRANSIT and
|
||||
# make the COW preserve skip the reused rows.
|
||||
self._release_task_slot(task)
|
||||
with self._lock:
|
||||
self._completed.append(task.tid)
|
||||
task.mark_done()
|
||||
@@ -0,0 +1,208 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""KV-cache group access for the omni prefix cache.
|
||||
|
||||
The sole path through which the prefix cache touches vLLM scheduler
|
||||
internals (block tables, slot mappings). Group-spec rejection happens
|
||||
at kv-cache init via ``check_prefix_cache_kv_groups``; the factory only
|
||||
returns None when the input batch has no block table.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.core.prefix_cache.interface import OmniPrefixCacheUnmatchError, PrefixCacheConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu_input_batch import InputBatch
|
||||
|
||||
|
||||
class FullAttentionGroupView:
|
||||
"""View over the first (full-attention) KV-cache group.
|
||||
|
||||
Step slots come from the CPU block table (`step_slots_cpu`), not the
|
||||
device slot_mapping.
|
||||
"""
|
||||
|
||||
def __init__(self, input_batch: InputBatch, block_size: int):
|
||||
self._input_batch = input_batch
|
||||
self.block_size = block_size
|
||||
check_prefix_cache_block_layout(input_batch.block_table[0], block_size)
|
||||
|
||||
def _block_table_cpu(self) -> torch.Tensor:
|
||||
return self._input_batch.block_table[0].block_table.cpu
|
||||
|
||||
def batch_req_ids(self) -> list[str]:
|
||||
return list(self._input_batch.req_ids)
|
||||
|
||||
def step_slots_cpu(self, req_ids: list[str], num_scheduled: dict[str, int]) -> torch.Tensor:
|
||||
"""This step's slot mapping, computed on CPU from the block table.
|
||||
|
||||
The device slot_mapping would need a stream sync to read back, which
|
||||
stalls the whole forward; the CPU block table carries the same
|
||||
information (positions are num_computed .. +num_scheduled per request).
|
||||
"""
|
||||
block_table = self._block_table_cpu()
|
||||
bs = self.block_size
|
||||
max_blocks = int(block_table.shape[1])
|
||||
computed = self._input_batch.num_computed_tokens_cpu
|
||||
parts: list[torch.Tensor] = []
|
||||
for req_id in req_ids:
|
||||
n = int(num_scheduled.get(req_id, 0))
|
||||
if n <= 0:
|
||||
continue
|
||||
req_idx = self._input_batch.req_id_to_index[req_id]
|
||||
start = int(computed[req_idx])
|
||||
pos = torch.arange(start, start + n, dtype=torch.long)
|
||||
offs = pos // bs
|
||||
if int(offs[-1]) >= max_blocks:
|
||||
keep = offs < max_blocks
|
||||
pos, offs = pos[keep], offs[keep]
|
||||
if pos.numel() == 0:
|
||||
continue
|
||||
parts.append(block_table[req_idx, offs].to(torch.long) * bs + (pos % bs))
|
||||
return torch.cat(parts) if parts else torch.empty((0,), dtype=torch.long)
|
||||
|
||||
|
||||
def check_prefix_cache_block_layout(block_table: object, block_size: int) -> None:
|
||||
"""Reject block-table layouts ``step_slots_cpu`` cannot mirror.
|
||||
|
||||
The CPU slot math is ``table[req, pos // block_size] * block_size +
|
||||
pos % block_size`` over allocator block ids. vLLM breaks that in two
|
||||
cases: hybrid kernel blocks (the row holds ``blocks_per_kv_block``
|
||||
kernel ids per allocator block, e.g. FlashInfer/FlashMLA with
|
||||
``--block-size 128``) and decode context parallel (tokens are striped
|
||||
across ranks and hashed at ``block_size * dcp_world_size``).
|
||||
"""
|
||||
if getattr(block_table, "use_hybrid_blocks", False) or int(getattr(block_table, "blocks_per_kv_block", 1)) != 1:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching requires kernel_block_size == block_size; the attention backend "
|
||||
f"splits each block into {getattr(block_table, 'blocks_per_kv_block', '?')} kernel blocks. "
|
||||
"Pick a --block-size the backend supports natively or disable enable_prefix_caching"
|
||||
)
|
||||
if int(getattr(block_table, "dcp_world_size", 1)) != 1:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching does not support decode context parallel "
|
||||
f"(dcp_world_size={getattr(block_table, 'dcp_world_size', '?')}); disable enable_prefix_caching"
|
||||
)
|
||||
kv_bs = getattr(block_table, "kv_cache_block_size", block_size)
|
||||
if int(kv_bs) != int(block_size):
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
f"omni prefix caching block_size {block_size} does not match the kv-cache block table ({kv_bs})"
|
||||
)
|
||||
|
||||
|
||||
def check_prefix_cache_kv_groups(kv_cache_groups: object) -> None:
|
||||
"""Reject hybrid / multi-group models at kv-cache init, not first step.
|
||||
|
||||
Only needs ``kv_cache_config.kv_cache_groups``. ``FullAttentionSpec``
|
||||
is imported here so ``tests/core`` can load this module without vllm.
|
||||
"""
|
||||
groups = list(kv_cache_groups or ())
|
||||
if len(groups) != 1:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching requires a single full-attention kv-cache group; "
|
||||
f"found {len(groups)}. disable enable_prefix_caching for this model"
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec
|
||||
|
||||
spec = getattr(groups[0], "kv_cache_spec", None)
|
||||
if not isinstance(spec, FullAttentionSpec):
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching requires a single full-attention kv-cache group; "
|
||||
f"found {type(spec).__name__}. disable enable_prefix_caching for this model"
|
||||
)
|
||||
|
||||
|
||||
def check_prefix_cache_kv_transfer(kv_transfer_config: object) -> None:
|
||||
"""Reject kv_consumer / kv_both stages.
|
||||
|
||||
KV loaded from a producer also shows up as ``num_computed_tokens``; the
|
||||
manager would read it as a local hit with no rows behind it.
|
||||
"""
|
||||
if kv_transfer_config is not None and getattr(kv_transfer_config, "is_kv_consumer", False):
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching cannot tell locally cached tokens from KV received "
|
||||
"through a KV connector; disable enable_prefix_caching on kv_consumer / "
|
||||
"kv_both stages"
|
||||
)
|
||||
|
||||
|
||||
def check_prefix_cache_token_accounting(cache_config: object, speculative_config: object) -> None:
|
||||
"""Reject configs where ``num_computed_tokens`` stops meaning "first
|
||||
scheduled position, block aligned".
|
||||
|
||||
Speculative decoding: with async scheduling vLLM keeps
|
||||
``num_computed_tokens_cpu`` optimistic (all drafts accepted) during the
|
||||
forward and corrects it after; ``step_slots_cpu`` would read the
|
||||
uncorrected value and mirror rows at the wrong slots. Refused as a
|
||||
whole until that path is verified. ``prefix_match_unit`` smaller than
|
||||
the block enables sub-block hits, which the hit registry rejects as
|
||||
unaligned on the first hit; refuse at init instead.
|
||||
"""
|
||||
if speculative_config is not None:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching is not supported together with speculative decoding; "
|
||||
"disable enable_prefix_caching on this stage"
|
||||
)
|
||||
unit = getattr(cache_config, "prefix_match_unit", None)
|
||||
block_size = getattr(cache_config, "block_size", None)
|
||||
if unit is not None and block_size is not None and int(unit) != int(block_size):
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
f"omni prefix caching requires block-aligned hits; prefix_match_unit={unit} with block_size={block_size} "
|
||||
"enables sub-block hits. Unset prefix_match_unit or disable enable_prefix_caching"
|
||||
)
|
||||
|
||||
|
||||
def stage_prefix_cache_config(
|
||||
*,
|
||||
kv_cache_config: object,
|
||||
cache_config: object,
|
||||
kv_transfer_config: object,
|
||||
scheduler_config: object,
|
||||
model_config: object,
|
||||
is_pooling_model: bool,
|
||||
speculative_config: object = None,
|
||||
) -> PrefixCacheConfig | None:
|
||||
"""Runner-side gate shared by the GPU and NPU model runners.
|
||||
|
||||
Returns None when the stage does not run an omni prefix cache
|
||||
(``enable_prefix_caching`` off, or a pooling stage that never saves).
|
||||
Otherwise refuses kv_consumer / kv_both, speculative decoding,
|
||||
sub-block matching and hybrid kv groups, then sizes the config from
|
||||
the scheduler. One place so a platform runner cannot silently skip a
|
||||
refusal the other one has.
|
||||
"""
|
||||
if not getattr(cache_config, "enable_prefix_caching", False) or is_pooling_model:
|
||||
return None
|
||||
check_prefix_cache_kv_transfer(kv_transfer_config)
|
||||
check_prefix_cache_token_accounting(cache_config, speculative_config)
|
||||
check_prefix_cache_kv_groups(getattr(kv_cache_config, "kv_cache_groups", None))
|
||||
return PrefixCacheConfig.from_vllm_config(
|
||||
num_blocks=kv_cache_config.num_blocks, # type: ignore[attr-defined]
|
||||
block_size=cache_config.block_size, # type: ignore[attr-defined]
|
||||
scheduler_config=scheduler_config,
|
||||
model_config=model_config,
|
||||
)
|
||||
|
||||
|
||||
def get_prefix_cache_group_view(
|
||||
input_batch: InputBatch,
|
||||
block_size: int,
|
||||
kv_cache_groups: object = None,
|
||||
) -> FullAttentionGroupView | None:
|
||||
"""Build the group view; None only if the batch has no block table.
|
||||
|
||||
Group spec is checked first (raises). Selection is by spec, not by
|
||||
counting block tables: a hybrid model's group 0 is not necessarily
|
||||
full attention, and a narrower per-group table would make
|
||||
step_slots_cpu silently clamp.
|
||||
"""
|
||||
check_prefix_cache_kv_groups(kv_cache_groups)
|
||||
block_tables = getattr(input_batch.block_table, "block_tables", None)
|
||||
if not block_tables:
|
||||
return None
|
||||
return FullAttentionGroupView(input_batch, block_size)
|
||||
@@ -0,0 +1,171 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Interface types for the omni prefix cache.
|
||||
|
||||
Naming aligns with vLLM's v1/core KV-cache design.
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, NamedTuple, TypeAlias
|
||||
|
||||
import torch
|
||||
|
||||
# Four identities (still str/int at runtime, not interchangeable):
|
||||
# TensorName which cached tensor (hidden / mm), not a prefix hash
|
||||
# ReqId vLLM request id
|
||||
# Tid WriteTask handle
|
||||
# StepId save_outputs id; materialize or discard exactly once
|
||||
TensorName: TypeAlias = str
|
||||
ReqId: TypeAlias = str
|
||||
Tid: TypeAlias = int
|
||||
StepId: TypeAlias = int
|
||||
|
||||
# Reserved pool key for hidden states (mm keys are flat dotted names).
|
||||
# Identity only — whether a model caches it lives on ModelCachePolicy.
|
||||
HIDDEN_KEY: TensorName = "__hidden_states__"
|
||||
|
||||
|
||||
def is_hidden_key(key: TensorName) -> bool:
|
||||
return key == HIDDEN_KEY
|
||||
|
||||
|
||||
def without_hidden(keys: Iterable[TensorName]) -> set[TensorName]:
|
||||
"""Drop the reserved hidden identity; the rest are mm names."""
|
||||
return {k for k in keys if k != HIDDEN_KEY}
|
||||
|
||||
|
||||
class WriteSchedule(Enum):
|
||||
"""Write scheduling policy for one WriteTask."""
|
||||
|
||||
# Immediately-cached keys: device→host launched at save into the
|
||||
# staging pool; committer waits that event and writes the CPU pool.
|
||||
# The next save waits done (a reused slot must be pool-complete).
|
||||
JOIN_NEXT_STEP = "join_next_step"
|
||||
# Deferred mm: stays on the GPU clone until finish/abort (GPU-byte
|
||||
# budget may force a copy earlier). One WriteTask per request.
|
||||
JOIN_ON_FINISH = "join_on_finish"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrefixCacheConfig:
|
||||
"""Sizing and flow-control knobs (mirrors KVCacheConfig)."""
|
||||
|
||||
num_blocks: int
|
||||
block_size: int
|
||||
# GPU-clone byte budget for JOIN_ON_FINISH; exceeding it forces a copy.
|
||||
gpu_staging_bytes: int = 512 * 1024 * 1024
|
||||
# Device→host staging: circular slots, one whole step each (not per request).
|
||||
# Host memory per key ≈ staging_depth * staging_capacity_tokens * width * dtype.
|
||||
# Prefer from_vllm_config so staging_capacity_tokens tracks max_num_batched_tokens.
|
||||
staging_depth: int = 4
|
||||
staging_capacity_tokens: int = 1024
|
||||
# How long save waits for a free staging slot, and join/join_host_ready
|
||||
# for the committer; exceeding it raises.
|
||||
staging_claim_timeout_s: float = 30.0
|
||||
# Device→host chunk size for JOIN_ON_FINISH (copied a piece at a time).
|
||||
copy_chunk_bytes: int = 16 * 1024 * 1024
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(
|
||||
cls,
|
||||
*,
|
||||
num_blocks: int,
|
||||
block_size: int,
|
||||
scheduler_config: Any = None,
|
||||
model_config: Any = None,
|
||||
) -> "PrefixCacheConfig":
|
||||
"""Size device→host staging from the running scheduler.
|
||||
|
||||
A slot holds one *step* (the whole batch), not one request:
|
||||
``staging_capacity_tokens`` is ``max_num_batched_tokens`` (falls back
|
||||
to ``max_model_len``); ``staging_depth`` is how many unconsumed
|
||||
step ids may exist at once, not ``max_num_seqs``.
|
||||
|
||||
Pinned staging is allocated lazily per key at
|
||||
``depth * capacity_tokens * width * dtype``. There is no clamp: a
|
||||
step larger than capacity raises. A 16k-token thinking batch at
|
||||
hidden=2048 bf16 is ~256 MiB for hidden alone; each mm key adds
|
||||
another pool tensor.
|
||||
|
||||
``staging_depth`` is the dataclass default (4). There is no CLI or
|
||||
deploy YAML knob — changing it is a code change. Every save that
|
||||
issues a step id claims one slot, including saves with only leftover
|
||||
mm. A full pool waits for materialize/discard;
|
||||
``staging_claim_timeout_s`` then errors.
|
||||
"""
|
||||
batched = getattr(scheduler_config, "max_num_batched_tokens", None)
|
||||
model_len = getattr(scheduler_config, "max_model_len", None)
|
||||
if not model_len and model_config is not None:
|
||||
model_len = getattr(model_config, "max_model_len", None)
|
||||
try:
|
||||
capacity = int(batched or model_len or 1024)
|
||||
except (TypeError, ValueError):
|
||||
capacity = 1024
|
||||
return cls(
|
||||
num_blocks=num_blocks,
|
||||
block_size=block_size,
|
||||
staging_capacity_tokens=max(1, capacity),
|
||||
)
|
||||
|
||||
|
||||
class StageCacheOutputs(NamedTuple):
|
||||
"""Plain value object: per-request merged stage outputs."""
|
||||
|
||||
# req -> full-prompt hidden states (None when policy skips them)
|
||||
hidden_states: dict[ReqId, torch.Tensor] | None
|
||||
# tensor name -> req -> payload element
|
||||
mm_outputs: dict[TensorName, dict[ReqId, Any]]
|
||||
|
||||
|
||||
class OmniPrefixCacheUnmatchError(RuntimeError):
|
||||
"""Contract, config, or KV-occupancy error that must raise.
|
||||
|
||||
Includes hit spans that resolve to absent slots (omni cache diverged
|
||||
from vLLM KV), a step id consumed twice or never saved, a step larger
|
||||
than the staging page, and a failed write. Do not pretend these
|
||||
were a miss.
|
||||
"""
|
||||
|
||||
|
||||
class OmniPrefixCacheStagingTimeoutError(OmniPrefixCacheUnmatchError):
|
||||
"""Save waited for a free staging slot and timed out."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ModelCachePolicy:
|
||||
"""Replaces getattr probing on models for cache behavior decisions.
|
||||
|
||||
Hidden's *name* is ``HIDDEN_KEY`` (shared identity). This object
|
||||
answers whether this model caches it, and which mm keys are deferred.
|
||||
"""
|
||||
|
||||
needs_full_hidden_states: bool = True
|
||||
# Mm whose first dim is this step's token count; stays on the GPU
|
||||
# clone until finish/abort (JOIN_ON_FINISH). Also skipped by the
|
||||
# immediate on-device clone / device→host path.
|
||||
deferred_keys: frozenset[TensorName] = frozenset()
|
||||
|
||||
@property
|
||||
def hidden_key(self) -> TensorName | None:
|
||||
"""Pool key for hidden, or None when this model opts out."""
|
||||
return HIDDEN_KEY if self.needs_full_hidden_states else None
|
||||
|
||||
def get_hit_keys(self, keys: Iterable[TensorName]) -> list[TensorName]:
|
||||
"""Keys to plan/prefetch for a hit: hidden first (if cached), then mm."""
|
||||
mm = sorted(without_hidden(keys))
|
||||
return [HIDDEN_KEY, *mm] if self.needs_full_hidden_states else mm
|
||||
|
||||
def skip_immediate_mm(self, key: TensorName) -> bool:
|
||||
"""Immediate on-device clone must not take hidden or deferred keys from mm."""
|
||||
return is_hidden_key(key) or key in self.deferred_keys
|
||||
|
||||
@classmethod
|
||||
def from_model(cls, model: Any) -> "ModelCachePolicy":
|
||||
"""Shim over legacy per-model attributes (deprecation window)."""
|
||||
deferred = frozenset(getattr(model, "deferred_prefix_cache_mm_keys", ()) or ())
|
||||
return cls(
|
||||
needs_full_hidden_states=bool(getattr(model, "requires_full_prefix_cached_hidden_states", True)),
|
||||
deferred_keys=deferred,
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,148 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Runner-facing access layer for the omni prefix cache.
|
||||
|
||||
One copy of the integration rules shared by the GPU and NPU runners:
|
||||
one-shot manager construction, the model cache-policy snapshot, and the
|
||||
per-step lifecycle entry. The manager/controller state machines and the
|
||||
platform output-building flows stay in their owners.
|
||||
|
||||
Not exported from the package ``__init__``; runners import this module
|
||||
directly. No module-level vLLM import (``get_pp_group`` is resolved at
|
||||
call time) so ``tests/core`` keeps loading the package without vLLM.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm_omni.core.prefix_cache.group_view import get_prefix_cache_group_view
|
||||
from vllm_omni.core.prefix_cache.interface import (
|
||||
ModelCachePolicy,
|
||||
OmniPrefixCacheUnmatchError,
|
||||
PrefixCacheConfig,
|
||||
)
|
||||
from vllm_omni.core.prefix_cache.manager import OmniPrefixCacheManager
|
||||
from vllm_omni.data_entry_keys import flatten_payload
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import torch
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
|
||||
|
||||
class PrefixCacheRunnerMixin:
|
||||
"""Prefix-cache integration for a model runner (no state machine here).
|
||||
|
||||
Host-class contract — the runner must provide:
|
||||
``input_batch`` live batch with the group-0 block table
|
||||
``kv_cache_config`` for ``kv_cache_groups`` at construction
|
||||
``omni_prefix_cache`` set here; ``None`` until first-step build
|
||||
``_omni_prefix_cache_cfg`` staged by the runner's kv-cache init
|
||||
(``stage_prefix_cache_config``), consumed here
|
||||
|
||||
No cooperative ``__init__``: the class attributes below are safe
|
||||
defaults (``ModelCachePolicy`` is frozen); runners keep initializing
|
||||
their instance fields as before.
|
||||
"""
|
||||
|
||||
# Host-class fields (annotation only; the runner initializes them).
|
||||
input_batch: Any
|
||||
kv_cache_config: Any
|
||||
is_pooling_model: bool
|
||||
|
||||
omni_prefix_cache: OmniPrefixCacheManager | None = None
|
||||
_omni_prefix_cache_cfg: PrefixCacheConfig | None = None
|
||||
# Snapshotted once at load_model; the hot path must not re-probe model
|
||||
# attributes every step. The same object is registered on the manager.
|
||||
_omni_cache_policy: ModelCachePolicy = ModelCachePolicy()
|
||||
|
||||
def _snapshot_prefix_cache_model_policy(self, model) -> None:
|
||||
"""Freeze the model's cache policy at load_model."""
|
||||
self._omni_cache_policy = ModelCachePolicy.from_model(model)
|
||||
|
||||
def _model_needs_full_prefix_hidden_states(self) -> bool:
|
||||
"""Opt-out hook for models whose postprocess only consumes the tail.
|
||||
|
||||
When False, we skip both the per-step hidden-state write into the
|
||||
omni prefix cache and the merged-tensor reconstruction on hits;
|
||||
postprocess receives the normal scheduled-token slice instead. Models
|
||||
that need the full cached_prefix + new_tail span (default) are not
|
||||
affected.
|
||||
"""
|
||||
return self._omni_cache_policy.needs_full_hidden_states
|
||||
|
||||
def _ensure_omni_prefix_cache(self) -> None:
|
||||
"""One-shot construction (caller gates on the staged config).
|
||||
|
||||
Only the last PP rank writes and materializes the cache. Other ranks
|
||||
would register hits they can never serve (save_outputs is last-rank
|
||||
only), so skip construction there.
|
||||
"""
|
||||
from vllm.distributed.parallel_state import get_pp_group
|
||||
|
||||
cfg = self._omni_prefix_cache_cfg
|
||||
self._omni_prefix_cache_cfg = None
|
||||
if cfg is None or not get_pp_group().is_last_rank:
|
||||
return
|
||||
view = get_prefix_cache_group_view(
|
||||
self.input_batch,
|
||||
cfg.block_size,
|
||||
kv_cache_groups=getattr(self.kv_cache_config, "kv_cache_groups", None),
|
||||
)
|
||||
if view is None:
|
||||
raise OmniPrefixCacheUnmatchError(
|
||||
"omni prefix caching requires a block table on the input batch; "
|
||||
"disable enable_prefix_caching for this model"
|
||||
)
|
||||
manager = OmniPrefixCacheManager(cfg, view)
|
||||
manager.register_policy(self._omni_cache_policy)
|
||||
self.omni_prefix_cache = manager
|
||||
|
||||
def _prefix_cache_step_begin(self, scheduler_output: SchedulerOutput) -> None:
|
||||
"""Per-step lifecycle entry; must run before ``_update_states``
|
||||
removes finished requests (finished/abort escalation happens inside
|
||||
``new_step_starts``). Builds the manager on the first real step."""
|
||||
if self.omni_prefix_cache is None and self._omni_prefix_cache_cfg is not None:
|
||||
self._ensure_omni_prefix_cache()
|
||||
if self.omni_prefix_cache is not None:
|
||||
self.omni_prefix_cache.new_step_starts(scheduler_output)
|
||||
|
||||
def _prefix_cache_save_step(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
multimodal_outputs: dict | None,
|
||||
*,
|
||||
num_tokens_unpadded: int,
|
||||
num_tokens_padded: int,
|
||||
) -> int | None:
|
||||
"""Write this step's outputs into the cache.
|
||||
|
||||
None when this stage/rank does not write (pooling, cache off, or not
|
||||
the last PP rank). The returned step id must be consumed exactly once
|
||||
— materialize or discard_step — by the output path.
|
||||
"""
|
||||
from vllm.distributed.parallel_state import get_pp_group
|
||||
|
||||
if self.is_pooling_model or self.omni_prefix_cache is None or not get_pp_group().is_last_rank:
|
||||
return None
|
||||
return self.omni_prefix_cache.save_outputs(
|
||||
hidden_states,
|
||||
flatten_payload(multimodal_outputs) if multimodal_outputs else {},
|
||||
num_tokens_unpadded=num_tokens_unpadded,
|
||||
num_tokens_padded=num_tokens_padded,
|
||||
)
|
||||
|
||||
def _prefix_cache_materialize(
|
||||
self, step_id: int | None, req_ids: list[str]
|
||||
) -> tuple[dict[str, torch.Tensor] | None, dict | None]:
|
||||
"""Per-request merged outputs for a saved step.
|
||||
|
||||
``req_ids`` must be the save-time snapshot, never the live
|
||||
``input_batch`` (under async output this runs a step late).
|
||||
``step_id`` None means save did not run — nothing to consume.
|
||||
``mm_outputs`` is all-or-nothing; empty only when the step had no mm.
|
||||
"""
|
||||
if step_id is None or self.omni_prefix_cache is None:
|
||||
return None, None
|
||||
outs = self.omni_prefix_cache.materialize(step_id, list(req_ids))
|
||||
return outs.hidden_states, (outs.mm_outputs or None)
|
||||
@@ -23,13 +23,31 @@ from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
from vllm_omni.core.sched.utils import omni_routed_experts_for_request
|
||||
from vllm_omni.core.sched.utils import (
|
||||
free_kv_blocks_in_physical_order,
|
||||
omni_routed_experts_for_request,
|
||||
)
|
||||
from vllm_omni.engine import OmniEngineCoreOutput
|
||||
from vllm_omni.engine.serialization import deserialize_additional_information
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _should_emit_engine_output(
|
||||
model_config: Any,
|
||||
*,
|
||||
stopped: bool,
|
||||
has_control: bool,
|
||||
) -> bool:
|
||||
if stopped or has_control:
|
||||
return True
|
||||
return not (
|
||||
bool(getattr(model_config, "use_v2_model_runner", False))
|
||||
and bool(getattr(model_config, "async_chunk", False))
|
||||
and not bool(getattr(model_config, "final_output", False))
|
||||
)
|
||||
|
||||
|
||||
class SampledLogprobContractError(RuntimeError):
|
||||
"""The model runner returned unusable sampled-token logprobs."""
|
||||
|
||||
@@ -81,6 +99,8 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
core scheduling logic.
|
||||
"""
|
||||
|
||||
max_num_running_reqs: int
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# Track requests that need KV cache transfer when finished
|
||||
@@ -127,6 +147,26 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
# Output placeholders are zero when async scheduling isn't used
|
||||
return request.num_computed_tokens - request.num_output_placeholders
|
||||
|
||||
def _uses_native_mooncake_connector(self) -> bool:
|
||||
kv_config = getattr(self.vllm_config, "kv_transfer_config", None)
|
||||
return getattr(kv_config, "kv_connector", None) == "MooncakeConnector"
|
||||
|
||||
def _free_request_blocks(self, request: Request) -> None:
|
||||
"""Keep native Mooncake pages coalescible without changing vLLM APIs."""
|
||||
|
||||
if not self._uses_native_mooncake_connector() or self.kv_cache_manager.enable_caching:
|
||||
super()._free_request_blocks(request)
|
||||
return
|
||||
if not self.defer_block_free or request.last_sched_seq <= self.processed_step_seq:
|
||||
free_kv_blocks_in_physical_order(self.kv_cache_manager, request)
|
||||
return
|
||||
blocks = self.kv_cache_manager.pop_blocks_for_free(request)
|
||||
if blocks:
|
||||
# vLLM's deferred-free drain reverses this list before returning
|
||||
# it to BlockPool, so store the inverse of the desired order.
|
||||
blocks.sort(key=lambda block: block.block_id, reverse=True)
|
||||
self.deferred_frees.append((self.sched_step_seq, blocks))
|
||||
|
||||
def _resolve_kv_connector_type(self) -> str:
|
||||
"""Connector backend name for the ``kv_wait_s`` label, or ``unknown``."""
|
||||
connector_cfg = self._get_omni_kv_config_value("connector_config")
|
||||
@@ -177,9 +217,10 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
finished_status: RequestStatus,
|
||||
) -> list[Request]:
|
||||
"""Finish requests and discard any incomplete KV-wait timing."""
|
||||
cleanup_ids: Iterable[str]
|
||||
if isinstance(request_ids, str):
|
||||
cleanup_ids = (request_ids,)
|
||||
finish_request_ids: str | tuple[str, ...] | None = request_ids
|
||||
finish_request_ids: str | Iterable[str] | None = request_ids
|
||||
elif request_ids is None:
|
||||
cleanup_ids = ()
|
||||
finish_request_ids = None
|
||||
@@ -306,15 +347,22 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
self._process_pending_omni_inputs(model_mode="ar")
|
||||
self._drop_aborted_queued_requests()
|
||||
self._resync_streaming_input_counter()
|
||||
|
||||
original_waiting = None
|
||||
if self._should_defer_waiting_admission():
|
||||
original_waiting = waiting
|
||||
self.waiting = create_request_queue(self.policy)
|
||||
|
||||
original_max_num_running_reqs = self.max_num_running_reqs
|
||||
async_chunk_transport = self._async_chunk_transport_enabled()
|
||||
reserved_running_slots = (
|
||||
self._get_async_chunk_reserved_running_slots() if async_chunk_transport and self.use_v2_model_runner else 0
|
||||
)
|
||||
if reserved_running_slots:
|
||||
self.max_num_running_reqs = max(0, original_max_num_running_reqs - reserved_running_slots)
|
||||
try:
|
||||
scheduler_output = super().schedule(throttle_prefills)
|
||||
finally:
|
||||
self.max_num_running_reqs = original_max_num_running_reqs
|
||||
if original_waiting is not None:
|
||||
deferred_waiting = list(self.waiting)
|
||||
if deferred_waiting:
|
||||
@@ -418,7 +466,7 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
assert num_tokens_scheduled > 0
|
||||
request = self.requests.get(req_id)
|
||||
if request is not None:
|
||||
# vLLM 0.26: settle the in-flight tokens counted in schedule().
|
||||
# Settle the in-flight tokens counted in schedule().
|
||||
# Must happen before the skips below — failed-KV-load and
|
||||
# already-finished requests were incremented too, and the two
|
||||
# readers (allocate_slots, _connector_finished) clamp with
|
||||
@@ -586,6 +634,11 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
|
||||
confirmed_num_computed_tokens = None
|
||||
boundary_generation = None
|
||||
# Capture before resumable stop handling can clear token history.
|
||||
output_token_ids: Any = getattr(request, "output_token_ids", None)
|
||||
if output_token_ids is None:
|
||||
output_token_ids = getattr(request, "_output_token_ids", ())
|
||||
num_generation_tokens = len(output_token_ids)
|
||||
if stopped:
|
||||
if self.chunk_transfer_adapter is not None:
|
||||
confirmed_num_computed_tokens = self.chunk_transfer_adapter._confirmed_num_computed_tokens(request)
|
||||
@@ -604,6 +657,8 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
is_segment_finished = not finished
|
||||
if finished:
|
||||
request.resumable = False
|
||||
if self._native_data_plane:
|
||||
self._pending_data_plane_terminal_req_ids.add(req_id)
|
||||
if not finished:
|
||||
# for streaming input request only
|
||||
if self.chunk_transfer_adapter:
|
||||
@@ -660,7 +715,18 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
|
||||
# Get prompt logprobs for this request.
|
||||
prompt_logprobs_tensors = prompt_logprobs_dict.get(req_id)
|
||||
if new_token_ids or mm_output is not None or pooler_output is not None or kv_transfer_params or stopped:
|
||||
has_stage_output = (
|
||||
bool(new_token_ids)
|
||||
or mm_output is not None
|
||||
or pooler_output is not None
|
||||
or kv_transfer_params
|
||||
or stopped
|
||||
)
|
||||
if has_stage_output and _should_emit_engine_output(
|
||||
self.vllm_config.model_config,
|
||||
stopped=stopped,
|
||||
has_control=kv_transfer_params is not None,
|
||||
):
|
||||
OmniSchedulerMixin._append_request_output(
|
||||
self,
|
||||
outputs,
|
||||
@@ -679,6 +745,7 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
num_nans_in_logits=request.num_nans_in_logits,
|
||||
is_segment_finished=is_segment_finished,
|
||||
new_prompt_len_snapshot=self._new_prompt_len_snapshot.get(req_id),
|
||||
num_generation_tokens=num_generation_tokens,
|
||||
)
|
||||
else:
|
||||
# Invariant: EngineCore returns no partial prefill outputs.
|
||||
@@ -755,9 +822,7 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
if req_id in self.waiting_for_transfer_free:
|
||||
req = self.requests.get(req_id)
|
||||
if req:
|
||||
self.kv_cache_manager.free(req)
|
||||
if req_id in self.requests:
|
||||
del self.requests[req_id]
|
||||
self._free_blocks(req)
|
||||
if req_id in self.transfer_triggered_requests:
|
||||
self.transfer_triggered_requests.remove(req_id)
|
||||
self.active_kv_transfers.discard(req_id)
|
||||
@@ -856,7 +921,8 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
# This streaming update has already been dequeued. Report the
|
||||
# permanent contract failure so the next scheduling pass
|
||||
# finishes only this request instead of crashing EngineCore.
|
||||
self.chunk_transfer_adapter.record_receive_failure(req_id, str(exc))
|
||||
if self.chunk_transfer_adapter is not None:
|
||||
self.chunk_transfer_adapter.record_receive_failure(req_id, str(exc))
|
||||
return
|
||||
if replaced is not None:
|
||||
if replaced:
|
||||
@@ -1041,7 +1107,36 @@ class OmniARScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
getattr(self, "_inflight_prefills", set()).discard(request)
|
||||
|
||||
# 1. Standard cleanup parts from base _free_request
|
||||
connector_delay_free_blocks, kv_xfer_params = self._connector_finished(request)
|
||||
status = getattr(request, "status", None)
|
||||
transfer_params = getattr(request, "kv_transfer_params", None)
|
||||
native_transfer = (
|
||||
transfer_params
|
||||
and transfer_params.get("do_remote_decode")
|
||||
and getattr(getattr(self.vllm_config, "kv_transfer_config", None), "kv_connector", None)
|
||||
== "MooncakeConnector"
|
||||
)
|
||||
if native_transfer and status == RequestStatus.FINISHED_STOPPED:
|
||||
request.status = RequestStatus.FINISHED_LENGTH_CAPPED
|
||||
num_computed_tokens = None
|
||||
if native_transfer:
|
||||
# vLLM clips the block table with
|
||||
# get_block_ids_for_computed_tokens(). Exclude Omni's optimistic
|
||||
# async output placeholders from the physical transfer boundary.
|
||||
num_computed_tokens = request.num_computed_tokens
|
||||
request.num_computed_tokens = self._get_confirmed_num_computed_tokens(request)
|
||||
try:
|
||||
connector_delay_free_blocks, kv_xfer_params = self._connector_finished(request)
|
||||
finally:
|
||||
if num_computed_tokens is not None:
|
||||
request.num_computed_tokens = num_computed_tokens
|
||||
if status is not None:
|
||||
request.status = status
|
||||
if native_transfer and connector_delay_free_blocks:
|
||||
kv_xfer_params = {
|
||||
**(kv_xfer_params or {}),
|
||||
"transfer_id": transfer_params["transfer_id"],
|
||||
"num_transfer_tokens": self._get_confirmed_num_computed_tokens(request),
|
||||
}
|
||||
|
||||
# EC Connector: mirror the KV hook (upstream v0.28 _free_request).
|
||||
# The contract requires firing before the encoder cache is freed so
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.logger import init_logger
|
||||
@@ -15,11 +15,7 @@ from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.core.sched.request_queue import create_request_queue
|
||||
from vllm.v1.core.sched.scheduler import Scheduler as VLLMScheduler
|
||||
from vllm.v1.core.sched.utils import remove_all
|
||||
from vllm.v1.engine import (
|
||||
EngineCoreEventType,
|
||||
EngineCoreOutput,
|
||||
EngineCoreOutputs,
|
||||
)
|
||||
from vllm.v1.engine import EngineCoreEventType, EngineCoreOutput, EngineCoreOutputs
|
||||
from vllm.v1.metrics.perf import PerfStats
|
||||
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
@@ -27,12 +23,33 @@ from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
from vllm_omni.core.sched.output import OmniCachedRequestData, OmniNewRequestData
|
||||
from vllm_omni.core.sched.utils import omni_routed_experts_for_request
|
||||
from vllm_omni.engine.serialization import deserialize_additional_information
|
||||
from vllm_omni.outputs import OmniModelRunnerOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.core.sched.request_queue import RequestQueue
|
||||
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _has_async_chunk_payload_to_run(request: Request) -> bool:
|
||||
additional_information = getattr(request, "additional_information", None)
|
||||
if not isinstance(additional_information, dict):
|
||||
additional_information = deserialize_additional_information(additional_information)
|
||||
|
||||
codes = additional_information.get("codes")
|
||||
audio = codes.get("audio") if isinstance(codes, dict) else additional_information.get("codes.audio")
|
||||
if audio is None:
|
||||
return False
|
||||
if hasattr(audio, "numel"):
|
||||
return bool(audio.numel())
|
||||
return bool(audio)
|
||||
|
||||
|
||||
class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
waiting: RequestQueue
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
model_config = self.vllm_config.model_config
|
||||
@@ -40,6 +57,25 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
self._retains_state_across_chunks = bool(getattr(model_config, "retains_state_across_chunks", False))
|
||||
self._pending_finish_reqs: list[Request] = []
|
||||
|
||||
def _is_done_receiving_chunks(self, request_id: str) -> bool:
|
||||
if self.chunk_transfer_adapter is not None:
|
||||
return self.chunk_transfer_adapter.is_done_receiving_chunks(request_id)
|
||||
coordinator = self.input_coordinator
|
||||
return bool(self._native_data_plane and coordinator is not None and request_id in coordinator.finished_requests)
|
||||
|
||||
def _input_execution_is_terminal(
|
||||
self,
|
||||
request_id: str,
|
||||
scheduler_output: SchedulerOutput,
|
||||
) -> bool:
|
||||
if self._native_data_plane:
|
||||
return request_id in getattr(
|
||||
scheduler_output,
|
||||
"input_terminal_req_ids",
|
||||
set(),
|
||||
)
|
||||
return self._is_done_receiving_chunks(request_id)
|
||||
|
||||
@staticmethod
|
||||
def _record_prefill_stats(request: Request) -> None:
|
||||
"""Mirror upstream first-prefill prompt accounting for generation stages.
|
||||
@@ -73,6 +109,29 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
return False
|
||||
return super()._handle_stopped_request(request)
|
||||
|
||||
def _requeue_completed_native_chunks(self) -> None:
|
||||
"""Return completed native generation chunks to the admission queue.
|
||||
|
||||
A generation batch slot belongs to one chunk, not the entire stream.
|
||||
Keep requests with outstanding output in ``running`` so their state
|
||||
cannot be reused before completion. Other live requests join the tail
|
||||
of ``waiting`` without freeing their decoder state or KV blocks.
|
||||
Preserve WAITING_FOR_CHUNK until the coordinator observes fresh input.
|
||||
Stateful codecs retain lifetime admission until their decoder state is
|
||||
released, even when no chunk is currently executing.
|
||||
"""
|
||||
if not getattr(self, "_native_data_plane", False) or self._retains_state_across_chunks:
|
||||
return
|
||||
in_flight: list[Request] = []
|
||||
for request in self.running:
|
||||
if request.num_in_flight_tokens > 0 or request.is_finished():
|
||||
in_flight.append(request)
|
||||
continue
|
||||
if request.status == RequestStatus.RUNNING:
|
||||
request.status = RequestStatus.WAITING
|
||||
self.waiting.add_request(request)
|
||||
self.running = in_flight
|
||||
|
||||
def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput:
|
||||
"""One-shot generation fast path:
|
||||
- Feed all input tokens of the request at once
|
||||
@@ -82,6 +141,7 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
"""
|
||||
|
||||
token_budget = self.max_num_scheduled_tokens
|
||||
execution_batch_size = self.max_num_running_reqs
|
||||
if self._pause_state == PauseState.PAUSED_ALL:
|
||||
token_budget = 0
|
||||
scheduled_timestamp = time.monotonic()
|
||||
@@ -102,14 +162,22 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
skipped_waiting_requests = create_request_queue(self.policy)
|
||||
req_index = 0
|
||||
self._drop_aborted_queued_requests()
|
||||
self._requeue_completed_native_chunks()
|
||||
self._process_pending_omni_inputs(model_mode="generation")
|
||||
self._drop_aborted_queued_requests()
|
||||
self._resync_streaming_input_counter()
|
||||
async_chunk_transport = self._async_chunk_transport_enabled()
|
||||
native_chunks = bool(getattr(self, "_native_data_plane", False))
|
||||
# Parking releases an execution slot, but stateful codecs retain their
|
||||
# request-owned state until completion or abort, in either runner.
|
||||
reserved_running_slots = (
|
||||
self._get_async_chunk_reserved_running_slots() if self._retains_state_across_chunks else 0
|
||||
)
|
||||
|
||||
# OMNI: Track requests that are already finished (e.g., marked by connector)
|
||||
# These should be removed from running and not scheduled
|
||||
already_finished_reqs: set[Request] = set()
|
||||
while req_index < len(self.running) and token_budget > 0:
|
||||
while req_index < len(self.running) and token_budget > 0 and len(num_scheduled_tokens) < execution_batch_size:
|
||||
request = self.running[req_index]
|
||||
# OMNI: Skip requests that are not in self.requests
|
||||
if request.request_id not in self.requests or (
|
||||
@@ -119,6 +187,12 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
req_index += 1
|
||||
continue
|
||||
|
||||
if native_chunks and request.num_in_flight_tokens > 0:
|
||||
# Overlap different streams, never two stateful chunks from
|
||||
# the same stream. Readiness remains pending for the next step.
|
||||
req_index += 1
|
||||
continue
|
||||
|
||||
num_computed_tokens = request.num_computed_tokens
|
||||
required_tokens = len(request.prompt_token_ids) - num_computed_tokens
|
||||
if not self.scheduler_config.enable_chunked_prefill and required_tokens > token_budget:
|
||||
@@ -127,12 +201,16 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
break
|
||||
# async_chunk: don't schedule placeholder tokens when no new chunk is available.
|
||||
if required_tokens <= 0:
|
||||
if self.chunk_transfer_adapter is not None and self.chunk_transfer_adapter.is_done_receiving_chunks(
|
||||
request.request_id
|
||||
):
|
||||
self._pending_finish_reqs.append(request)
|
||||
req_index += 1
|
||||
continue
|
||||
if async_chunk_transport and self._is_done_receiving_chunks(request.request_id):
|
||||
if len(request.prompt_token_ids) == 0 and _has_async_chunk_payload_to_run(request):
|
||||
required_tokens = 1
|
||||
else:
|
||||
self._pending_finish_reqs.append(request)
|
||||
req_index += 1
|
||||
continue
|
||||
else:
|
||||
req_index += 1
|
||||
continue
|
||||
num_new_tokens = min(required_tokens, token_budget)
|
||||
new_blocks = self.kv_cache_manager.allocate_slots(
|
||||
request,
|
||||
@@ -161,20 +239,27 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
if already_finished_reqs:
|
||||
self.running = remove_all(self.running, already_finished_reqs)
|
||||
|
||||
# Fast path selection and scheduling for one-shot generation requests,
|
||||
# independent of pooling_params.
|
||||
while self.waiting and token_budget > 0 and self._pause_state == PauseState.UNPAUSED:
|
||||
# Requests waiting for their next chunk are temporarily absent
|
||||
# from `running`, but stateful models still retain their model
|
||||
# runner slot. Mirror vLLM's treatment of
|
||||
# `num_waiting_for_streaming_input` when enforcing max_num_seqs.
|
||||
num_running = len(self.running)
|
||||
if self._retains_state_across_chunks and self.chunk_transfer_adapter is not None:
|
||||
num_running += self.chunk_transfer_adapter.num_running_waiting_for_chunk
|
||||
if num_running >= self.max_num_running_reqs:
|
||||
break
|
||||
|
||||
# Fast path selection and scheduling (treat all as diffusion requests,
|
||||
# independent of pooling_params)
|
||||
while (
|
||||
self.waiting
|
||||
and token_budget > 0
|
||||
and len(num_scheduled_tokens) < execution_batch_size
|
||||
and (
|
||||
len(num_scheduled_tokens)
|
||||
if native_chunks and not self._retains_state_across_chunks
|
||||
else len(self.running) + reserved_running_slots
|
||||
)
|
||||
< self.max_num_running_reqs
|
||||
and self._pause_state == PauseState.UNPAUSED
|
||||
):
|
||||
request = self.waiting.peek_request()
|
||||
if native_chunks and request.num_in_flight_tokens > 0:
|
||||
# A restored waiting entry can still own an outstanding batch.
|
||||
# Do not let it block other ready streams or execute it twice.
|
||||
self.waiting.pop_request()
|
||||
skipped_waiting_requests.add_request(request)
|
||||
continue
|
||||
# OMNI: Skip requests that are not in self.requests
|
||||
if request.request_id not in self.requests or (
|
||||
self.chunk_transfer_adapter is None and request.status == RequestStatus.FINISHED_STOPPED
|
||||
@@ -184,11 +269,12 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
continue
|
||||
|
||||
# async_chunk: wait for the first upstream chunk (don't start with placeholders).
|
||||
if self.chunk_transfer_adapter is not None and len(request.prompt_token_ids) == 0:
|
||||
if self.chunk_transfer_adapter.is_done_receiving_chunks(request.request_id):
|
||||
self.waiting.pop_request()
|
||||
self._pending_finish_reqs.append(request)
|
||||
continue
|
||||
if async_chunk_transport and len(request.prompt_token_ids) == 0:
|
||||
if self._is_done_receiving_chunks(request.request_id):
|
||||
if not _has_async_chunk_payload_to_run(request):
|
||||
self.waiting.pop_request()
|
||||
self._pending_finish_reqs.append(request)
|
||||
continue
|
||||
else:
|
||||
self.waiting.pop_request()
|
||||
skipped_waiting_requests.prepend_request(request)
|
||||
@@ -197,6 +283,22 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
# Allocate all input tokens for the request in one shot
|
||||
# (allocate 1 placeholder if zero)
|
||||
required_tokens = max(len(request.prompt_token_ids), 1)
|
||||
if native_chunks:
|
||||
required_tokens = len(request.prompt_token_ids) - request.num_computed_tokens
|
||||
if required_tokens <= 0:
|
||||
if (
|
||||
self._is_done_receiving_chunks(request.request_id)
|
||||
and not request.prompt_token_ids
|
||||
and _has_async_chunk_payload_to_run(request)
|
||||
):
|
||||
required_tokens = 1
|
||||
else:
|
||||
self.waiting.pop_request()
|
||||
if self._is_done_receiving_chunks(request.request_id):
|
||||
self._pending_finish_reqs.append(request)
|
||||
else:
|
||||
skipped_waiting_requests.add_request(request)
|
||||
continue
|
||||
num_new_tokens = min(required_tokens, token_budget)
|
||||
new_blocks = self.kv_cache_manager.allocate_slots(
|
||||
request,
|
||||
@@ -229,7 +331,7 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
|
||||
# If fast path scheduled none, fall back to the original scheduling
|
||||
if not num_scheduled_tokens:
|
||||
if self.chunk_transfer_adapter:
|
||||
if async_chunk_transport:
|
||||
# Don't fall back: base scheduler doesn't handle async_chunk
|
||||
# requests with empty prompt_token_ids.
|
||||
self._restore_omni_wait_queues()
|
||||
@@ -245,7 +347,7 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
any_request = self.running[0]
|
||||
num_common_prefix_blocks = self.kv_cache_manager.get_num_common_prefix_blocks(any_request.request_id)
|
||||
|
||||
# Assemble SchedulerOutput (align with v0.14.0)
|
||||
# Assemble the current SchedulerOutput contract.
|
||||
if self.use_v2_model_runner:
|
||||
# No resumed reqs in fast path; pass prefill_token_ids for new reqs.
|
||||
new_reqs_data = [
|
||||
@@ -284,7 +386,7 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
|
||||
total_num_scheduled_tokens = sum(num_scheduled_tokens.values())
|
||||
|
||||
# Record the request ids scheduled in this step (v0.14.0 behavior).
|
||||
# Record request ids scheduled in this step for the next update.
|
||||
self.prev_step_scheduled_req_ids.clear()
|
||||
self.prev_step_scheduled_req_ids.update(num_scheduled_tokens.keys())
|
||||
|
||||
@@ -404,7 +506,7 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
assert num_tokens_scheduled > 0
|
||||
request = self.requests.get(req_id)
|
||||
if request is not None:
|
||||
# vLLM 0.26: settle the in-flight tokens counted in schedule().
|
||||
# Settle the in-flight tokens counted in schedule().
|
||||
# Must happen before the skips below — failed-KV-load and
|
||||
# already-finished requests were incremented too, and the two
|
||||
# readers (allocate_slots, _connector_finished) clamp with
|
||||
@@ -496,10 +598,16 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
if (
|
||||
request.status == RequestStatus.FINISHED_ERROR
|
||||
or request.status == RequestStatus.FINISHED_STOPPED
|
||||
or (self.chunk_transfer_adapter is None and request.num_computed_tokens >= request.num_prompt_tokens)
|
||||
or (
|
||||
self.chunk_transfer_adapter is not None
|
||||
and self.chunk_transfer_adapter.is_done_receiving_chunks(request.request_id)
|
||||
not self._async_chunk_transport_enabled()
|
||||
and request.num_computed_tokens >= request.num_prompt_tokens
|
||||
)
|
||||
or (
|
||||
self._async_chunk_transport_enabled()
|
||||
and self._input_execution_is_terminal(
|
||||
request.request_id,
|
||||
scheduler_output,
|
||||
)
|
||||
and request.num_computed_tokens >= len(request.prompt_token_ids)
|
||||
)
|
||||
):
|
||||
@@ -526,6 +634,8 @@ class OmniGenerationScheduler(OmniSchedulerMixin, VLLMScheduler):
|
||||
finish_reason = request.get_finished_reason()
|
||||
finished = self._handle_stopped_request(request)
|
||||
is_segment_finished = not finished
|
||||
if finished and self._native_data_plane:
|
||||
self._pending_data_plane_terminal_req_ids.add(req_id)
|
||||
if not finished:
|
||||
# for streaming input request only
|
||||
if self.chunk_transfer_adapter:
|
||||
|
||||
@@ -5,17 +5,20 @@ from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import queue
|
||||
import time
|
||||
from collections.abc import Iterable, Iterator
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.kv_events import KVEventBatch
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.core.sched.request_queue import RequestQueue
|
||||
from vllm.v1.core.sched.utils import remove_all
|
||||
from vllm.v1.engine import (
|
||||
EngineCoreEventType,
|
||||
@@ -31,6 +34,7 @@ from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
from vllm_omni.core.sched.omni_scheduling_coordinator import (
|
||||
OmniSchedulingCoordinator,
|
||||
uses_full_payload_input_coordinator,
|
||||
uses_native_mrv2_data_plane,
|
||||
)
|
||||
from vllm_omni.core.sched.output import (
|
||||
OmniChunkRecvHandle,
|
||||
@@ -41,6 +45,8 @@ from vllm_omni.distributed.omni_connectors.transfer_adapter.chunk_transfer_adapt
|
||||
OmniChunkTransferAdapter,
|
||||
)
|
||||
from vllm_omni.engine import OmniEngineCoreOutput
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
from vllm_omni.outputs import OmniConnectorOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -101,6 +107,19 @@ elif DEFAULT_INPUT_WAIT_TIMEOUT_S == 0:
|
||||
class OmniSchedulerMixin:
|
||||
"""Shared scheduler helpers for omni-specific request handling."""
|
||||
|
||||
# Provided by the concrete vLLM scheduler.
|
||||
vllm_config: VllmConfig
|
||||
requests: dict[str, Request]
|
||||
waiting: RequestQueue
|
||||
running: list[Request]
|
||||
|
||||
def _init_omni_connector_output_inbox(self) -> None:
|
||||
self._omni_connector_output_inbox: queue.SimpleQueue[OmniConnectorOutput] = queue.SimpleQueue()
|
||||
|
||||
def enqueue_omni_connector_output(self, output: OmniConnectorOutput) -> None:
|
||||
"""Accept a lightweight readiness event from the local runner thread."""
|
||||
self._omni_connector_output_inbox.put(output)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Shared scheduler/output helpers (lift the AR / generation duplicates)
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -119,15 +138,30 @@ class OmniSchedulerMixin:
|
||||
self.use_v2_model_runner = False
|
||||
|
||||
model_config = self.vllm_config.model_config
|
||||
self.chunk_transfer_adapter = (
|
||||
OmniChunkTransferAdapter(self.vllm_config) if getattr(model_config, "async_chunk", False) else None
|
||||
self.use_v2_model_runner = bool(getattr(model_config, "use_v2_model_runner", False))
|
||||
self._native_data_plane = uses_native_mrv2_data_plane(
|
||||
model_config,
|
||||
use_v2_model_runner=self.use_v2_model_runner,
|
||||
)
|
||||
self.input_coordinator = (
|
||||
OmniSchedulingCoordinator(stage_id=getattr(model_config, "stage_id", 0))
|
||||
if uses_full_payload_input_coordinator(model_config)
|
||||
self.chunk_transfer_adapter = (
|
||||
OmniChunkTransferAdapter(self.vllm_config)
|
||||
if getattr(model_config, "async_chunk", False) and not self._native_data_plane
|
||||
else None
|
||||
)
|
||||
self._latest_omni_connector_output = None
|
||||
self.input_coordinator: OmniSchedulingCoordinator | None = None
|
||||
if self._native_data_plane:
|
||||
self.input_coordinator = OmniSchedulingCoordinator(
|
||||
scheduler_max_num_seqs=self.vllm_config.scheduler_config.max_num_seqs,
|
||||
stage_id=getattr(model_config, "stage_id", 0),
|
||||
async_chunk=True,
|
||||
)
|
||||
elif uses_full_payload_input_coordinator(model_config):
|
||||
self.input_coordinator = OmniSchedulingCoordinator(
|
||||
stage_id=getattr(model_config, "stage_id", 0),
|
||||
)
|
||||
self._latest_omni_connector_output: OmniConnectorOutput | None = None
|
||||
self._init_omni_connector_output_inbox()
|
||||
self._pending_data_plane_terminal_req_ids: set[str] = set()
|
||||
# Optional per-stage pooling-output decoder hook (dotted path in
|
||||
# model_config); applied worker-side before IPC.
|
||||
self._pooling_output_decoder = None
|
||||
@@ -214,6 +248,35 @@ class OmniSchedulerMixin:
|
||||
session.num_prompt_tokens = len(new_prompt)
|
||||
self._finish_streaming_session_update(session, update)
|
||||
|
||||
def _async_chunk_transport_enabled(self) -> bool:
|
||||
return getattr(self, "chunk_transfer_adapter", None) is not None or bool(
|
||||
getattr(self, "_native_data_plane", False)
|
||||
)
|
||||
|
||||
def _get_async_chunk_reserved_running_slots(self) -> int:
|
||||
adapter = getattr(self, "chunk_transfer_adapter", None)
|
||||
live_requests = self.requests
|
||||
reserved_ids: set[str] = set()
|
||||
if adapter is not None:
|
||||
parked = getattr(adapter, "waiting_for_chunk_running_requests", ())
|
||||
held = getattr(adapter, "_held_non_active", ())
|
||||
else:
|
||||
coordinator = getattr(self, "input_coordinator", None)
|
||||
parked = getattr(coordinator, "_waiting_for_chunk_running", ())
|
||||
held = ()
|
||||
for request in parked:
|
||||
req_id = getattr(request, "request_id", None)
|
||||
if req_id is not None and req_id in live_requests:
|
||||
reserved_ids.add(req_id)
|
||||
for request in held:
|
||||
req_id = getattr(request, "request_id", None)
|
||||
if req_id is not None and req_id in live_requests:
|
||||
reserved_ids.add(req_id)
|
||||
return len(reserved_ids)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Shared scheduler/output helpers (lift the AR / generation duplicates)
|
||||
# ------------------------------------------------------------------ #
|
||||
def _release_replaced_streaming_prompt_cache(self, session: Request) -> None:
|
||||
"""Discard cache state that belongs to a replaced prompt."""
|
||||
# A prompt replacement is not a normal streaming extension: none of
|
||||
@@ -259,19 +322,55 @@ class OmniSchedulerMixin:
|
||||
AR and generation schedulers except for the ``model_mode`` argument
|
||||
forwarded to ``update_request_metadata``.
|
||||
"""
|
||||
connector_outputs: list[OmniConnectorOutput] = []
|
||||
inbox = getattr(self, "_omni_connector_output_inbox", None)
|
||||
if inbox is not None:
|
||||
while True:
|
||||
try:
|
||||
connector_outputs.append(inbox.get_nowait())
|
||||
except queue.Empty:
|
||||
break
|
||||
connector_output = getattr(self, "_latest_omni_connector_output", None)
|
||||
self._latest_omni_connector_output = None
|
||||
if connector_output is not None:
|
||||
connector_outputs.append(connector_output)
|
||||
input_coordinator = getattr(self, "input_coordinator", None)
|
||||
if input_coordinator is None:
|
||||
return
|
||||
if connector_output and connector_output.request_metadata:
|
||||
request_metadata: dict[str, dict[str, Any]] = {}
|
||||
chunk_ready_req_ids: set[str] = set()
|
||||
chunk_finished_req_ids: set[str] = set()
|
||||
stage_recv_req_ids: set[str] = set()
|
||||
for output in connector_outputs:
|
||||
request_metadata.update(output.request_metadata)
|
||||
chunk_ready_req_ids.update(output.chunk_ready_req_ids)
|
||||
chunk_finished_req_ids.update(output.chunk_finished_req_ids)
|
||||
stage_recv_req_ids.update(output.stage_recv_req_ids)
|
||||
live_request_ids = self.requests.keys()
|
||||
request_metadata = {
|
||||
req_id: metadata for req_id, metadata in request_metadata.items() if req_id in live_request_ids
|
||||
}
|
||||
chunk_ready_req_ids.intersection_update(live_request_ids)
|
||||
chunk_finished_req_ids.intersection_update(live_request_ids)
|
||||
stage_recv_req_ids.intersection_update(live_request_ids)
|
||||
if request_metadata:
|
||||
input_coordinator.update_request_metadata(
|
||||
self.requests, connector_output.request_metadata, model_mode=model_mode
|
||||
self.requests,
|
||||
request_metadata,
|
||||
model_mode=model_mode,
|
||||
)
|
||||
if input_coordinator._async_chunk:
|
||||
input_coordinator.process_pending_chunks(
|
||||
self.waiting,
|
||||
self.running,
|
||||
chunk_ready_req_ids,
|
||||
chunk_finished_req_ids,
|
||||
)
|
||||
else:
|
||||
input_coordinator.process_pending_full_payload_inputs(
|
||||
self.waiting,
|
||||
stage_recv_req_ids,
|
||||
)
|
||||
input_coordinator.process_pending_full_payload_inputs(
|
||||
self.waiting,
|
||||
connector_output.stage_recv_req_ids if connector_output else set(),
|
||||
)
|
||||
|
||||
def _process_pending_omni_inputs(self, model_mode: str) -> None:
|
||||
"""Apply pending connector inputs, timeouts, and async chunks."""
|
||||
@@ -316,7 +415,7 @@ class OmniSchedulerMixin:
|
||||
scheduler_requests=self.requests,
|
||||
)
|
||||
if self.input_coordinator:
|
||||
self.input_coordinator.restore_queues(self.waiting)
|
||||
self.input_coordinator.restore_queues(self.waiting, self.running)
|
||||
|
||||
def _process_pending_input_timeouts(self) -> None:
|
||||
"""Force-fail requests waiting on the full-payload coordinator too long.
|
||||
@@ -458,6 +557,8 @@ class OmniSchedulerMixin:
|
||||
*,
|
||||
finished_requests_needing_kv_transfer: dict | None = None,
|
||||
pending_input_registrations: list[OmniChunkRecvHandle] | None = None,
|
||||
data_plane_terminal_req_ids: set[str] | None = None,
|
||||
input_terminal_req_ids: set[str] | None = None,
|
||||
) -> OmniSchedulerOutput:
|
||||
"""Wrap a base ``SchedulerOutput`` in ``OmniSchedulerOutput``.
|
||||
|
||||
@@ -468,11 +569,31 @@ class OmniSchedulerMixin:
|
||||
base_data = {name: getattr(base, name) for name in SchedulerOutput.__dataclass_fields__}
|
||||
input_coordinator = getattr(self, "input_coordinator", None)
|
||||
if pending_input_registrations is None:
|
||||
pending_input_registrations = input_coordinator.pending_input_registrations if input_coordinator else []
|
||||
if input_coordinator is None:
|
||||
pending_input_registrations = []
|
||||
elif input_coordinator._async_chunk:
|
||||
pending_input_registrations = input_coordinator.pending_chunk_registrations
|
||||
else:
|
||||
pending_input_registrations = input_coordinator.pending_input_registrations
|
||||
if data_plane_terminal_req_ids is None:
|
||||
pending_terminal: set[str] = getattr(self, "_pending_data_plane_terminal_req_ids", set())
|
||||
data_plane_terminal_req_ids = set(pending_terminal)
|
||||
pending_terminal.clear()
|
||||
if input_coordinator is not None:
|
||||
scheduled_terminal_req_ids = input_coordinator.get_scheduled_input_terminal_req_ids(base)
|
||||
if input_terminal_req_ids is None:
|
||||
input_terminal_req_ids = scheduled_terminal_req_ids
|
||||
else:
|
||||
input_terminal_req_ids = set(input_terminal_req_ids).union(
|
||||
scheduled_terminal_req_ids,
|
||||
)
|
||||
input_coordinator.postprocess_scheduler_output(base)
|
||||
return OmniSchedulerOutput(
|
||||
**base_data,
|
||||
finished_requests_needing_kv_transfer=finished_requests_needing_kv_transfer or {},
|
||||
pending_input_registrations=pending_input_registrations,
|
||||
data_plane_terminal_req_ids=data_plane_terminal_req_ids,
|
||||
input_terminal_req_ids=input_terminal_req_ids or set(),
|
||||
)
|
||||
|
||||
def _rewrap_scheduled_new_reqs(self, scheduler_output: SchedulerOutput) -> None:
|
||||
@@ -520,8 +641,14 @@ class OmniSchedulerMixin:
|
||||
num_nans_in_logits: int = 0,
|
||||
is_segment_finished: bool | None = False,
|
||||
new_prompt_len_snapshot: int | None = None,
|
||||
num_generation_tokens: int | None = None,
|
||||
) -> OmniEngineCoreOutput:
|
||||
"""Build the common request-output envelope used by LLM schedulers."""
|
||||
pooling_output_payload = None
|
||||
if isinstance(pooling_output, dict):
|
||||
pooling_output_payload = serialize_additional_information(pooling_output)
|
||||
pooling_output = None
|
||||
|
||||
return OmniEngineCoreOutput(
|
||||
request_id=request.request_id,
|
||||
new_token_ids=new_token_ids,
|
||||
@@ -529,6 +656,7 @@ class OmniSchedulerMixin:
|
||||
new_logprobs=new_logprobs,
|
||||
new_prompt_logprobs_tensors=new_prompt_logprobs_tensors,
|
||||
pooling_output=pooling_output,
|
||||
pooling_output_payload=pooling_output_payload,
|
||||
multimodal_output=multimodal_output,
|
||||
stop_reason=stop_reason,
|
||||
events=request.take_events(),
|
||||
@@ -540,6 +668,7 @@ class OmniSchedulerMixin:
|
||||
num_nans_in_logits=num_nans_in_logits,
|
||||
is_segment_finished=is_segment_finished,
|
||||
new_prompt_len_snapshot=new_prompt_len_snapshot,
|
||||
num_generation_tokens=num_generation_tokens,
|
||||
)
|
||||
|
||||
def _append_request_output(
|
||||
@@ -953,10 +1082,10 @@ class OmniSchedulerMixin:
|
||||
self.running[:] = [req for req in self.running if keep_running(req)]
|
||||
|
||||
def _drop_aborted_queued_requests(self) -> None:
|
||||
for queue in (self.waiting, self.skipped_waiting):
|
||||
aborted = [req for req in queue if req.status == RequestStatus.FINISHED_ABORTED]
|
||||
for request_queue in (self.waiting, self.skipped_waiting):
|
||||
aborted = [req for req in request_queue if req.status == RequestStatus.FINISHED_ABORTED]
|
||||
if aborted:
|
||||
queue.remove_requests(aborted)
|
||||
request_queue.remove_requests(aborted)
|
||||
self.running[:] = [req for req in self.running if req.status != RequestStatus.FINISHED_ABORTED]
|
||||
|
||||
def _resync_streaming_input_counter(self) -> None:
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Scheduling-side coordination for full_payload input waiting.
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Scheduling-side coordination for chunk and full-payload input waiting.
|
||||
|
||||
Manages WAITING_FOR_INPUT state transitions based on readiness signals
|
||||
from OmniConnectorOutput, without ever calling connector.put()/get().
|
||||
|
||||
Chunk waiting (WAITING_FOR_CHUNK) lives on OmniChunkTransferAdapter.
|
||||
Manages WAITING_FOR_CHUNK and WAITING_FOR_INPUT state transitions based on
|
||||
readiness signals from OmniConnectorOutput, without calling connector I/O.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +20,18 @@ from vllm_omni.core.sched.output import OmniChunkRecvHandle
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def uses_native_mrv2_data_plane(
|
||||
model_config: Any,
|
||||
*,
|
||||
use_v2_model_runner: bool,
|
||||
) -> bool:
|
||||
return bool(
|
||||
use_v2_model_runner
|
||||
and getattr(model_config, "async_chunk", False)
|
||||
and getattr(model_config, "supports_native_mrv2_data_plane", False)
|
||||
)
|
||||
|
||||
|
||||
def uses_full_payload_input_coordinator(model_config: Any) -> bool:
|
||||
"""Returns True if this stage parks pending requests in
|
||||
WAITING_FOR_INPUT awaiting a full_payload delivery on the worker connector.
|
||||
@@ -38,7 +48,7 @@ def uses_full_payload_input_coordinator(model_config: Any) -> bool:
|
||||
|
||||
|
||||
class OmniSchedulingCoordinator:
|
||||
"""Pure-scheduling coordinator for full_payload input waiting.
|
||||
"""Pure-scheduling coordinator for chunk and full-payload input waiting.
|
||||
|
||||
The Scheduler owns an instance of this class. It consumes readiness
|
||||
signals produced by the Model Runner's ``OmniConnectorModelRunnerMixin``
|
||||
@@ -46,12 +56,28 @@ class OmniSchedulingCoordinator:
|
||||
transitions accordingly.
|
||||
"""
|
||||
|
||||
def __init__(self, stage_id: int = 0):
|
||||
def __init__(
|
||||
self,
|
||||
scheduler_max_num_seqs: int = 0,
|
||||
stage_id: int = 0,
|
||||
async_chunk: bool = False,
|
||||
) -> None:
|
||||
self._stage_id = stage_id
|
||||
self._scheduler_max_num_seqs = scheduler_max_num_seqs
|
||||
self._async_chunk = async_chunk
|
||||
|
||||
self.finished_requests: set[str] = set()
|
||||
self.requests_with_ready_chunks: set[str] = set()
|
||||
self.input_terminal_req_ids: set[str] = set()
|
||||
self._full_payload_input_received: set[str] = set()
|
||||
|
||||
self._waiting_for_chunk_waiting: deque[Any] = deque()
|
||||
self._waiting_for_chunk_running: deque[Any] = deque()
|
||||
|
||||
# Request IDs that were newly registered for chunk recv this cycle.
|
||||
# The engine/Model Runner should call register_chunk_recv() for these
|
||||
# so the bg thread starts polling.
|
||||
self.pending_chunk_registrations: list[OmniChunkRecvHandle] = []
|
||||
# Requests waiting for full_payload stage input (WAITING_FOR_INPUT).
|
||||
self._waiting_for_input: deque[Any] = deque()
|
||||
# Per-cycle list of minimal handles to ship to the model runner so it
|
||||
@@ -69,6 +95,47 @@ class OmniSchedulingCoordinator:
|
||||
# Core scheduling methods
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def process_pending_chunks(
|
||||
self,
|
||||
waiting_queue: Any,
|
||||
running_queue: list[Request],
|
||||
chunk_ready_req_ids: set[str],
|
||||
chunk_finished_req_ids: set[str],
|
||||
) -> None:
|
||||
"""Transition requests whose chunks have arrived.
|
||||
|
||||
Args:
|
||||
waiting_queue: Scheduler's waiting request queue.
|
||||
running_queue: Scheduler's running request list.
|
||||
chunk_ready_req_ids: IDs with a newly arrived chunk this cycle.
|
||||
chunk_finished_req_ids: IDs whose final chunk has arrived.
|
||||
"""
|
||||
if self._stage_id == 0 or not self._async_chunk:
|
||||
return
|
||||
|
||||
self.finished_requests.update(chunk_finished_req_ids)
|
||||
self.pending_chunk_registrations = []
|
||||
|
||||
self._process_chunk_queue(
|
||||
waiting_queue,
|
||||
self._waiting_for_chunk_waiting,
|
||||
RequestStatus.WAITING,
|
||||
chunk_ready_req_ids,
|
||||
)
|
||||
self._process_chunk_queue(
|
||||
running_queue,
|
||||
self._waiting_for_chunk_running,
|
||||
RequestStatus.RUNNING,
|
||||
chunk_ready_req_ids,
|
||||
)
|
||||
while len(running_queue) > self._scheduler_max_num_seqs:
|
||||
request = running_queue.pop()
|
||||
# Must reset status to WAITING so the scheduler treats it as
|
||||
# schedulable work. KV blocks are NOT freed here (unlike a
|
||||
# real preemption), so PREEMPTED would be incorrect.
|
||||
request.status = RequestStatus.WAITING
|
||||
waiting_queue.prepend_requests([request])
|
||||
|
||||
def process_pending_full_payload_inputs(
|
||||
self,
|
||||
waiting_queue: Any,
|
||||
@@ -144,10 +211,29 @@ class OmniSchedulingCoordinator:
|
||||
waiting_queue.remove_requests(to_remove)
|
||||
|
||||
def free_finished_request(self, request_id: str) -> None:
|
||||
"""Prune internal tracking sets for a freed request to prevent unbounded growth."""
|
||||
"""Prune all coordinator state owned by a freed request."""
|
||||
self._full_payload_input_received.discard(request_id)
|
||||
self.finished_requests.discard(request_id)
|
||||
self.requests_with_ready_chunks.discard(request_id)
|
||||
self.input_terminal_req_ids.discard(request_id)
|
||||
self._waiting_since.pop(request_id, None)
|
||||
for queue_attr in (
|
||||
"_waiting_for_chunk_waiting",
|
||||
"_waiting_for_chunk_running",
|
||||
"_waiting_for_input",
|
||||
):
|
||||
queue = getattr(self, queue_attr)
|
||||
setattr(
|
||||
self,
|
||||
queue_attr,
|
||||
deque(request for request in queue if request.request_id != request_id),
|
||||
)
|
||||
self.pending_chunk_registrations = [
|
||||
handle for handle in self.pending_chunk_registrations if handle.request_id != request_id
|
||||
]
|
||||
self.pending_input_registrations = [
|
||||
handle for handle in self.pending_input_registrations if handle.request_id != request_id
|
||||
]
|
||||
|
||||
def collect_timed_out_request_ids(
|
||||
self,
|
||||
@@ -178,11 +264,14 @@ class OmniSchedulingCoordinator:
|
||||
|
||||
# Defensively remove from coordinator internal queues (may already
|
||||
# be empty if restore_queues() has run).
|
||||
remaining: deque[Any] = deque()
|
||||
for request in self._waiting_for_input:
|
||||
if request.request_id not in timed_out_ids:
|
||||
remaining.append(request)
|
||||
self._waiting_for_input = remaining
|
||||
for queue_attr in (
|
||||
"_waiting_for_chunk_waiting",
|
||||
"_waiting_for_chunk_running",
|
||||
"_waiting_for_input",
|
||||
):
|
||||
queue = getattr(self, queue_attr)
|
||||
remaining = deque(request for request in queue if request.request_id not in timed_out_ids)
|
||||
setattr(self, queue_attr, remaining)
|
||||
|
||||
for req_id in timed_out_ids:
|
||||
self._waiting_since.pop(req_id, None)
|
||||
@@ -198,8 +287,17 @@ class OmniSchedulingCoordinator:
|
||||
def restore_queues(
|
||||
self,
|
||||
waiting_queue: Any,
|
||||
running_queue: list[Request] | None = None,
|
||||
) -> None:
|
||||
"""Return waiting-for-input requests to the waiting queue."""
|
||||
"""Return waiting-for-chunk/input requests to scheduling queues."""
|
||||
for request in self._waiting_for_chunk_waiting:
|
||||
waiting_queue.add_request(request)
|
||||
self._waiting_for_chunk_waiting = deque()
|
||||
|
||||
if running_queue is not None and self._waiting_for_chunk_running:
|
||||
running_queue.extend(self._waiting_for_chunk_running)
|
||||
self._waiting_for_chunk_running = deque()
|
||||
|
||||
for request in self._waiting_for_input:
|
||||
waiting_queue.add_request(request)
|
||||
self._waiting_for_input = deque()
|
||||
@@ -247,6 +345,9 @@ class OmniSchedulingCoordinator:
|
||||
if request is None:
|
||||
continue
|
||||
|
||||
if metadata.get("input_terminal") is True:
|
||||
self.input_terminal_req_ids.add(req_id)
|
||||
|
||||
# Handle next_stage_prompt_len if present (for models like Qwen3-Omni).
|
||||
# Only apply when the request has not started decoding yet
|
||||
# (no output tokens). Resetting a mid-decode request would
|
||||
@@ -255,8 +356,7 @@ class OmniSchedulingCoordinator:
|
||||
next_len = metadata["next_stage_prompt_len"]
|
||||
if isinstance(next_len, int) and next_len > 0:
|
||||
output_token_ids = getattr(request, "_output_token_ids", None)
|
||||
has_decode_output = output_token_ids is not None and len(output_token_ids) > 0
|
||||
if has_decode_output:
|
||||
if output_token_ids is not None and len(output_token_ids) > 0:
|
||||
logger.debug(
|
||||
"[Coordinator stage-%s] Skipping prompt resize for req %s: "
|
||||
"request already has %s output tokens",
|
||||
@@ -284,6 +384,12 @@ class OmniSchedulingCoordinator:
|
||||
|
||||
if model_mode != "ar":
|
||||
new_ids = self._flatten_prompt_token_ids(metadata.get("code_predictor_codes"))
|
||||
runtime_seed = None
|
||||
if "left_context_size" in metadata:
|
||||
runtime_seed = {
|
||||
"meta": {"left_context_size": metadata["left_context_size"]},
|
||||
}
|
||||
request._omni_initial_model_buffer = runtime_seed
|
||||
if new_ids:
|
||||
request.prompt_token_ids = new_ids
|
||||
request.num_prompt_tokens = len(new_ids)
|
||||
@@ -291,3 +397,103 @@ class OmniSchedulingCoordinator:
|
||||
request._all_token_ids.extend(new_ids)
|
||||
request._output_token_ids.clear()
|
||||
request.num_computed_tokens = 0
|
||||
|
||||
def postprocess_scheduler_output(
|
||||
self,
|
||||
scheduler_output: Any,
|
||||
requests: dict[str, Request] | None = None,
|
||||
) -> None:
|
||||
"""Clear per-cycle ready state after scheduler output is materialized."""
|
||||
self._clear_chunk_ready(scheduler_output)
|
||||
self.input_terminal_req_ids.difference_update(
|
||||
self._scheduled_request_ids(scheduler_output),
|
||||
)
|
||||
|
||||
def get_scheduled_input_terminal_req_ids(
|
||||
self,
|
||||
scheduler_output: Any,
|
||||
) -> set[str]:
|
||||
"""Return terminal inputs executed by this immutable scheduler step."""
|
||||
return self.input_terminal_req_ids.intersection(
|
||||
self._scheduled_request_ids(scheduler_output),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _scheduled_request_ids(scheduler_output: Any) -> set[str]:
|
||||
num_scheduled_tokens = getattr(
|
||||
scheduler_output,
|
||||
"num_scheduled_tokens",
|
||||
None,
|
||||
)
|
||||
if num_scheduled_tokens is not None:
|
||||
return set(num_scheduled_tokens)
|
||||
|
||||
request_ids = {req.req_id for req in getattr(scheduler_output, "scheduled_new_reqs", ())}
|
||||
cached_reqs = getattr(scheduler_output, "scheduled_cached_reqs", None)
|
||||
request_ids.update(getattr(cached_reqs, "req_ids", ()))
|
||||
return request_ids
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _process_chunk_queue(
|
||||
self,
|
||||
queue: Any,
|
||||
waiting_for_chunk_list: deque[Any],
|
||||
target_status: RequestStatus,
|
||||
chunk_ready_req_ids: set[str],
|
||||
) -> None:
|
||||
queue_snapshot = list(queue)
|
||||
for request in queue_snapshot:
|
||||
request_can_run = self._request_can_run(request, chunk_ready_req_ids)
|
||||
if request.status != RequestStatus.WAITING_FOR_CHUNK:
|
||||
if request_can_run:
|
||||
if request.request_id in chunk_ready_req_ids:
|
||||
self.requests_with_ready_chunks.add(request.request_id)
|
||||
continue
|
||||
if request.status == RequestStatus.WAITING_FOR_INPUT:
|
||||
continue
|
||||
self.pending_chunk_registrations.append(
|
||||
OmniChunkRecvHandle(
|
||||
request_id=request.request_id,
|
||||
external_req_id=getattr(request, "external_req_id", None),
|
||||
)
|
||||
)
|
||||
request.status = RequestStatus.WAITING_FOR_CHUNK
|
||||
self._waiting_since.setdefault(request.request_id, time.monotonic())
|
||||
else:
|
||||
if request_can_run:
|
||||
request.status = target_status
|
||||
if request.request_id in chunk_ready_req_ids:
|
||||
self.requests_with_ready_chunks.add(request.request_id)
|
||||
self._waiting_since.pop(request.request_id, None)
|
||||
continue
|
||||
if isinstance(queue, list):
|
||||
queue.remove(request)
|
||||
else:
|
||||
queue.remove_request(request)
|
||||
waiting_for_chunk_list.append(request)
|
||||
|
||||
def _request_can_run(
|
||||
self,
|
||||
request: Request,
|
||||
chunk_ready_req_ids: set[str],
|
||||
) -> bool:
|
||||
req_id = request.request_id
|
||||
if req_id in self.finished_requests:
|
||||
# Admit the final payload or terminal marker for cleanup.
|
||||
return True
|
||||
|
||||
return req_id in chunk_ready_req_ids or req_id in self.requests_with_ready_chunks
|
||||
|
||||
def _clear_chunk_ready(self, scheduler_output: Any) -> None:
|
||||
if scheduler_output.scheduled_new_reqs:
|
||||
for req_data in scheduler_output.scheduled_new_reqs:
|
||||
req_id = getattr(req_data, "req_id", None)
|
||||
if req_id is not None:
|
||||
self.requests_with_ready_chunks.discard(req_id)
|
||||
|
||||
if scheduler_output.scheduled_cached_reqs:
|
||||
for req_id in scheduler_output.scheduled_cached_reqs.req_ids:
|
||||
self.requests_with_ready_chunks.discard(req_id)
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from dataclasses import dataclass, field, fields
|
||||
|
||||
from vllm.v1.core.sched.output import CachedRequestData, NewRequestData, SchedulerOutput
|
||||
@@ -18,14 +21,14 @@ class OmniNewRequestData(NewRequestData):
|
||||
|
||||
Args:
|
||||
external_req_id: Optional external request ID for tracking
|
||||
additional_information: Optional serialized additional information
|
||||
additional_information: Optional serialized or materialized additional information
|
||||
dictionary containing tensors or lists
|
||||
model_intermediate_buffer: Optional runner-owned payload for
|
||||
GPUModelRunner.model_intermediate_buffer
|
||||
"""
|
||||
|
||||
external_req_id: str | None = None
|
||||
additional_information: AdditionalInformationPayload | None = None
|
||||
additional_information: AdditionalInformationPayload | dict[str, object] | None = None
|
||||
model_intermediate_buffer: dict[str, object] | None = None
|
||||
|
||||
@classmethod
|
||||
@@ -114,3 +117,5 @@ class OmniSchedulerOutput(SchedulerOutput):
|
||||
|
||||
finished_requests_needing_kv_transfer: dict[str, dict] = field(default_factory=dict)
|
||||
pending_input_registrations: list[OmniChunkRecvHandle] = field(default_factory=list)
|
||||
data_plane_terminal_req_ids: set[str] = field(default_factory=set)
|
||||
input_terminal_req_ids: set[str] = field(default_factory=set)
|
||||
@@ -3,7 +3,9 @@
|
||||
"""Shared utilities for omni schedulers."""
|
||||
|
||||
import numpy as np
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.outputs import RoutedExpertsLists
|
||||
from vllm.v1.request import Request
|
||||
|
||||
|
||||
def omni_routed_experts_for_request(routed_experts: RoutedExpertsLists, request) -> np.ndarray | None:
|
||||
@@ -21,3 +23,19 @@ def omni_routed_experts_for_request(routed_experts: RoutedExpertsLists, request)
|
||||
mask = np.isin(routed_experts.slot_mapping, list(slot_set))
|
||||
data = routed_experts.routing_data[mask]
|
||||
return data if data.size > 0 else None
|
||||
|
||||
|
||||
def free_kv_blocks_in_physical_order(manager: KVCacheManager, request: Request) -> None:
|
||||
"""Return non-cached request blocks in increasing physical order.
|
||||
|
||||
vLLM's block pool deliberately honors the eviction-priority order passed
|
||||
to ``free_blocks``. For a non-caching P/D pool there is no LRU priority to
|
||||
preserve, so physical order lets native connectors coalesce adjacent
|
||||
source/destination pages on the next allocation.
|
||||
"""
|
||||
|
||||
if manager.enable_caching:
|
||||
manager.free(request)
|
||||
return
|
||||
blocks = manager.pop_blocks_for_free(request)
|
||||
manager.block_pool.free_blocks(sorted(blocks, key=lambda block: block.block_id))
|
||||
@@ -34,9 +34,14 @@ class HiddenStates(TypedDict, total=False):
|
||||
|
||||
|
||||
class Embeddings(TypedDict, total=False):
|
||||
prepared_prefill: torch.Tensor
|
||||
prefill: torch.Tensor
|
||||
decode: torch.Tensor
|
||||
decode_token_start: int
|
||||
decode_token_end: int
|
||||
cached_decode: torch.Tensor
|
||||
cached_decode_token_start: int
|
||||
cached_decode_token_end: int
|
||||
tts_bos: torch.Tensor
|
||||
tts_eos: torch.Tensor
|
||||
tts_pad: torch.Tensor
|
||||
@@ -54,6 +59,7 @@ class Codes(TypedDict, total=False):
|
||||
|
||||
|
||||
class Ids(TypedDict, total=False):
|
||||
prepared_prefill: torch.Tensor
|
||||
all: list[int]
|
||||
prompt: list[int]
|
||||
output: list[int]
|
||||
@@ -81,6 +87,7 @@ class OmniPayloadMeta(TypedDict, total=False):
|
||||
next_stage_prompt_len: int
|
||||
next_stage_generation_tokens: int
|
||||
replace_streaming_prompt: bool
|
||||
next_stage_prompt_ids: list[int]
|
||||
streaming_prompt_recompute: bool
|
||||
streaming_condition_seq: int
|
||||
replace_runtime_additional_information: bool
|
||||
@@ -94,6 +101,7 @@ class OmniPayloadMeta(TypedDict, total=False):
|
||||
width: int
|
||||
decode_flag: bool
|
||||
codec_streaming: bool
|
||||
codec_frame_valid: bool | torch.Tensor
|
||||
ref_code_len: int
|
||||
ref_context_size: int
|
||||
ref_context_request_id: str
|
||||
@@ -148,6 +156,8 @@ class EmbeddingsStruct(_StructBase):
|
||||
decode_token_start: int | None = None
|
||||
decode_token_end: int | None = None
|
||||
cached_decode: torch.Tensor | None = None
|
||||
cached_decode_token_start: int | None = None
|
||||
cached_decode_token_end: int | None = None
|
||||
tts_bos: torch.Tensor | None = None
|
||||
tts_eos: torch.Tensor | None = None
|
||||
tts_pad: torch.Tensor | None = None
|
||||
@@ -190,6 +200,7 @@ class MetaStruct(_StructBase):
|
||||
next_stage_prompt_len: int | None = None
|
||||
next_stage_generation_tokens: int | None = None
|
||||
replace_streaming_prompt: bool | None = None
|
||||
next_stage_prompt_ids: list[int] | None = None
|
||||
streaming_prompt_recompute: bool | None = None
|
||||
streaming_condition_seq: int | None = None
|
||||
replace_runtime_additional_information: bool | None = None
|
||||
@@ -203,6 +214,7 @@ class MetaStruct(_StructBase):
|
||||
width: int | None = None
|
||||
decode_flag: bool | None = None
|
||||
codec_streaming: bool | None = None
|
||||
codec_frame_valid: torch.Tensor | None = None
|
||||
ref_code_len: int | None = None
|
||||
# Expected FINAL length of a growing async-chunk sequence, when the
|
||||
# producer knows it up front (e.g. a frame-locked AR stage whose
|
||||
|
||||
@@ -14,7 +14,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
|
||||
@@ -9,7 +9,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
|
||||
@@ -21,7 +21,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
|
||||
@@ -9,7 +9,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
|
||||
@@ -26,7 +26,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
|
||||
@@ -26,7 +26,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
|
||||
@@ -32,8 +32,12 @@ stages:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
# Match upstream's penalty on generated codebook-0 history.
|
||||
repetition_penalty: 1.1
|
||||
max_tokens: 2048
|
||||
min_tokens: 1
|
||||
# min_tokens also masks the tokenizer's EOS 1 despite ignore_eos.
|
||||
# Keep valid codec token 1 and an immediate backbone EOS available.
|
||||
min_tokens: 0
|
||||
|
||||
- stage_id: 1
|
||||
max_num_seqs: 8
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
# dots.tts deployment config (single-stage AR talker).
|
||||
#
|
||||
# Conservative first-integration settings: eager execution, no CUDA
|
||||
# Graphs, no batched side-path optimizations yet — see voxcpm2.yaml for
|
||||
# the runtime knobs a mature deployment of this model family grows.
|
||||
#
|
||||
# Verified locally on RTX 5080 16GB.
|
||||
|
||||
async_chunk: false
|
||||
dtype: bfloat16
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
max_num_seqs: 4
|
||||
gpu_memory_utilization: 0.8
|
||||
enforce_eager: true
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 4096
|
||||
max_model_len: 4096
|
||||
devices: "0"
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
top_p: 1.0
|
||||
top_k: -1
|
||||
max_tokens: 4096
|
||||
repetition_penalty: 1.0
|
||||
@@ -1,38 +0,0 @@
|
||||
# Dynin-Omni 3-stage deploy: token2text → token2image → token2audio.
|
||||
#
|
||||
# Topology (stages, processor functions, model_arch) is frozen in
|
||||
# vllm_omni/model_executor/models/dynin_omni/pipeline.py. This file carries
|
||||
# only the deploy-time knobs (devices, GPU memory, batched tokens).
|
||||
#
|
||||
# async_chunk=false: dynin hands the full token payload across stages through
|
||||
# the worker-connector data plane (``*_full_payload`` producers), not chunked
|
||||
# streaming. Pipeline-wide ``trust_remote_code`` is required by the custom
|
||||
# Dynin HF modeling code.
|
||||
async_chunk: false
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.5
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
|
||||
- stage_id: 1
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.1
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
|
||||
- stage_id: 2
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.1
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
@@ -1,35 +0,0 @@
|
||||
# Dynin-Omni deploy for e2e smoke tests (3-stage, one GPU).
|
||||
#
|
||||
# Topology is frozen in models/dynin_omni/pipeline.py; ``pipeline: dynin_omni``
|
||||
# pins it explicitly so this CI YAML resolves regardless of model_type
|
||||
# auto-detection. Differs from the default deploy only in reduced GPU memory
|
||||
# and a smaller max_num_batched_tokens so the pipeline fits L4-class CI GPUs.
|
||||
pipeline: dynin_omni
|
||||
async_chunk: false
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.5
|
||||
max_num_batched_tokens: 4096
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
|
||||
- stage_id: 1
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.2
|
||||
max_num_batched_tokens: 4096
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
|
||||
- stage_id: 2
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
gpu_memory_utilization: 0.2
|
||||
max_num_batched_tokens: 4096
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
@@ -1,63 +0,0 @@
|
||||
# Dynin-Omni 3-stage deploy with cross-node connectors (Mooncake demo).
|
||||
#
|
||||
# Topology is frozen in models/dynin_omni/pipeline.py (``pipeline: dynin_omni``).
|
||||
# This variant wires a MooncakeConnector for each stage hand-off in place of
|
||||
# the default SharedMemoryConnector. Update the ``extra`` host/master/metadata
|
||||
# fields to match your Mooncake deployment before use.
|
||||
pipeline: dynin_omni
|
||||
async_chunk: false
|
||||
trust_remote_code: false
|
||||
enable_prefix_caching: false
|
||||
|
||||
connectors:
|
||||
# Mooncake connector for cross-node/intra-node communication.
|
||||
mooncake_connector:
|
||||
name: MooncakeConnector
|
||||
extra:
|
||||
host: "127.0.0.1"
|
||||
metadata_server: "http://10.90.67.86:8080/metadata"
|
||||
master: "10.90.67.86:50051"
|
||||
segment: 512000000 # 512MB
|
||||
localbuf: 64000000 # 64MB
|
||||
proto: "tcp"
|
||||
|
||||
# Yuanrong connector for cross-node/intra-node communication.
|
||||
yuanrong_connector:
|
||||
name: YuanrongConnector
|
||||
extra:
|
||||
host: "127.0.0.1"
|
||||
port: "35000"
|
||||
|
||||
# Alternative SHM connector with an explicit threshold.
|
||||
shared_memory_connector:
|
||||
name: SharedMemoryConnector
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
output_connectors:
|
||||
to_stage_1: mooncake_connector
|
||||
|
||||
- stage_id: 1
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
input_connectors:
|
||||
from_stage_0: mooncake_connector
|
||||
output_connectors:
|
||||
to_stage_2: mooncake_connector
|
||||
|
||||
- stage_id: 2
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
max_num_batched_tokens: 32768
|
||||
enforce_eager: true
|
||||
async_scheduling: false
|
||||
input_connectors:
|
||||
from_stage_1: mooncake_connector
|
||||
@@ -64,6 +64,15 @@ stages:
|
||||
repetition_penalty: 1.0
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
# Ascend paged attention only accepts 128-token cache blocks
|
||||
# (AscendAttentionBackend.get_supported_kernel_block_sizes() == [128]),
|
||||
# while vLLM's CacheConfig default is 16. Without this override stage 0
|
||||
# aborts during KV-cache init with:
|
||||
# ValueError: No common block size for 16.
|
||||
stages:
|
||||
- stage_id: 0
|
||||
block_size: 128
|
||||
xpu:
|
||||
stages:
|
||||
# Verified on Intel Arc B60.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
pipeline: hunyuan_image_3_moe
|
||||
async_chunk: false
|
||||
trust_remote_code: true
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
is_comprehension: true
|
||||
# Return AR text (including CoT) alongside the final image.
|
||||
final_output: true
|
||||
final_output_type: text
|
||||
num_replicas: 2
|
||||
devices: "0,1,2,3"
|
||||
tensor_parallel_size: 2
|
||||
max_num_seqs: 1
|
||||
max_num_batched_tokens: 32768
|
||||
kv_cache_memory_bytes: 2147483648
|
||||
gpu_memory_utilization: 0.95
|
||||
enforce_eager: true
|
||||
moe_backend: triton
|
||||
env:
|
||||
MC_TCP_ENABLE_CONNECTION_POOL: "1"
|
||||
MC_TCP_SLICE_SIZE: "4194304"
|
||||
VLLM_USE_FLASHINFER_SAMPLER: "0"
|
||||
hf_overrides:
|
||||
rope_parameters:
|
||||
mrope_section: [0, 32, 32]
|
||||
rope_type: default
|
||||
kv_transfer_config:
|
||||
kv_connector: MooncakeConnector
|
||||
kv_role: kv_producer
|
||||
engine_id: hunyuan-image3-ar
|
||||
kv_ip: 127.0.0.1
|
||||
kv_connector_extra_config:
|
||||
mooncake_protocol: tcp
|
||||
bootstrap_port: 8998
|
||||
default_sampling_params:
|
||||
temperature: 0.0
|
||||
max_tokens: 8192
|
||||
detokenize: true
|
||||
skip_special_tokens: false
|
||||
include_stop_str_in_output: true
|
||||
|
||||
- stage_id: 1
|
||||
num_replicas: 2
|
||||
devices: "4,5,6,7"
|
||||
max_num_seqs: 1
|
||||
max_num_batched_tokens: 16384
|
||||
max_model_len: 12288
|
||||
kv_cache_memory_bytes: 1073741824
|
||||
enforce_eager: true
|
||||
# Registered Mooncake KV pages must remain mapped for the connector lifetime.
|
||||
enable_sleep_mode: false
|
||||
moe_backend: triton
|
||||
env:
|
||||
MC_TCP_ENABLE_CONNECTION_POOL: "1"
|
||||
MC_TCP_SLICE_SIZE: "4194304"
|
||||
PYTORCH_CUDA_ALLOC_CONF: expandable_segments:True
|
||||
distributed_executor_backend: mp
|
||||
diffusion_kv_mode: paged_scheduler
|
||||
diffusion_kv_max_rows_per_request: 2
|
||||
kv_transfer_config:
|
||||
kv_connector: MooncakeConnector
|
||||
kv_role: kv_consumer
|
||||
engine_id: hunyuan-image3-dit
|
||||
kv_connector_extra_config:
|
||||
mooncake_protocol: tcp
|
||||
# Seconds to wait before failing a request; in-flight pages remain reserved.
|
||||
transfer_timeout: 60.0
|
||||
parallel_config:
|
||||
tensor_parallel_size: 2
|
||||
enable_expert_parallel: true
|
||||
default_sampling_params:
|
||||
num_inference_steps: 2
|
||||
guidance_scale: 2.0
|
||||
height: 512
|
||||
width: 512
|
||||
|
||||
edges:
|
||||
- from: 0
|
||||
to: 1
|
||||
window_size: -1
|
||||
max_inflight: 1
|
||||
@@ -106,11 +106,14 @@ platforms:
|
||||
|
||||
xpu:
|
||||
stages:
|
||||
# Both stages stay resident, so they cannot share cards.
|
||||
- stage_id: 0
|
||||
gpu_memory_utilization: 0.95
|
||||
devices: "0,1,2,3,4,5,6,7"
|
||||
tensor_parallel_size: 8
|
||||
max_num_batched_tokens: 32784
|
||||
devices: "0,1,2,3"
|
||||
tensor_parallel_size: 4
|
||||
# fp8 AR weights leave under 1 GiB for KV; 22800 tokens will not fit.
|
||||
max_num_batched_tokens: 8192
|
||||
max_model_len: 8192
|
||||
quantization: fp8
|
||||
enable_expert_parallel: true
|
||||
worker_cls: vllm_omni.platforms.xpu.worker.xpu_ar_worker.XPUARWorker
|
||||
@@ -120,12 +123,12 @@ platforms:
|
||||
repetition_penalty: 1.1
|
||||
- stage_id: 1
|
||||
gpu_memory_utilization: 0.9
|
||||
devices: "0,1,2,3,4,5,6,7"
|
||||
devices: "4,5,6,7"
|
||||
quantization: fp8
|
||||
parallel_config:
|
||||
pipeline_parallel_size: 1
|
||||
data_parallel_size: 1
|
||||
tensor_parallel_size: 8
|
||||
tensor_parallel_size: 4
|
||||
enable_expert_parallel: true
|
||||
sequence_parallel_size: 1
|
||||
ulysses_degree: 1
|
||||
|
||||
@@ -20,8 +20,3 @@ stages:
|
||||
enforce_eager: true
|
||||
trust_remote_code: true
|
||||
enable_prefix_caching: false
|
||||
default_sampling_params:
|
||||
extra_args:
|
||||
text_guidance_scale: 9.0
|
||||
cfg_range: [0.0, 1.0]
|
||||
num_inference_steps: 50
|
||||
@@ -1,8 +1,7 @@
|
||||
# MiniCPM-o 4.5 three-stage deploy on one large-memory GPU.
|
||||
pipeline: minicpmo_4_5
|
||||
async_chunk: true
|
||||
# session_mode: duplex makes vllm-omni serve run this model duplex-only
|
||||
# (/v1/realtime?duplex=1); every other duplex_session knob keeps its runtime default.
|
||||
# Use minicpmo_4_5_turn.yaml to select the ordinary turn-based serving engine.
|
||||
session_mode: duplex
|
||||
# Keep the active window aligned with the session and stage capacities below.
|
||||
# A smaller window serializes first-packet generation for concurrent chat turns.
|
||||
@@ -48,7 +47,7 @@ stages:
|
||||
fps: 1
|
||||
num_frames: 128
|
||||
limit_mm_per_prompt:
|
||||
# Daily-Omni MiniCPM pack: up to 64 interleaved image/audio pairs (1fps).
|
||||
# Daily-Omni: up to 64 interleaved image/audio pairs (1fps).
|
||||
image: 64
|
||||
audio: 64
|
||||
video: 1
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# MiniCPM-o 4.5 using the turn-based engine and ordinary HTTP serving.
|
||||
base_config: minicpmo_4_5.yaml
|
||||
session_mode: turn
|
||||
@@ -25,7 +25,6 @@ connectors:
|
||||
# Window geometry is fixed by the checkpoint (200-frame windows on a
|
||||
# 100-frame hop, models/minimax_music3/constants.py), so there are no
|
||||
# codec_chunk_frames knobs here: changing the window changes the audio.
|
||||
shm_threshold_bytes: 65536
|
||||
connector_get_sleep_s: 0.01
|
||||
# One window is 200 AR frames = 8 s of music, so stage 1 waits far longer
|
||||
# for a chunk than a per-step codec stage would. First chunk additionally
|
||||
|
||||
@@ -22,7 +22,6 @@ connectors:
|
||||
# Window geometry is fixed by the checkpoint (200-frame windows on a
|
||||
# 100-frame hop, models/minimax_music3/constants.py), so there are no
|
||||
# codec_chunk_frames knobs here: changing the window changes the audio.
|
||||
shm_threshold_bytes: 65536
|
||||
connector_get_sleep_s: 0.01
|
||||
# One window is 200 AR frames = 8 s of music, so stage 1 waits far longer
|
||||
# for a chunk than a per-step codec stage would. First chunk additionally
|
||||
|
||||
@@ -57,3 +57,11 @@ stages:
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
|
||||
platforms:
|
||||
rocm:
|
||||
stages:
|
||||
- stage_id: 1
|
||||
# MIOPEN_FIND_MODE=FAST changes solver selection, not HIP graph safety.
|
||||
# Keep the Conv1d codec outside the outer vLLM graph on ROCm.
|
||||
enforce_eager: true
|
||||
@@ -64,3 +64,14 @@ stages:
|
||||
max_tokens: 65536
|
||||
seed: 42
|
||||
repetition_penalty: 1.0
|
||||
|
||||
# Stage 1 NPU override: PIECEWISE cudagraph for NPUGraph capture; set enforce_eager: true to disable.
|
||||
platforms:
|
||||
npu:
|
||||
stages:
|
||||
- stage_id: 1
|
||||
compilation_config:
|
||||
cudagraph_mode: PIECEWISE
|
||||
# Re-declared: _apply_platform_overrides() wholesale-replaces compilation_config.
|
||||
cudagraph_capture_sizes: [1, 2, 4, 8, 16, 32, 64]
|
||||
cudagraph_num_of_warmups: 1
|
||||
@@ -25,8 +25,6 @@ async_chunk: false
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
|
||||
stages:
|
||||
- stage_id: 0 # thinker: speech -> frame-locked text (final text output)
|
||||
|
||||
@@ -58,7 +58,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_chunk_frames: 1
|
||||
# PARITY: delete this line together with the stage-1 hf_overrides
|
||||
# below (the vendored talker drains chunks model-side and keeps the
|
||||
|
||||
@@ -22,7 +22,6 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
# Streaming cadence for talker -> code2wav: emit a chunk once this many
|
||||
# NEW frames (80 ms each) have accumulated (5 frames = 0.4 s of audio).
|
||||
# Small chunks are cheap because the incremental codec cache decodes
|
||||
|
||||
@@ -23,14 +23,9 @@ connectors:
|
||||
connector_of_shared_memory:
|
||||
name: SharedMemoryConnector
|
||||
extra:
|
||||
shm_threshold_bytes: 65536
|
||||
codec_streaming: true
|
||||
connector_get_sleep_s: 0.01
|
||||
connector_get_max_wait_first_chunk: 3000
|
||||
connector_get_max_wait: 300
|
||||
# Mimi runs at 12.5 Hz (80 ms / frame). Stream a few frames per chunk.
|
||||
codec_chunk_frames: 5
|
||||
codec_left_context_frames: 10
|
||||
# Emit only the first audio chunk early, then return to codec_chunk_frames.
|
||||
initial_codec_chunk_frames: 1
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
# π0.5 VLA: one diffusion stage, one GPU, eager, bsz 1 (OpenPI policy serving is
|
||||
# one observation -> one action reply). Every key below is documented in
|
||||
# recipes/lerobot/Pi05.md.
|
||||
|
||||
pipeline: pi05
|
||||
async_chunk: false
|
||||
distributed_executor_backend: mp
|
||||
# float32 or bfloat16. bfloat16 is faster and halves memory at a numerical cost;
|
||||
# read "Choosing a dtype" in the recipe before switching.
|
||||
dtype: float32
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
devices: "0"
|
||||
max_num_seqs: 1
|
||||
enforce_eager: true
|
||||
model_class_name: Pi05Pipeline
|
||||
model_config:
|
||||
paligemma_variant: gemma_2b
|
||||
action_expert_variant: gemma_300m
|
||||
chunk_size: 50
|
||||
# Must equal chunk_size: this endpoint returns the whole chunk and keeps no
|
||||
# action queue, so "execute the first N steps, then replan" is not available.
|
||||
n_action_steps: 50
|
||||
max_action_dim: 32
|
||||
max_state_dim: 32
|
||||
num_inference_steps: 10
|
||||
image_resolution: [224, 224]
|
||||
tokenizer_max_length: 200
|
||||
state_num_bins: 256
|
||||
max_cameras: 3
|
||||
image_feature_keys:
|
||||
- observation.images.base_0_rgb
|
||||
- observation.images.left_wrist_0_rgb
|
||||
- observation.images.right_wrist_0_rgb
|
||||
image_key_map: {}
|
||||
use_relative_actions: false
|
||||
relative_exclude_joints:
|
||||
- gripper
|
||||
# OpenPI handshake metadata advertised to the robot client.
|
||||
policy_server_config:
|
||||
image_resolution: [224, 224]
|
||||
n_external_cameras: 1
|
||||
needs_wrist_camera: true
|
||||
needs_stereo_camera: false
|
||||
needs_session_id: false
|
||||
action_space: joint_position
|
||||
action_horizon: 50
|
||||
action_dim: 32
|
||||
max_action_dim: 32
|
||||
max_cameras: 3
|
||||
@@ -0,0 +1,8 @@
|
||||
# Concurrent input / interruptible VAD turns; not native streaming input KV.
|
||||
base_config: qwen3_omni_moe.yaml
|
||||
session_mode: duplex
|
||||
stages:
|
||||
- stage_id: 0
|
||||
limit_mm_per_prompt:
|
||||
audio: 4
|
||||
image: 8
|
||||
@@ -63,11 +63,12 @@ stages:
|
||||
max_num_seqs: 64
|
||||
gpu_memory_utilization: 0.3
|
||||
trust_remote_code: true
|
||||
# Prefix caching on by default. The HS opt-out (talker only consumes the
|
||||
# last token's hidden state) and deferred mm-output writes added in this
|
||||
# PR make per-step bookkeeping negligible, and any text repetition across
|
||||
# requests (same voice or shared ref_audio) is a net throughput win.
|
||||
# Disable explicitly if memory headroom is tight on a single-GPU deploy.
|
||||
# Omni prefix cache (reuse of talker codec rows on shared prefixes). Off
|
||||
# by default; set true when text repeats across requests (same voice or
|
||||
# shared ref_audio). The talker opts out of hidden-state caching and
|
||||
# defers codes.audio writes, so per-step cost is small. Stage 1 (codec
|
||||
# decoder) is not a supported prefix-cache stage: keep it false there.
|
||||
# See docs/design/feature/prefix_caching.md for the stage matrix.
|
||||
enable_prefix_caching: false
|
||||
async_scheduling: true
|
||||
max_num_batched_tokens: 32768
|
||||
|
||||
@@ -9,6 +9,15 @@
|
||||
# Profile validated for the c64 / PROMPTS=512 performance experiments:
|
||||
# Stage 0 talker on GPU 0 with S0=64, Stage 1 Code2Wav on GPU 1 with S1=10.
|
||||
#
|
||||
# For CPU-bound frontend or orchestration workloads, this profile can be used
|
||||
# with ``--api-server-count 2`` or higher to run multiple API frontends over
|
||||
# one shared set of local stage engines. This can improve request parsing,
|
||||
# multimodal/audio preprocessing, and response handling under concurrency;
|
||||
# it does not duplicate GPU engines or make a single GPU-bound request faster.
|
||||
# Each frontend keeps process-local state, so runtime voice mutations, sleep /
|
||||
# wakeup, async video jobs, and resumable duplex sessions are not supported
|
||||
# with more than one API worker. See docs/cli/serve.md for the full boundary.
|
||||
#
|
||||
async_chunk: true
|
||||
|
||||
connectors:
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Opt-in CUDA Model Runner V2 profile. The base profile retains V1.
|
||||
base_config: qwen3_tts_high_concurrency.yaml
|
||||
model_runner: v2
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
model_runner: v1
|
||||
xpu:
|
||||
model_runner: v1
|
||||
rocm:
|
||||
model_runner: v1
|
||||
musa:
|
||||
model_runner: v1
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
extra:
|
||||
# Keep unqualified prefix-graph optimizations disabled in this profile.
|
||||
code_predictor_prefix_graphs: false
|
||||
ref_audio_artifact_cache_max_entries: 1024
|
||||
# Opt-in B2 codec graphs. Validate quality for the deployment workload.
|
||||
decode_batch_max_size: 2
|
||||
decode_cudagraph_batch_sizes: [1, 2]
|
||||
|
||||
stages:
|
||||
- stage_id: 1
|
||||
# Enable the decoder's inner graphs; the generation runner stays eager.
|
||||
enforce_eager: false
|
||||
@@ -0,0 +1,8 @@
|
||||
# Experimental B4 profile. Early first audio can require startup buffering.
|
||||
# MPS is a separate operator setting and is not enabled by this file.
|
||||
base_config: qwen3_tts_high_concurrency_mrv2.yaml
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
extra:
|
||||
decode_batch_max_size: 4
|
||||
decode_cudagraph_batch_sizes: [1, 2, 3, 4]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Opt-in single-GPU throughput profile, measured on H200 at concurrency 128
|
||||
# with Qwen3-TTS-12Hz-1.7B-Base. Warm the full pipeline before benchmarking.
|
||||
# B8 uses more graph memory than B4; this is not a low-latency profile.
|
||||
# MPS is optional and is not enabled by this file.
|
||||
#
|
||||
# vllm serve Qwen/Qwen3-TTS-12Hz-1.7B-Base --omni \
|
||||
# --deploy-config vllm_omni/deploy/qwen3_tts_high_concurrency_mrv2_single_gpu.yaml
|
||||
base_config: qwen3_tts_high_concurrency_mrv2.yaml
|
||||
|
||||
connectors:
|
||||
connector_of_shared_memory:
|
||||
extra:
|
||||
decode_batch_max_size: 8
|
||||
decode_cudagraph_batch_sizes: [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
devices: "0"
|
||||
max_num_seqs: 128
|
||||
- stage_id: 1
|
||||
devices: "0"
|
||||
# Admission candidates are grouped by codec phase before B8 execution.
|
||||
max_num_seqs: 32
|
||||
@@ -0,0 +1,18 @@
|
||||
# Opt-in CUDA Model Runner V2 profile. The base profile retains V1.
|
||||
base_config: qwen3_tts.yaml
|
||||
model_runner: v2
|
||||
|
||||
platforms:
|
||||
npu:
|
||||
model_runner: v1
|
||||
xpu:
|
||||
model_runner: v1
|
||||
rocm:
|
||||
model_runner: v1
|
||||
musa:
|
||||
model_runner: v1
|
||||
|
||||
stages:
|
||||
- stage_id: 0
|
||||
# Bound per-step prefill work, matching the high-concurrency TTS profile.
|
||||
max_num_batched_tokens: 512
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
from functools import cache, partial
|
||||
|
||||
import torch
|
||||
@@ -75,18 +76,18 @@ class FlashAttentionBackend(AttentionBackend):
|
||||
|
||||
|
||||
class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
# Per-platform FP8 KV quantization support.
|
||||
# To enable FP8 on a new platform, add its OmniPlatformEnum value here
|
||||
# Per-platform attention quantization support.
|
||||
# To enable a method on a new platform, add its OmniPlatformEnum value here
|
||||
# and handle kv_cache_dtype in the corresponding forward_{platform}().
|
||||
#
|
||||
# TODO(quant-backend): The FP8 quant path currently lives inside
|
||||
# TODO(quant-backend): The quantized path currently lives inside
|
||||
# FlashAttentionImpl gated by ``attn_metadata.extra["kv_cache_dtype"]``.
|
||||
# Eventually extract it into a dedicated FlashAttentionQuantBackend so
|
||||
# backend selection (not metadata) decides quant. Until then, model
|
||||
# authors can opt a specific Attention layer out via
|
||||
# backend selection decides quant.
|
||||
# Until then, model authors can opt a specific Attention layer out via
|
||||
# ``Attention(disable_kv_quant=True)``.
|
||||
_supported_kv_cache_dtypes = {
|
||||
"npu": {"fp8"},
|
||||
"npu": {"fp8", "mxfp8", "mxfp4"},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
@@ -310,11 +311,17 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
if native_impl is None:
|
||||
raise RuntimeError(f"Native attention implementation is not bound for diffusion layer {layer.layer_name!r}")
|
||||
prewrite_kv = current_omni_platform.requires_diffusion_paged_kv_prewrite()
|
||||
read_kv_from_cache = prewrite_kv and layer.attn_backend.forward_includes_kv_cache_update
|
||||
forward_updates_cache = layer.attn_backend.forward_includes_kv_cache_update
|
||||
# Match vLLM's split update/attention contract. Once K/V has been
|
||||
# written by do_kv_cache_update(), decoder attention consumes the
|
||||
# paged cache and does not need segment-local K/V tensors. In
|
||||
# particular, this avoids packing the same K/V projection view once
|
||||
# for every piecewise segment.
|
||||
read_kv_from_cache = not forward_updates_cache or prewrite_kv
|
||||
# The GPU/default path preserves native cache-update ownership. Ascend
|
||||
# prewrites through vLLM-Ascend's normal-layout writer so piecewise FIA
|
||||
# segments do not repeatedly scatter the same layer K/V.
|
||||
if not layer.attn_backend.forward_includes_kv_cache_update or prewrite_kv:
|
||||
if not forward_updates_cache or prewrite_kv:
|
||||
cache_update = getattr(native_impl, "do_kv_cache_update", None)
|
||||
if not callable(cache_update):
|
||||
raise RuntimeError(
|
||||
@@ -352,14 +359,11 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
)
|
||||
|
||||
if paged_kv_context.piecewise_plan is not None:
|
||||
# Ascend FIA can execute identical CFG rows as one batched call
|
||||
# per piece. Keep that batch layout through the piecewise runner
|
||||
# so it can concatenate row-major results instead of emitting an
|
||||
# indexed ScatterUpdate for every segment. The CUDA path keeps
|
||||
# its existing output-buffer contract (including graph capture).
|
||||
use_homogeneous_batch = (
|
||||
current_omni_platform.is_npu() and paged_kv_context.piecewise_plan.homogeneous_batch_shape is not None
|
||||
)
|
||||
# Identical CFG rows can execute as one batched call per piece.
|
||||
# Keep that batch layout through the piecewise runner so Q/K/V use
|
||||
# strided slices instead of indexed gathers and results can be
|
||||
# concatenated in row-major order.
|
||||
use_homogeneous_batch = paged_kv_context.piecewise_plan.homogeneous_batch_shape is not None
|
||||
output = None
|
||||
if not use_homogeneous_batch:
|
||||
output = torch.empty(
|
||||
@@ -526,11 +530,47 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
) -> torch.Tensor:
|
||||
"""NPU attention implementation using mindiesd."""
|
||||
|
||||
kv_cache_dtype = attn_metadata.extra.get("kv_cache_dtype") if attn_metadata else None
|
||||
if kv_cache_dtype is not None:
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
method = extra.get("kv_cache_dtype")
|
||||
if method not in (None, "float", "auto"):
|
||||
return self.forward_fa_quant_npu(query, key, value, attn_metadata)
|
||||
return self.forward_fa_npu(query, key, value, attn_metadata)
|
||||
|
||||
@staticmethod
|
||||
def _load_quant_runtime(method: str) -> Callable[..., torch.Tensor]:
|
||||
if method not in ("fp8", "mxfp8", "mxfp4"):
|
||||
raise ValueError(f"Unsupported NPU attention quantization method {method!r}.")
|
||||
from mindiesd import quant_attention
|
||||
|
||||
return quant_attention
|
||||
|
||||
def _validate_quant_request(
|
||||
self,
|
||||
method: str,
|
||||
query: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> None:
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
reason = None
|
||||
if self.causal:
|
||||
reason = "causal quantized FA is not supported"
|
||||
elif any(name in extra for name in ("cu_seqlens_q", "cu_seqlens_k")) or extra.get("npu_attn_varlen"):
|
||||
reason = "packed/varlen metadata requires the float attention path"
|
||||
elif attn_metadata is not None and attn_metadata.full_attn_spans is not None:
|
||||
reason = "piecewise attention requires the float attention path"
|
||||
elif attn_metadata is not None and attn_metadata.attn_mask is not None:
|
||||
reason = "caller masks require the float attention path"
|
||||
elif method in ("fp8", "mxfp8", "mxfp4") and (
|
||||
query.ndim != 4 or query.shape[-1] <= 0 or query.shape[-1] & (query.shape[-1] - 1)
|
||||
):
|
||||
reason = "generated Hadamard rotations require a four-dimensional input and power-of-two head size"
|
||||
if reason is not None:
|
||||
raise ValueError(
|
||||
f"NPU attention precision {method!r} is unavailable: {reason}. "
|
||||
"Set diffusion_kv_cache_dtype to a supported method, or set it to "
|
||||
"'auto'. Automatic precision fallback is not performed."
|
||||
)
|
||||
|
||||
def forward_fa_quant_npu(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
@@ -538,18 +578,29 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
from vllm_omni.platforms.npu.quant.kv_quant_npu import fp8_rotate_quant_fa
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
method = extra.get("kv_cache_dtype", "fp8")
|
||||
layout = self.qkv_layout or "BSND"
|
||||
self._validate_quant_request(method, query, attn_metadata)
|
||||
try:
|
||||
runtime = self._load_quant_runtime(method)
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
f"NPU attention precision {method!r} requires a compatible MindIE-SD "
|
||||
"quant Runtime. Install a compatible MindIE-SD build, select another "
|
||||
"diffusion_kv_cache_dtype, or set it to 'auto'. Automatic precision "
|
||||
"fallback is not performed."
|
||||
) from exc
|
||||
kwargs = dict(precision=method, layout=layout, scale=self.softmax_scale)
|
||||
# Apply Omni's deterministic Q/K rotation before every Dense quantized path.
|
||||
if method in ("fp8", "mxfp8", "mxfp4"):
|
||||
from vllm_omni.platforms.npu.quant.kv_quant_npu import get_quant_attention_rotation
|
||||
|
||||
layout = self.qkv_layout or "BNSD"
|
||||
# Models pass (B, S, H, D); NPU fused op expects (B, N, S, D).
|
||||
out = fp8_rotate_quant_fa(
|
||||
query.transpose(1, 2),
|
||||
key.transpose(1, 2),
|
||||
value.transpose(1, 2),
|
||||
layout=layout,
|
||||
softmax_scale=self.softmax_scale,
|
||||
)
|
||||
return out.transpose(1, 2)
|
||||
rotation = get_quant_attention_rotation(query.device, query.dtype, query.shape[-1])
|
||||
kwargs.update(q_rot=rotation, k_rot=rotation)
|
||||
logger.info_once("NPU attention uses MindIE-SD %s Runtime, layout=%s.", method, layout)
|
||||
# Execution errors propagate. Never retry with another precision.
|
||||
return runtime(query, key, value, **kwargs)
|
||||
|
||||
def forward_fa_npu(
|
||||
self,
|
||||
|
||||
@@ -135,6 +135,11 @@ class RainFusionPlan:
|
||||
class RainFusionAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
supported_platforms: tuple[str, ...] = ("npu",)
|
||||
# The impl trims [real, pad] packed tensors to the valid prefix with
|
||||
# [:, :used] itself, so models may run the padded layout without
|
||||
# materializing a padding mask (a forward that carries one anyway falls
|
||||
# back dense in _resolve_plan).
|
||||
supports_prefix_kv_slicing: bool = True
|
||||
|
||||
@classmethod
|
||||
def validate_available(cls) -> None:
|
||||
@@ -146,8 +151,10 @@ class RainFusionAttentionBackend(AttentionBackend):
|
||||
from mindiesd import sparse_attention
|
||||
except ImportError as exc:
|
||||
raise ValueError(_MISSING_MINDIESD) from exc
|
||||
if not _supports_video_spans(sparse_attention):
|
||||
raise ValueError(_INCOMPATIBLE_MINDIESD)
|
||||
if not callable(sparse_attention):
|
||||
raise ValueError(_MISSING_MINDIESD)
|
||||
# Single-video Wan only needs the legacy geometry. Check video_spans
|
||||
# when a forward actually carries multiple videos.
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
@@ -174,6 +181,8 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
irregular video tail internally, retaining it outside the sparse blocks.
|
||||
"""
|
||||
|
||||
_supported_kv_cache_dtypes = {"npu": {"fp8", "mxfp4"}}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
@@ -222,6 +231,8 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
def _validate_parallel_config(self) -> None:
|
||||
config = get_current_diffusion_config_or_none()
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
if getattr(parallel_config, "allgather_degree", 1) > 1:
|
||||
raise ValueError("RAINFUSION_ATTN requires full Q/K/V sequences; AllGather-KV SP is unsupported.")
|
||||
ring_degree = getattr(parallel_config, "ring_degree", 1)
|
||||
if ring_degree > 1:
|
||||
# Ring gives each rank a slice of the sequence, so block selection
|
||||
@@ -262,7 +273,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
plan = self._resolve_plan(attn_metadata)
|
||||
if plan is None:
|
||||
return self.dense_fallback.forward_npu(query, key, value, attn_metadata)
|
||||
return self._forward_sparse_npu(query, key, value, plan)
|
||||
if query.ndim != 4 or key.shape != query.shape or value.shape != query.shape or plan.used_len > query.shape[1]:
|
||||
raise ValueError("RainFusion video geometry must fit identical full-sequence BSND Q/K/V tensors.")
|
||||
return self._forward_sparse_npu(query, key, value, plan, attn_metadata)
|
||||
|
||||
def _resolve_plan(self, attn_metadata: AttentionMetadata | None) -> RainFusionPlan | None:
|
||||
"""Return the rf_v2 geometry, or None when this forward must stay dense."""
|
||||
@@ -271,18 +284,17 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
return None
|
||||
if self.layer_idx is not None and self.layer_idx in rf.skip_layers:
|
||||
return None
|
||||
step_idx = total_steps = None
|
||||
if is_forward_context_available():
|
||||
step_idx = get_forward_context().denoise_step_idx
|
||||
total_steps = get_forward_context().total_denoise_steps
|
||||
if step_idx is not None and step_idx < rf.start_step:
|
||||
if (rf.start_step and step_idx is None) or (rf.end_step and (step_idx is None or total_steps is None)):
|
||||
return None
|
||||
if step_idx is not None:
|
||||
if step_idx < rf.start_step:
|
||||
return None
|
||||
# Tail fallback: keep the last ``end_step`` denoise steps dense.
|
||||
if (
|
||||
rf.end_step > 0
|
||||
and step_idx is not None
|
||||
and total_steps is not None
|
||||
and step_idx >= total_steps - rf.end_step
|
||||
):
|
||||
if rf.end_step > 0 and total_steps is not None and step_idx >= total_steps - rf.end_step:
|
||||
return None
|
||||
if self.qkv_layout is None:
|
||||
# The sparse path reads the sequence off dim 1, which the tensors alone
|
||||
@@ -308,7 +320,16 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
"model must publish AttentionMetadata.video_layout for the sequence to be sparsified."
|
||||
)
|
||||
return None
|
||||
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q")
|
||||
|
||||
# The sparse Runtime constructs its own block mask. It cannot preserve
|
||||
# an arbitrary caller-supplied mask or piecewise visibility constraints.
|
||||
mask = attn_metadata.attn_mask
|
||||
padding_only = layout.used_len is not None
|
||||
if attn_metadata.full_attn_spans is not None or (
|
||||
mask is not None and not (padding_only and mask.ndim == 2 and mask.dtype == torch.bool)
|
||||
):
|
||||
return None
|
||||
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q", layout.used_len)
|
||||
if max_seqlen_q is None:
|
||||
logger.warning_once(
|
||||
"RAINFUSION_ATTN staying dense: attention metadata is missing max_seqlen_q, so the "
|
||||
@@ -459,31 +480,56 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
plan: RainFusionPlan,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
try:
|
||||
from mindiesd import sparse_attention
|
||||
except ImportError:
|
||||
raise ImportError(_MISSING_MINDIESD)
|
||||
if self.rainfusion.precision != "bf16" and not _mindiesd_supports_precision():
|
||||
raise RuntimeError(
|
||||
f"block_sparse.precision={self.rainfusion.precision!r} requires MindIE-SD "
|
||||
"with sparse_attention(precision=...) support; the installed mindiesd "
|
||||
"silently ignores it and would run the BF16 path. Install a compatible "
|
||||
"MindIE-SD release or use precision='bf16'."
|
||||
if plan.video_spans is not None and not _supports_video_spans(sparse_attention):
|
||||
raise ValueError(_INCOMPATIBLE_MINDIESD)
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
requested = extra.get("kv_cache_dtype", self.rainfusion.precision)
|
||||
reason = None
|
||||
if requested in ("float", "bf16"):
|
||||
precision = "bf16"
|
||||
else:
|
||||
precision = requested
|
||||
if requested not in ("fp8", "mxfp4", "mix"):
|
||||
reason = f"sparse {requested} is not supported"
|
||||
elif not _mindiesd_supports_precision():
|
||||
reason = "MindIE-SD sparse_attention must explicitly support precision"
|
||||
elif plan.video_spans is not None:
|
||||
reason = "quantized multi-video RainFusion is not supported"
|
||||
elif requested in ("fp8", "mxfp4") and query.shape[0] != 1:
|
||||
reason = "quantized Wan BSA requires batch size 1"
|
||||
elif requested in ("fp8", "mxfp4") and (query.shape[-1] < 64 or query.shape[-1] & (query.shape[-1] - 1)):
|
||||
reason = "BSA Hadamard rotations require a power-of-two head dimension of at least 64"
|
||||
if reason is not None:
|
||||
raise ValueError(
|
||||
f"RainFusion precision {requested!r} is unavailable: {reason}. "
|
||||
"Set diffusion_kv_cache_dtype or block_sparse.precision to a method supported by the installed "
|
||||
"MindIE-SD, or disable attention quantization. Automatic precision fallback is not performed."
|
||||
)
|
||||
|
||||
logger.info_once("RainFusion uses MindIE-SD sparse attention, precision=%s.", precision)
|
||||
used = plan.used_len
|
||||
q, k, v = (tensor[:, :used] for tensor in (query, key, value))
|
||||
# Split query once: the valid prefix drives the kernel, the padding
|
||||
# tail is reused verbatim as the output padding below. All views,
|
||||
# zero-copy. split_with_sizes always yields both parts, including an
|
||||
# empty tail when the sequence needs no padding.
|
||||
q, q_pad = torch.split(query, [used, query.shape[1] - used], dim=1)
|
||||
k, v = key[:, :used], value[:, :used]
|
||||
# Ulysses has already gathered the full sequence onto this rank and split
|
||||
# the heads, so read the head count off the tensor rather than num_heads.
|
||||
common_kwargs: dict[str, object] = {
|
||||
"scale": self.softmax_scale,
|
||||
"head_num": query.shape[-2],
|
||||
"input_layout": _INPUT_LAYOUT,
|
||||
"inner_precise": _INNER_PRECISE,
|
||||
"inner_precise": 4 if precision != "bf16" else _INNER_PRECISE,
|
||||
"block_size": _BLOCK_SIZE,
|
||||
"sparsity": self.rainfusion.sparsity,
|
||||
"precision": self.rainfusion.precision,
|
||||
"precision": precision,
|
||||
}
|
||||
if plan.video_spans is not None:
|
||||
out = sparse_attention(
|
||||
@@ -497,7 +543,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
else:
|
||||
assert plan.prefix_len is not None and plan.latent_shape is not None
|
||||
common_kwargs.update(
|
||||
sparse_type="rf_v2",
|
||||
# rf_v2 ignores precision on non-A5 devices. Select the explicit
|
||||
# quantized high-level path so mask/rearrangement remain in MindIE.
|
||||
sparse_type="rf_v3" if precision != "bf16" else "rf_v2",
|
||||
txt_len=plan.prefix_len,
|
||||
latent_shape_q=plan.latent_shape,
|
||||
latent_shape_k=plan.latent_shape,
|
||||
@@ -505,6 +553,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
out = sparse_attention(q, k, v, **common_kwargs)
|
||||
if used == query.shape[1]:
|
||||
return out
|
||||
padded = torch.zeros_like(query)
|
||||
padded[:, :used] = out
|
||||
return padded
|
||||
# Only the first ``used`` rows are read back downstream, so the padding
|
||||
# payload is free. Reuse the query tail split off above instead of
|
||||
# zeroing a fresh buffer: a single cat write, no extra allocation, and
|
||||
# always finite values (uninitialized memory could hold NaN bit
|
||||
# patterns).
|
||||
return torch.cat([out, q_pad], dim=1)
|
||||
@@ -321,7 +321,7 @@ class Attention(nn.Module):
|
||||
dtype = None
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
ring_degree = getattr(parallel_config, "ring_degree", 1)
|
||||
if dtype:
|
||||
if dtype and dtype != "float":
|
||||
if ring_degree > 1:
|
||||
raise ValueError(
|
||||
"KV quantization is not compatible with ring attention "
|
||||
@@ -338,13 +338,15 @@ class Attention(nn.Module):
|
||||
self._kv_cache_dtype = dtype
|
||||
self._kv_cache_skip_steps = getattr(config, "diffusion_kv_cache_skip_step_indices", None)
|
||||
self._kv_cache_skip_layers = getattr(config, "diffusion_kv_cache_skip_layer_indices", None)
|
||||
if self._kv_cache_skip_layers and self.layer_idx is None and not self._disable_kv_quant:
|
||||
raise ValueError("Attention quantization skip_layers requires a parseable transformer block index.")
|
||||
|
||||
def _should_apply_kv_cache_quant(self) -> bool:
|
||||
skip_steps = self._kv_cache_skip_steps
|
||||
skip_layers = self._kv_cache_skip_layers
|
||||
if skip_steps is not None:
|
||||
step_idx = get_forward_context().denoise_step_idx if is_forward_context_available() else None
|
||||
if step_idx is not None and step_idx in skip_steps:
|
||||
if skip_steps and (step_idx is None or step_idx in skip_steps):
|
||||
return False
|
||||
if skip_layers is not None:
|
||||
if self.layer_idx is not None and self.layer_idx in skip_layers:
|
||||
@@ -352,18 +354,21 @@ class Attention(nn.Module):
|
||||
return True
|
||||
|
||||
def _with_kv_cache_dtype(self, attn_metadata: AttentionMetadata | None) -> AttentionMetadata | None:
|
||||
kv_cache_dtype = self._kv_cache_dtype
|
||||
if kv_cache_dtype is None or self._disable_kv_quant or not self._should_apply_kv_cache_quant():
|
||||
if attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra:
|
||||
return attn_metadata
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra.pop("kv_cache_dtype", None)
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
disabled = self._disable_kv_quant or not self._should_apply_kv_cache_quant()
|
||||
dtype = self._kv_cache_dtype
|
||||
if dtype in (None, "float"):
|
||||
dtype = None
|
||||
elif disabled:
|
||||
dtype = "float"
|
||||
if dtype is None and (attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra):
|
||||
return attn_metadata
|
||||
extra = dict(attn_metadata.extra) if attn_metadata is not None else {}
|
||||
# Recompute per forward so shared metadata cannot retain another step's policy.
|
||||
extra.pop("kv_cache_dtype", None)
|
||||
if dtype is not None:
|
||||
extra["kv_cache_dtype"] = dtype
|
||||
if attn_metadata is None:
|
||||
return AttentionMetadata(extra={"kv_cache_dtype": kv_cache_dtype})
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra["kv_cache_dtype"] = kv_cache_dtype
|
||||
return AttentionMetadata(extra=extra) if extra else None
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
def forward(
|
||||
|
||||
+99
-42
@@ -6,6 +6,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import warnings
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from enum import Enum
|
||||
@@ -44,55 +45,63 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def normalize_omni_diffusion_kwargs(raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize legacy diffusion kwargs before config construction."""
|
||||
def _move_diffusion_alias(
|
||||
normalized: dict[str, Any],
|
||||
legacy_name: str,
|
||||
canonical_name: str,
|
||||
) -> None:
|
||||
legacy_value = normalized.pop(legacy_name, None)
|
||||
if legacy_value is None:
|
||||
return
|
||||
if normalized.get(canonical_name) is not None:
|
||||
raise ValueError(f"Diffusion config fields {legacy_name!r} and {canonical_name!r} cannot both be provided.")
|
||||
warnings.warn(
|
||||
f"Diffusion config field {legacy_name!r} is deprecated; use {canonical_name!r}.",
|
||||
FutureWarning,
|
||||
stacklevel=3,
|
||||
)
|
||||
normalized[canonical_name] = legacy_value
|
||||
|
||||
|
||||
def normalize_omni_diffusion_kwargs(
|
||||
raw_kwargs: Mapping[str, Any],
|
||||
*,
|
||||
apply_defaults: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Normalize diffusion kwargs, deferring defaults until sources are merged."""
|
||||
config_kwargs = dict(raw_kwargs)
|
||||
|
||||
dtype = config_kwargs.get("dtype")
|
||||
if dtype is None:
|
||||
config_kwargs["dtype"] = "auto"
|
||||
if apply_defaults:
|
||||
config_kwargs["dtype"] = "auto"
|
||||
elif isinstance(dtype, torch.dtype):
|
||||
config_kwargs["dtype"] = str(dtype).removeprefix("torch.")
|
||||
elif not isinstance(dtype, str):
|
||||
raise TypeError(f"Provided dtype must be a string or torch.dtype, got {type(dtype).__name__}")
|
||||
|
||||
# Backwards-compatibility: older callers may use a diffusion-specific
|
||||
# "static_lora_scale" kwarg. Normalize it to the canonical "lora_scale".
|
||||
if "static_lora_scale" in config_kwargs:
|
||||
if "lora_scale" not in config_kwargs:
|
||||
config_kwargs["lora_scale"] = config_kwargs["static_lora_scale"]
|
||||
config_kwargs.pop("static_lora_scale", None)
|
||||
|
||||
diffusion_quantization = config_kwargs.pop("diffusion_quantization_config", None)
|
||||
if config_kwargs.get("quantization_config") is None and diffusion_quantization is not None:
|
||||
config_kwargs["quantization_config"] = diffusion_quantization
|
||||
|
||||
# Backwards-compatibility: map "quantization" to "quantization_config"
|
||||
# so callers using the old field name still work.
|
||||
if "quantization" in config_kwargs and config_kwargs.get("quantization_config", None) is None:
|
||||
config_kwargs["quantization_config"] = config_kwargs.pop("quantization")
|
||||
else:
|
||||
config_kwargs.pop("quantization", None)
|
||||
|
||||
# Renamed from kv_cache_* to avoid clashing with vLLM's --kv-cache-dtype.
|
||||
if config_kwargs.get("diffusion_kv_cache_dtype") is None and "kv_cache_dtype" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_dtype"] = config_kwargs.pop("kv_cache_dtype")
|
||||
else:
|
||||
config_kwargs.pop("kv_cache_dtype", None)
|
||||
if config_kwargs.get("diffusion_kv_cache_skip_steps") is None and "kv_cache_skip_steps" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_skip_steps"] = config_kwargs.pop("kv_cache_skip_steps")
|
||||
else:
|
||||
config_kwargs.pop("kv_cache_skip_steps", None)
|
||||
if config_kwargs.get("diffusion_kv_cache_skip_layers") is None and "kv_cache_skip_layers" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_skip_layers"] = config_kwargs.pop("kv_cache_skip_layers")
|
||||
else:
|
||||
config_kwargs.pop("kv_cache_skip_layers", None)
|
||||
for legacy, canonical in (
|
||||
("static_lora_scale", "lora_scale"),
|
||||
("quantization", "quantization_config"),
|
||||
("diffusion_quantization_config", "quantization_config"),
|
||||
("max_batch_size", "max_num_seqs"),
|
||||
("kv_cache_skip_steps", "diffusion_kv_cache_skip_steps"),
|
||||
("kv_cache_skip_layers", "diffusion_kv_cache_skip_layers"),
|
||||
):
|
||||
_move_diffusion_alias(config_kwargs, legacy, canonical)
|
||||
_move_diffusion_alias(config_kwargs, "kv_cache_dtype", "diffusion_kv_cache_dtype")
|
||||
|
||||
# Handle "diffusion_attention_backend" shorthand: merge into
|
||||
# diffusion_attention_config before field filtering.
|
||||
diffusion_attn_backend = config_kwargs.pop("diffusion_attention_backend", None)
|
||||
fastvideo_vsa_topk = config_kwargs.pop("fastvideo_vsa_topk", None)
|
||||
if diffusion_attn_backend is not None or fastvideo_vsa_topk is not None:
|
||||
if diffusion_attn_backend is not None:
|
||||
warnings.warn(
|
||||
"Diffusion config field 'diffusion_attention_backend' is deprecated; use 'diffusion_attention_config'.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
existing = config_kwargs.get("diffusion_attention_config")
|
||||
config_kwargs["diffusion_attention_config"] = parse_attention_config(
|
||||
existing,
|
||||
@@ -100,12 +109,23 @@ def normalize_omni_diffusion_kwargs(raw_kwargs: Mapping[str, Any]) -> dict[str,
|
||||
fastvideo_vsa_topk=fastvideo_vsa_topk,
|
||||
)
|
||||
|
||||
auxiliary_text_encoder = config_kwargs.pop("auxiliary_text_encoder", None)
|
||||
if auxiliary_text_encoder is not None:
|
||||
extras = dict(config_kwargs.get("extras") or {})
|
||||
if extras.get("auxiliary_text_encoder") is not None:
|
||||
raise ValueError(
|
||||
"Diffusion engine field 'auxiliary_text_encoder' cannot be provided both at the top level and in "
|
||||
"'extras'."
|
||||
)
|
||||
extras["auxiliary_text_encoder"] = auxiliary_text_encoder
|
||||
config_kwargs["extras"] = extras
|
||||
|
||||
# Check environment variable as fallback for cache_backend.
|
||||
# Support both old DIFFUSION_CACHE_ADAPTER and new DIFFUSION_CACHE_BACKEND.
|
||||
if "cache_backend" not in config_kwargs:
|
||||
if "cache_backend" not in config_kwargs and apply_defaults:
|
||||
cache_backend = os.environ.get("DIFFUSION_CACHE_BACKEND") or os.environ.get("DIFFUSION_CACHE_ADAPTER")
|
||||
config_kwargs["cache_backend"] = cache_backend.lower() if cache_backend else "none"
|
||||
elif config_kwargs["cache_backend"] is None:
|
||||
elif "cache_backend" in config_kwargs and config_kwargs["cache_backend"] is None and apply_defaults:
|
||||
# Callers (e.g. example CLIs with `default=None`) pass an explicit
|
||||
# None for "no cache"; canonicalize it so every consumer sees the
|
||||
# declared `str` value instead of relying on per-model None handling.
|
||||
@@ -162,6 +182,20 @@ def validate_dlo_host_registration_options(
|
||||
return value
|
||||
|
||||
|
||||
def validate_omni_diffusion_kwargs(
|
||||
kwargs: Mapping[str, Any],
|
||||
allowed_fields: set[str] | frozenset[str],
|
||||
*,
|
||||
stage_id: int | str | None = None,
|
||||
) -> None:
|
||||
"""Reject every field without an owner."""
|
||||
unknown = set(kwargs) - allowed_fields
|
||||
if unknown:
|
||||
names = ", ".join(repr(name) for name in sorted(unknown))
|
||||
suffix = "" if stage_id is None else f" for stage {stage_id}"
|
||||
raise ValueError(f"Unknown diffusion config field(s){suffix}: {names}")
|
||||
|
||||
|
||||
def parse_kv_cache_skip_selector(
|
||||
selector: str | list[int] | tuple[int, ...] | set[int] | None,
|
||||
) -> set[int] | None:
|
||||
@@ -1021,16 +1055,15 @@ class OmniDiffusionConfig:
|
||||
# str is resolved to {"method": <str>} internally.
|
||||
# Per-component: {"transformer": {"method": "fp8"}, "vae": None}
|
||||
quantization_config: str | QuantizationConfig | dict[str, Any] | None = None
|
||||
# Internal provenance, retained across config projection and worker transport.
|
||||
quantization_config_is_auto_detected: bool = False
|
||||
# Explicit runtime override for ModelOpt FP8 diffusion checkpoints. This
|
||||
# does not enable FP8 by itself; it only selects CUTLASS once the checkpoint
|
||||
# has already resolved to vLLM's ModelOpt FP8 linear method.
|
||||
force_cutlass_fp8: bool = False
|
||||
|
||||
# Diffusion attention KV cache dtype (not vLLM's --kv-cache-dtype for AR models).
|
||||
# None = native dtype (no quantization).
|
||||
# "fp8" = dynamic FP8 (float8_e4m3fn) quantization per forward pass.
|
||||
# On Hopper+FA3: native FP8 attention (memory + compute savings).
|
||||
# On other backends: no benefit, backends skip quantization.
|
||||
# Runtime diffusion attention method (not vLLM's --kv-cache-dtype for AR models).
|
||||
# None/"auto" keeps native dtype; other values are validated by the selected backend.
|
||||
diffusion_kv_cache_dtype: str | None = None
|
||||
# Optional skip selectors for KV-cache quantization. Format: "0-9,20,25-30".
|
||||
# Listed steps/layers skip quantization; others keep quantized execution.
|
||||
@@ -1192,6 +1225,8 @@ class OmniDiffusionConfig:
|
||||
if self.diffusion_kv_mode is not DiffusionKVCacheMode.PAGED_SCHEDULER:
|
||||
raise ValueError("native kv_transfer_config requires diffusion_kv_mode='paged_scheduler'")
|
||||
self.kv_transfer_config = parse_kv_transfer_config(self.kv_transfer_config)
|
||||
if self.enable_sleep_mode:
|
||||
raise ValueError("Native KV transfer does not support sleep mode: registered pages must remain mapped")
|
||||
|
||||
self.master_port = self._resolve_master_port()
|
||||
self.request_batch_max_wait_ms = float(self.request_batch_max_wait_ms or 0.0)
|
||||
@@ -1346,6 +1381,10 @@ class OmniDiffusionConfig:
|
||||
self.model,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_single_file(self) -> bool:
|
||||
return isinstance(self.model, str) and os.path.isfile(self.model)
|
||||
|
||||
def _propagate_quantization_from_tf_config(self, tf_config: "TransformerConfig") -> None:
|
||||
if tf_config.quant_config is None:
|
||||
return
|
||||
@@ -1358,6 +1397,8 @@ class OmniDiffusionConfig:
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
if self.quantization_config is None:
|
||||
self.quantization_config_is_auto_detected = True
|
||||
self.quantization_config = tf_config.quant_config
|
||||
logger.info(
|
||||
"Auto-detected quantization '%s' from model config",
|
||||
@@ -1448,12 +1489,22 @@ class OmniDiffusionConfig:
|
||||
"""
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
from vllm_omni.diffusion.registry import resolve_native_single_file
|
||||
from vllm_omni.diffusion.utils.hf_utils import (
|
||||
get_diffusion_model_index,
|
||||
resolve_native_diffusion_model_class,
|
||||
)
|
||||
|
||||
assert self.model is not None
|
||||
|
||||
native_single_file_model = resolve_native_single_file(self.model_class_name)
|
||||
if self.is_single_file and native_single_file_model is not None:
|
||||
self.diffusion_load_format = "default"
|
||||
self.model_class_name = native_single_file_model
|
||||
self.diffusers_pipeline_cls = None
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
return
|
||||
|
||||
try:
|
||||
config_dict = get_diffusion_model_index(
|
||||
self.model,
|
||||
@@ -1611,6 +1662,11 @@ class OmniDiffusionConfig:
|
||||
self.model_class_name = "Pi0Pipeline"
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
self.update_multimodal_support()
|
||||
elif cfg.get("type") == "pi05":
|
||||
if self.model_class_name is None:
|
||||
self.model_class_name = "Pi05Pipeline"
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
self.update_multimodal_support()
|
||||
elif architectures and len(architectures) == 1:
|
||||
architecture = architectures[0]
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
@@ -1625,8 +1681,9 @@ class OmniDiffusionConfig:
|
||||
|
||||
@classmethod
|
||||
def normalize_init_kwargs(cls, raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
valid_fields = frozenset(f.name for f in fields(cls))
|
||||
config_kwargs = normalize_omni_diffusion_kwargs(raw_kwargs)
|
||||
valid_fields = {f.name for f in fields(cls)}
|
||||
validate_omni_diffusion_kwargs(config_kwargs, valid_fields)
|
||||
# Remaining ``None`` values mean "unset" at the CLI/deploy boundary.
|
||||
# Drop them so non-optional dataclass defaults are not overwritten.
|
||||
# Fields where ``None`` has normalization semantics (for example dtype
|
||||
|
||||
@@ -603,7 +603,11 @@ class DiffusionEngine:
|
||||
|
||||
self._wait_for_admission_if_needed_locked()
|
||||
|
||||
sched_output = self.scheduler.schedule()
|
||||
try:
|
||||
sched_output = self.scheduler.schedule()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
return
|
||||
self._scheduler_num_waiting_reqs = max(int(sched_output.num_waiting_reqs), 0)
|
||||
|
||||
self._emit_request_started_outputs(sched_output)
|
||||
@@ -613,8 +617,17 @@ class DiffusionEngine:
|
||||
continue
|
||||
|
||||
try:
|
||||
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
|
||||
self._prepare_kv_for_forward(sched_output)
|
||||
runner_output: BaseRunnerOutput = (
|
||||
self.execute_fn(sched_output)
|
||||
if sched_output.scheduled_request_ids
|
||||
else BatchRunnerOutput.from_list([])
|
||||
)
|
||||
worker_execution_completed = True
|
||||
except Exception as exc:
|
||||
if self._closed:
|
||||
return
|
||||
worker_execution_completed = False
|
||||
logger.error(
|
||||
"Execution failed for diffusion requests %s", sched_output.scheduled_request_ids, exc_info=True
|
||||
)
|
||||
@@ -632,8 +645,23 @@ class DiffusionEngine:
|
||||
|
||||
self._process_aborts_queue()
|
||||
self._process_rpc_queue()
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
self._emit_outputs(finished_req_ids, sched_output.scheduled_request_ids, runner_output)
|
||||
try:
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
self._emit_outputs(
|
||||
finished_req_ids,
|
||||
sched_output.scheduled_request_ids,
|
||||
runner_output,
|
||||
worker_execution_completed=worker_execution_completed,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
return
|
||||
|
||||
if not sched_output.scheduled_request_ids and self.scheduler._kv_draining_requests:
|
||||
# Only exceptional in-flight receives need idle polling. New
|
||||
# requests / aborts wake this wait immediately.
|
||||
with self._cv:
|
||||
self._cv.wait(timeout=0.01)
|
||||
|
||||
# Engine is stopping: fail any RPCs still queued so callers don't hang.
|
||||
self._fail_pending_rpcs(RuntimeError("DiffusionEngine is shutting down."))
|
||||
@@ -755,15 +783,80 @@ class DiffusionEngine:
|
||||
return
|
||||
unique_request_ids = list(dict.fromkeys(request_ids))
|
||||
if unique_request_ids:
|
||||
self.executor.remove_diffusion_kv_requests(unique_request_ids)
|
||||
scheduler = getattr(self, "scheduler", None)
|
||||
target_builder = getattr(scheduler, "get_diffusion_kv_cleanup_targets", None)
|
||||
cleanup_targets = target_builder(unique_request_ids) if target_builder is not None else unique_request_ids
|
||||
try:
|
||||
if cleanup_targets:
|
||||
self.executor.remove_diffusion_kv_requests(cleanup_targets)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _prepare_kv_for_forward(self, sched_output: DiffusionSchedulerOutput) -> None:
|
||||
if getattr(sched_output, "kv_connector_metadata", None) is None:
|
||||
return
|
||||
try:
|
||||
output = self.executor.prepare_kv_for_forward(sched_output)
|
||||
assert output is not None
|
||||
self.scheduler.update_kv_connector_output(output)
|
||||
if not self.abort_queue.empty():
|
||||
self._process_aborts_queue()
|
||||
incomplete = sched_output.kv_transfer_request_ids - (output.finished_recving or set())
|
||||
sched_output.finished_req_ids.update(self.scheduler.fail_incomplete_kv_loads(incomplete))
|
||||
# Timed-out/cancelled requests must never reach model execution.
|
||||
terminal = {
|
||||
rid
|
||||
for rid in sched_output.scheduled_request_ids
|
||||
if (state := self.scheduler.get_request_state(rid)) is not None and state.is_finished()
|
||||
}
|
||||
if terminal:
|
||||
sched_output.finished_req_ids.update(terminal)
|
||||
sched_output.scheduled_new_reqs = [
|
||||
req for req in sched_output.scheduled_new_reqs if req.request_id not in terminal
|
||||
]
|
||||
sched_output.scheduled_cached_reqs.request_ids = [
|
||||
rid for rid in sched_output.scheduled_cached_reqs.request_ids if rid not in terminal
|
||||
]
|
||||
# is_empty / started-output handling may have already cached it.
|
||||
sched_output.__dict__.pop("scheduled_request_ids", None)
|
||||
drained = self.scheduler.completed_kv_drains()
|
||||
if drained:
|
||||
self._remove_diffusion_kv_requests(drained)
|
||||
self.scheduler.release_kv_drains(drained)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _fail_engine(self, exc: Exception) -> None:
|
||||
if getattr(self, "_shutdown_complete", False):
|
||||
return
|
||||
logger.error("Diffusion engine failed; stopping workers before releasing KV pages", exc_info=exc)
|
||||
with self._cv:
|
||||
self._closed = True
|
||||
if self.stop_event is not None:
|
||||
self.stop_event.set()
|
||||
streams = list(self._out_streams.values())
|
||||
self._cv.notify_all()
|
||||
for stream in streams:
|
||||
self._put_queue_output(stream, DiffusionOutput.from_exception(exc))
|
||||
self._fail_pending_rpcs(exc)
|
||||
try:
|
||||
self.executor.shutdown()
|
||||
finally:
|
||||
try:
|
||||
self.scheduler.close()
|
||||
finally:
|
||||
self._shutdown_complete = True
|
||||
|
||||
def _emit_finished_outputs(
|
||||
self,
|
||||
finished_ids: set[str],
|
||||
runner_output: BaseRunnerOutput | None = None,
|
||||
missing_result_error: str = "Diffusion execution finished without a final output",
|
||||
worker_cleaned_ids: set[str] | None = None,
|
||||
) -> None:
|
||||
self._remove_diffusion_kv_requests(finished_ids)
|
||||
self._remove_diffusion_kv_requests(finished_ids - (worker_cleaned_ids or set()))
|
||||
for rid in finished_ids:
|
||||
if runner_output is not None:
|
||||
_output = runner_output.get_request_output(rid)
|
||||
@@ -777,13 +870,21 @@ class DiffusionEngine:
|
||||
finished_ids: set[str],
|
||||
scheduled_request_ids: list[str],
|
||||
runner_output: BaseRunnerOutput,
|
||||
*,
|
||||
worker_execution_completed: bool = False,
|
||||
) -> None:
|
||||
"""Emit output chunks for every request through the unified output stream."""
|
||||
finished_ids = set(finished_ids)
|
||||
worker_cleaned_ids = finished_ids.intersection(scheduled_request_ids) if worker_execution_completed else set()
|
||||
if self.execution_mode != DiffusionExecutionMode.STEP_BATCH:
|
||||
self._emit_finished_outputs(finished_ids, runner_output)
|
||||
self._emit_finished_outputs(
|
||||
finished_ids,
|
||||
runner_output,
|
||||
worker_cleaned_ids=worker_cleaned_ids,
|
||||
)
|
||||
return
|
||||
|
||||
self._remove_diffusion_kv_requests(finished_ids)
|
||||
self._remove_diffusion_kv_requests(finished_ids - worker_cleaned_ids)
|
||||
|
||||
delivered_finished_req_ids: set[str] = set()
|
||||
|
||||
@@ -975,7 +1076,11 @@ class DiffusionEngine:
|
||||
# keep scheduling and executing until the target request is finished
|
||||
while True:
|
||||
self._process_aborts_queue()
|
||||
sched_output = self.scheduler.schedule()
|
||||
try:
|
||||
sched_output = self.scheduler.schedule()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
if sched_output.is_empty:
|
||||
if target_request_id in sched_output.finished_req_ids:
|
||||
self._remove_diffusion_kv_requests([target_request_id])
|
||||
@@ -986,12 +1091,19 @@ class DiffusionEngine:
|
||||
|
||||
# NOTE: add_req_and_wait_for_response() is synchronous, will be only called
|
||||
# within _dummy_run, only one request will be scheduled
|
||||
request_id = sched_output.scheduled_request_ids[0]
|
||||
request_id = target_request_id
|
||||
try:
|
||||
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
|
||||
self._prepare_kv_for_forward(sched_output)
|
||||
runner_output: BaseRunnerOutput = (
|
||||
self.execute_fn(sched_output)
|
||||
if sched_output.scheduled_request_ids
|
||||
else BatchRunnerOutput.from_list([])
|
||||
)
|
||||
except EngineDeadError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if self._closed:
|
||||
raise
|
||||
logger.error("Execution failed for diffusion request %s", request_id, exc_info=True)
|
||||
runner_output = RunnerOutput(
|
||||
request_id=request_id,
|
||||
@@ -1005,7 +1117,11 @@ class DiffusionEngine:
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
|
||||
# sync func should receive one result
|
||||
if not isinstance(runner_output, RunnerOutput) and not len(runner_output) == 1:
|
||||
if (
|
||||
sched_output.scheduled_request_ids
|
||||
and not isinstance(runner_output, RunnerOutput)
|
||||
and len(runner_output) != 1
|
||||
):
|
||||
raise ValueError("Sync func should receive one result at one time")
|
||||
if target_request_id in finished_req_ids:
|
||||
self._remove_diffusion_kv_requests([target_request_id])
|
||||
@@ -1100,7 +1216,8 @@ class DiffusionEngine:
|
||||
executes one request from the collective wave.
|
||||
|
||||
Hunyuan is currently the only model integrated with
|
||||
``paged_scheduler``; 1024x1024, enabled CFG, and the maximum advertised
|
||||
``paged_scheduler``. The stage's configured default resolution (or
|
||||
1024x1024 when absent), enabled CFG, and the maximum advertised
|
||||
reference-image count exercise its first-step activation peak.
|
||||
Admission compares each preprocessed request's CFG count and tokenized
|
||||
sequence/target shape with the resulting per-request profile envelope.
|
||||
@@ -1117,9 +1234,12 @@ class DiffusionEngine:
|
||||
model_class_name = self.od_config.model_class_name
|
||||
if model_class_name is None:
|
||||
raise RuntimeError("Diffusion KV profiling requires a resolved model_class_name")
|
||||
additional_config = getattr(self.od_config, "additional_config", {}) or {}
|
||||
profile_height = additional_config.get("diffusion_kv_profile_height", 1024)
|
||||
profile_width = additional_config.get("diffusion_kv_profile_width", 1024)
|
||||
request = self._make_dummy_request(
|
||||
height=1024,
|
||||
width=1024,
|
||||
height=profile_height,
|
||||
width=profile_width,
|
||||
guidance_scale=5.0,
|
||||
num_image_inputs=get_dummy_run_num_image_inputs(model_class_name),
|
||||
)
|
||||
@@ -1335,7 +1455,11 @@ class DiffusionEngine:
|
||||
|
||||
def _process_aborts_queue(self) -> None:
|
||||
with self._cv:
|
||||
self._drain_abort_queue()
|
||||
try:
|
||||
self._drain_abort_queue()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _drain_abort_queue(self) -> None:
|
||||
if self.abort_queue.empty():
|
||||
@@ -1352,11 +1476,10 @@ class DiffusionEngine:
|
||||
request_ids = [request_ids] if isinstance(request_ids, str) else list(request_ids)
|
||||
request_ids = list(dict.fromkeys(request_ids))
|
||||
|
||||
self._remove_diffusion_kv_requests(request_ids)
|
||||
|
||||
for request_id in request_ids:
|
||||
if self.scheduler.get_request_state(request_id) is not None:
|
||||
self.scheduler.finish_requests(request_id, DiffusionRequestStatus.FINISHED_ABORTED)
|
||||
self._remove_diffusion_kv_requests(request_ids)
|
||||
|
||||
def _finalize_finished_request(
|
||||
self,
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Diffusion-side assembly facade built on the upstream Mooncake KV connector.
|
||||
|
||||
The configured ``kv_connector`` (currently ``MooncakeConnector``) is created
|
||||
through vLLM's native ``KVConnectorFactory``. PR0 only validates configuration
|
||||
and creates the Scheduler/Worker connector objects; it does not subclass or
|
||||
reimplement Mooncake's transfer runtime. Real page sizing, cache registration,
|
||||
admission, and remote loading belong to the follow-up landing PR.
|
||||
"""
|
||||
"""Assemble native vLLM KV connectors for Scheduler-owned diffusion pages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_transfer_state import ensure_kv_transfer_initialized, ensure_kv_transfer_shutdown
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorBase_V1
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.diffusion_kv.request import DiffusionKVRequest
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionSchedulerOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class KVTransferRegistrationError(ValueError):
|
||||
"""A failed handoff whose destination pages have not been dispatched."""
|
||||
|
||||
|
||||
def mint_transfer_id(request_id: str) -> str:
|
||||
"""Return the stable ticket shared by one AR -> Diffusion handoff."""
|
||||
|
||||
@@ -110,6 +115,8 @@ def parse_kv_transfer_config(value: object | None) -> KVTransferConfig | None:
|
||||
|
||||
def create_scheduler_kv_connector(
|
||||
od_config: OmniDiffusionConfig,
|
||||
kv_cache_config: KVCacheConfig | None = None,
|
||||
vllm_config: VllmConfig | None = None,
|
||||
) -> KVConnectorBase_V1 | None:
|
||||
"""Create a Scheduler-role connector when native config is present."""
|
||||
|
||||
@@ -121,14 +128,15 @@ def create_scheduler_kv_connector(
|
||||
f"Diffusion native kv_transfer_config must be KVTransferConfig, got {type(kv_transfer_config)!r}"
|
||||
)
|
||||
|
||||
vllm_config = _build_native_vllm_config(od_config)
|
||||
if kv_cache_config is None or vllm_config is None:
|
||||
raise ValueError("KV transfer requires paged_scheduler and a native cache configuration")
|
||||
connector = KVConnectorFactory.create_connector(
|
||||
config=vllm_config,
|
||||
role=KVConnectorRole.SCHEDULER,
|
||||
kv_cache_config=_empty_kv_cache_config(),
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
logger.info(
|
||||
"Created KV connector stub (SCHEDULER role): connector=%s engine_id=%s",
|
||||
"Created KV connector (SCHEDULER role): connector=%s engine_id=%s",
|
||||
kv_transfer_config.kv_connector,
|
||||
kv_transfer_config.engine_id,
|
||||
)
|
||||
@@ -140,9 +148,27 @@ def init_worker_kv_connector(vllm_config: VllmConfig, kv_cache_config: KVCacheCo
|
||||
|
||||
if vllm_config.kv_transfer_config is None:
|
||||
return
|
||||
ensure_kv_transfer_initialized(vllm_config, kv_cache_config)
|
||||
import vllm.distributed.parallel_state as parallel_state
|
||||
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
|
||||
# vLLM 0.29 Mooncake snapshots tp_rank/tp_size in its Worker constructor;
|
||||
# consumer receive/region mapping use those saved values, not get_tp_group.
|
||||
# Restrict this compatibility bridge to that connector and restore the
|
||||
# model's TP group even when construction fails. Never remap model TP for
|
||||
# the connector's entire lifetime (it would change model collectives).
|
||||
tp_group = parallel_state._TP
|
||||
parallel_config = getattr(vllm_config, "parallel_config", None)
|
||||
if getattr(parallel_config, "prefill_context_parallel_size", 1) > 1 and tp_group.world_size == 1:
|
||||
if vllm_config.kv_transfer_config.kv_connector != "MooncakeConnector":
|
||||
raise ValueError("Native SP KV transfer currently requires MooncakeConnector")
|
||||
parallel_state._TP = get_sp_group()
|
||||
try:
|
||||
ensure_kv_transfer_initialized(vllm_config, kv_cache_config)
|
||||
finally:
|
||||
parallel_state._TP = tp_group
|
||||
logger.info(
|
||||
"Initialized KV connector stub (WORKER role): connector=%s engine_id=%s",
|
||||
"Initialized KV connector (WORKER role): connector=%s engine_id=%s",
|
||||
vllm_config.kv_transfer_config.kv_connector,
|
||||
vllm_config.kv_transfer_config.engine_id,
|
||||
)
|
||||
@@ -156,26 +182,165 @@ def shutdown_kv_connector(*, scheduler_connector: KVConnectorBase_V1 | None = No
|
||||
ensure_kv_transfer_shutdown()
|
||||
|
||||
|
||||
def _empty_kv_cache_config() -> KVCacheConfig:
|
||||
"""Empty cache config used only for PR0 connector assembly."""
|
||||
|
||||
return KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[])
|
||||
def prepare_kv_requests(requests: tuple[DiffusionKVRequest, ...], params: Mapping[str, Any]) -> None:
|
||||
for request in requests:
|
||||
request.kv_transfer_params = dict(params)
|
||||
num_tokens = min(len(request.prompt_token_ids), params["num_transfer_tokens"])
|
||||
request.prompt_token_ids = request.prompt_token_ids[:num_tokens]
|
||||
request.num_prompt_tokens = num_tokens
|
||||
|
||||
|
||||
def _build_native_vllm_config(od_config: OmniDiffusionConfig) -> VllmConfig:
|
||||
from vllm_omni.diffusion.vllm_config import create_diffusion_vllm_config
|
||||
def install_mooncake_cfg_fanout(connector: KVConnectorBase_V1) -> None:
|
||||
"""Account for multiple CFG destinations on one native Mooncake ticket.
|
||||
|
||||
kv_transfer_config = getattr(od_config, "kv_transfer_config", None)
|
||||
assert isinstance(kv_transfer_config, KVTransferConfig)
|
||||
vllm_config = create_diffusion_vllm_config(torch.device("cpu"), od_config)
|
||||
vllm_config.kv_transfer_config = kv_transfer_config
|
||||
return vllm_config
|
||||
vLLM 0.29 initializes ``need_send`` to the paired consumer rank count,
|
||||
but increments ``sent`` per consumer request. Adapt only this producer
|
||||
instance, after KV initialization and before serving requests. Keep the
|
||||
upstream address planning, transport, timeout and completion code intact.
|
||||
"""
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import MooncakeConnector
|
||||
|
||||
if not isinstance(connector, MooncakeConnector):
|
||||
return
|
||||
worker = connector.connector_worker
|
||||
if worker is None or worker.is_kv_consumer or getattr(worker, "_omni_cfg_fanout_installed", False):
|
||||
return
|
||||
build_transfer_params = worker._build_transfer_params
|
||||
|
||||
async def build_with_fanout(ready_reqs, agent_meta, local_regions, remote_regions):
|
||||
# commit_kv_load registers all rows before build_connector_meta. Thus
|
||||
# each rank's message contains the complete row set for each ticket,
|
||||
# including empty-block notifications. Count the full message, not
|
||||
# just the subset whose producer-ready events fired in this iteration.
|
||||
rows_per_ticket = Counter(transfer_id for transfer_id, _ in agent_meta.req_blocks.values())
|
||||
tickets = {send_meta.transfer_id: send_meta for _, send_meta in ready_reqs}
|
||||
for transfer_id, send_meta in tickets.items():
|
||||
rows = rows_per_ticket[transfer_id]
|
||||
previous = getattr(send_meta, "_omni_cfg_rows", None)
|
||||
if rows < 1 or (previous is not None and previous != rows):
|
||||
# Use the upstream transfer-error path: it decrements sending
|
||||
# without incrementing sent, so a malformed rank cannot free
|
||||
# source pages still needed by another rank.
|
||||
return [], [], [], [req_id for req_id, _ in ready_reqs], "Inconsistent Mooncake CFG receive count"
|
||||
# No await between checking and updating: all handlers run on the
|
||||
# sender loop. The marker belongs to the ticket, not to a request-global
|
||||
# variable; it disappears with the upstream ticket on completion/expiry.
|
||||
for transfer_id, send_meta in tickets.items():
|
||||
if getattr(send_meta, "_omni_cfg_rows", None) is None:
|
||||
send_meta.need_send *= rows_per_ticket[transfer_id]
|
||||
send_meta._omni_cfg_rows = rows_per_ticket[transfer_id]
|
||||
return await build_transfer_params(ready_reqs, agent_meta, local_regions, remote_regions)
|
||||
|
||||
worker._build_transfer_params = build_with_fanout # type: ignore[method-assign]
|
||||
setattr(worker, "_omni_cfg_fanout_installed", True)
|
||||
|
||||
|
||||
def commit_kv_load(
|
||||
connector: KVConnectorBase_V1,
|
||||
manager: KVCacheManager,
|
||||
requests: tuple[DiffusionKVRequest, ...],
|
||||
matched_tokens: list[int],
|
||||
) -> set[str]:
|
||||
expected = set()
|
||||
allocations = []
|
||||
# All rows sharing a transfer_id must reach the same connector metadata:
|
||||
# the producer uses this complete per-rank row set for fan-out accounting.
|
||||
# Validate every CFG row before mutating any connector state.
|
||||
for request, num_tokens in zip(requests, matched_tokens, strict=True):
|
||||
blocks = manager.get_blocks(request.request_id)
|
||||
# Mooncake's producer advertises complete physical blocks. Keep every
|
||||
# CFG receiver on that same block boundary so the native connector can
|
||||
# use its normal one-to-one page mapping even when the branches have
|
||||
# different logical prefix lengths. Bytes beyond ``num_tokens`` are
|
||||
# not marked computed and are overwritten by the DiT prefill.
|
||||
transfer_tokens = num_tokens
|
||||
if num_tokens > 0 and request.kv_transfer_params is not None:
|
||||
transfer_tokens = request.kv_transfer_params["num_transfer_tokens"]
|
||||
if type(transfer_tokens) is not int or not num_tokens <= transfer_tokens <= request.num_tokens:
|
||||
raise KVTransferRegistrationError(
|
||||
"Diffusion KV transfer boundary must cover the reusable prefix "
|
||||
f"without exceeding the allocated sequence: reusable={num_tokens}, "
|
||||
f"transfer={transfer_tokens!r}, allocated={request.num_tokens}"
|
||||
)
|
||||
prefix_blocks = KVCacheBlocks(
|
||||
tuple(
|
||||
group[: (transfer_tokens + spec.kv_cache_spec.block_size - 1) // spec.kv_cache_spec.block_size]
|
||||
for group, spec in zip(blocks.blocks, manager.kv_cache_config.kv_cache_groups, strict=True)
|
||||
)
|
||||
)
|
||||
allocations.append((request, prefix_blocks, num_tokens))
|
||||
try:
|
||||
for request, prefix_blocks, num_tokens in allocations:
|
||||
connector.update_state_after_alloc(request, prefix_blocks, num_tokens)
|
||||
request.num_computed_tokens = num_tokens
|
||||
if request.kv_transfer_params is not None:
|
||||
expected.add(request.request_id)
|
||||
except Exception as exc:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import MooncakeConnector
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
if not isinstance(connector, MooncakeConnector):
|
||||
# Unknown connectors may have started I/O during registration.
|
||||
raise
|
||||
# Mooncake only queues metadata here; no Worker has seen addresses yet.
|
||||
# Re-arm its pre-scheduling abort hook to replace even partially
|
||||
# registered CFG receives with empty-block notifications to the producer.
|
||||
for request in requests:
|
||||
if request.kv_transfer_params is not None:
|
||||
request.kv_transfer_params["do_remote_prefill"] = True
|
||||
request.status = RequestStatus.FINISHED_ABORTED
|
||||
delay_free, _ = connector.request_finished(request, [])
|
||||
if delay_free:
|
||||
raise RuntimeError("Connector could not cancel an undispatched KV load") from exc
|
||||
raise KVTransferRegistrationError(f"Could not register diffusion KV receive: {exc}") from exc
|
||||
return expected
|
||||
|
||||
|
||||
def wait_for_kv_load(
|
||||
active_connector: ActiveKVConnector, scheduler_output: DiffusionSchedulerOutput, timeout: float
|
||||
) -> KVConnectorOutput:
|
||||
connector = active_connector.kv_connector
|
||||
active_connector.pre_forward(scheduler_output)
|
||||
pending = set(scheduler_output.kv_transfer_request_ids)
|
||||
finished_ids = scheduler_output.kv_finished_request_ids
|
||||
if not pending:
|
||||
output = active_connector.post_forward(finished_ids)
|
||||
if output.invalid_block_ids:
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
return output
|
||||
|
||||
received, sent = set(), set()
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
finished_sending, finished_recving = connector.get_finished(finished_ids)
|
||||
sent.update(finished_sending or ())
|
||||
received.update(finished_recving or ())
|
||||
pending.difference_update(received)
|
||||
if connector.get_block_ids_with_load_errors():
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
if not pending:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
# A timeout is not a cancellation acknowledgement. Return partial
|
||||
# completion; Scheduler quarantines the remaining destination pages.
|
||||
break
|
||||
time.sleep(0.001)
|
||||
output = active_connector.post_forward(finished_ids)
|
||||
output.finished_sending = sent | (output.finished_sending or set())
|
||||
output.finished_recving = received | (output.finished_recving or set())
|
||||
if output.invalid_block_ids:
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
return output
|
||||
|
||||
|
||||
def _validate_kv_transfer_config(config: KVTransferConfig) -> None:
|
||||
engine_id = config.engine_id
|
||||
if not isinstance(engine_id, str) or not engine_id.strip():
|
||||
raise ValueError("Diffusion native kv_transfer_config requires a non-empty engine_id")
|
||||
extra_config = config.kv_connector_extra_config or {}
|
||||
timeout = extra_config.get("transfer_timeout", 60.0)
|
||||
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError("Diffusion transfer_timeout must be a positive finite number of seconds")
|
||||
if config.kv_connector is not None and config.kv_role is None:
|
||||
raise ValueError("Diffusion native kv_transfer_config requires kv_role when kv_connector is set")
|
||||
if config.kv_role not in (None, "kv_consumer", "kv_producer", "kv_both"):
|
||||
|
||||
@@ -8,6 +8,7 @@ from collections.abc import Sequence
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
from vllm_omni.core.sched.utils import free_kv_blocks_in_physical_order
|
||||
from vllm_omni.diffusion.diffusion_kv.metadata import (
|
||||
DiffusionKVMetadata,
|
||||
DiffusionKVSequenceMetadata,
|
||||
@@ -179,7 +180,7 @@ class DiffusionKVCacheManager:
|
||||
requests = self._requests.pop(public_request_id, ())
|
||||
self._metadata.pop(public_request_id, None)
|
||||
for request in reversed(requests):
|
||||
self.native_manager.free(request)
|
||||
free_kv_blocks_in_physical_order(self.native_manager, request)
|
||||
self._internal_request_ids.discard(request.request_id)
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -188,4 +189,4 @@ class DiffusionKVCacheManager:
|
||||
|
||||
def _rollback(self, requests: Sequence[DiffusionKVRequest]) -> None:
|
||||
for request in reversed(requests):
|
||||
self.native_manager.free(request)
|
||||
free_kv_blocks_in_physical_order(self.native_manager, request)
|
||||
@@ -41,6 +41,7 @@ class DiffusionKVSequenceMetadata:
|
||||
seq_len: int
|
||||
block_ids: tuple[list[int], ...]
|
||||
context_ids: tuple[str, ...] = ()
|
||||
num_computed_tokens: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -190,6 +190,10 @@ class DiffusionKVModelRunnerBackend:
|
||||
)
|
||||
return ulysses_degree
|
||||
|
||||
@property
|
||||
def kv_caches_by_layer(self) -> dict[str, torch.Tensor]:
|
||||
return {name: layer.kv_cache for name, layer in self._kv_cache_layer_adapters.items()}
|
||||
|
||||
def _get_max_rows_per_request(self) -> int:
|
||||
max_rows = getattr(self.od_config, "diffusion_kv_max_rows_per_request", None)
|
||||
if type(max_rows) is not int or max_rows <= 0:
|
||||
@@ -245,7 +249,9 @@ class DiffusionKVModelRunnerBackend:
|
||||
for capacity, block_size in zip(unaligned_max_num_blocks_per_group, block_sizes, strict=True)
|
||||
]
|
||||
|
||||
max_num_reqs = max_num_seqs * max_rows_per_request
|
||||
max_num_reqs = max_num_seqs
|
||||
if max_num_reqs % max_rows_per_request:
|
||||
raise ValueError("scheduler_config.max_num_seqs must be a multiple of diffusion_kv_max_rows_per_request")
|
||||
max_num_batched_tokens = getattr(scheduler_config, "max_num_batched_tokens", None)
|
||||
if type(max_num_batched_tokens) is not int or max_num_batched_tokens <= 0:
|
||||
raise ValueError("scheduler_config.max_num_batched_tokens must be a positive integer")
|
||||
@@ -254,9 +260,6 @@ class DiffusionKVModelRunnerBackend:
|
||||
cp_rank = get_dcp_group().rank_in_group if cp_size > 1 else 0
|
||||
cp_interleave = parallel_config.cp_kv_cache_interleave_size
|
||||
|
||||
# Native metadata builders size per-row buffers from max_num_seqs.
|
||||
# A diffusion public request can occupy several sequence/context rows.
|
||||
scheduler_config.max_num_seqs = max_num_reqs
|
||||
kv_caches: list[torch.Tensor | list[torch.Tensor]] = []
|
||||
previous_adapter_caches = {
|
||||
layer_name: adapter.kv_cache for layer_name, adapter in self._kv_cache_layer_adapters.items()
|
||||
@@ -303,7 +306,6 @@ class DiffusionKVModelRunnerBackend:
|
||||
self.vllm_config,
|
||||
)
|
||||
except Exception:
|
||||
scheduler_config.max_num_seqs = max_num_seqs
|
||||
for layer_name, previous_cache in previous_adapter_caches.items():
|
||||
self._kv_cache_layer_adapters[layer_name].kv_cache = previous_cache
|
||||
raise
|
||||
@@ -591,7 +593,7 @@ class DiffusionKVModelRunnerBackend:
|
||||
)
|
||||
raise RuntimeError(f"Diffusion KV request state is missing logical length for {identity!r}")
|
||||
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str]) -> int:
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str | tuple[str, int]]) -> int:
|
||||
"""Retire Worker rows without logically freeing Scheduler-owned blocks."""
|
||||
if (
|
||||
not is_scheduler_paged_kv_mode(
|
||||
@@ -600,11 +602,25 @@ class DiffusionKVModelRunnerBackend:
|
||||
or self.block_tables is None
|
||||
):
|
||||
return 0
|
||||
request_id_set = set(request_ids)
|
||||
request_generations = {
|
||||
request_id: generation
|
||||
for item in request_ids
|
||||
if isinstance(item, tuple)
|
||||
for request_id, generation in (item,)
|
||||
if isinstance(request_id, str) and type(generation) is int
|
||||
}
|
||||
request_id_set = {item if isinstance(item, str) else item[0] for item in request_ids}
|
||||
identities_and_rows = [
|
||||
(identity, row)
|
||||
for identity, row in self._diffusion_kv_identity_to_row.items()
|
||||
if identity[0] in request_id_set
|
||||
and (
|
||||
identity[0] not in request_generations
|
||||
or (
|
||||
(request_state := self._diffusion_kv_request_states.get(identity[0])) is not None
|
||||
and request_state.generation == request_generations[identity[0]]
|
||||
)
|
||||
)
|
||||
]
|
||||
rows = [row for _, row in identities_and_rows]
|
||||
if rows:
|
||||
@@ -620,9 +636,10 @@ class DiffusionKVModelRunnerBackend:
|
||||
]
|
||||
self._apply_rows(rows, installs)
|
||||
|
||||
removed_request_ids = {identity[0] for identity, _ in identities_and_rows}
|
||||
for identity, _ in identities_and_rows:
|
||||
del self._diffusion_kv_identity_to_row[identity]
|
||||
for request_id in request_id_set:
|
||||
for request_id in removed_request_ids:
|
||||
self._diffusion_kv_request_states.pop(request_id, None)
|
||||
self._diffusion_kv_free_rows.extend(rows)
|
||||
self._diffusion_kv_free_rows.sort(reverse=True)
|
||||
|
||||
@@ -84,12 +84,14 @@ class DiffusionPagedAttentionLayerAdapter(AttentionLayerBase):
|
||||
attention_config = vllm_config.attention_config
|
||||
previous_backend = attention_config.backend
|
||||
previous_backend_per_kind = attention_config.backend_per_kind
|
||||
previous_pcp_size = vllm_config.parallel_config.prefill_context_parallel_size
|
||||
try:
|
||||
# This is a portable vLLM backend request. The active platform
|
||||
# resolves it to its native implementation, such as FlashAttention
|
||||
# on CUDA or AscendAttentionBackend on NPU.
|
||||
attention_config.backend = AttentionBackendEnum.FLASH_ATTN
|
||||
attention_config.backend_per_kind = {}
|
||||
vllm_config.parallel_config.prefill_context_parallel_size = 1
|
||||
with set_current_vllm_config(vllm_config):
|
||||
attn_backend = get_attn_backend(
|
||||
head_size=spec.head_size,
|
||||
@@ -101,6 +103,7 @@ class DiffusionPagedAttentionLayerAdapter(AttentionLayerBase):
|
||||
finally:
|
||||
attention_config.backend = previous_backend
|
||||
attention_config.backend_per_kind = previous_backend_per_kind
|
||||
vllm_config.parallel_config.prefill_context_parallel_size = previous_pcp_size
|
||||
attn_backend = current_omni_platform.get_diffusion_paged_kv_attn_backend(
|
||||
attn_backend,
|
||||
ulysses_degree=ulysses_degree,
|
||||
@@ -758,6 +761,19 @@ class DiffusionPagedAttentionAdapter:
|
||||
slot_mappings=slot_mappings,
|
||||
causal=(row_segments[0].mode == "causal"),
|
||||
)
|
||||
# FA2's ``num_splits=0`` auto policy selects SplitKV for these
|
||||
# already-small piecewise calls. Reuse vLLM's supported metadata
|
||||
# control to select the single-pass kernel and avoid its extra
|
||||
# partial-output/reduction work. Leave newer native backends and
|
||||
# metadata without this control untouched.
|
||||
for layer_name, native_metadata in segment_metadata.items():
|
||||
layer = self.layers.get(layer_name)
|
||||
if (
|
||||
layer is not None
|
||||
and getattr(layer.impl, "vllm_flash_attn_version", None) == 2
|
||||
and hasattr(native_metadata, "max_num_splits")
|
||||
):
|
||||
native_metadata.max_num_splits = 1
|
||||
# FA3's full-CUDA-graph metadata builder reuses one persistent
|
||||
# scheduler buffer across builds. Piecewise attention prepares all
|
||||
# segments before executing any of them, so each segment needs its
|
||||
@@ -901,9 +917,17 @@ class DiffusionPagedAttentionAdapter:
|
||||
raise KeyError(
|
||||
f"No piecewise native attention metadata was built for diffusion layer {layer_name!r}"
|
||||
) from exc
|
||||
# Identical rows are sliced and packed once per segment by the
|
||||
# homogeneous piecewise runner. Keeping the projection view here
|
||||
# avoids first copying the complete Q tensor only to copy each segment
|
||||
# again immediately afterwards. Other native paths still require one
|
||||
# packed query buffer.
|
||||
query_input = query_flat
|
||||
if piecewise_plan is None or piecewise_plan.homogeneous_batch_shape is None:
|
||||
query_input = query_flat.contiguous()
|
||||
return DiffusionPagedAttentionContext(
|
||||
layer=layer,
|
||||
query=query_flat.contiguous(),
|
||||
query=query_input,
|
||||
key_write=key_flat,
|
||||
value_write=value_flat,
|
||||
slot_mapping=slot_mapping,
|
||||
|
||||
@@ -113,8 +113,6 @@ class DiffusionKVRequest:
|
||||
self.shared_prefix_boundary = 0
|
||||
# Opaque request-scoped parameters consumed by an upstream KVConnector.
|
||||
self.kv_transfer_params = kv_transfer_params
|
||||
# Mooncake derives the remote-load length from this list. PR0 carries
|
||||
# the field without creating a placeholder or starting a load.
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
|
||||
@property
|
||||
|
||||
@@ -505,22 +505,8 @@ class WanDistCausalConv3d(nn.Conv3d):
|
||||
self._trim_cache: dict[int, tuple[int, int, int]] = {}
|
||||
|
||||
def forward(self, x: torch.Tensor, cache_x: torch.Tensor | None = None) -> torch.Tensor:
|
||||
padding = list(self._padding)
|
||||
if cache_x is not None and padding[4] > 0:
|
||||
cache_x = cache_x.to(x.device)
|
||||
x = torch.cat([cache_x, x], dim=2)
|
||||
padding[4] -= cache_x.shape[2]
|
||||
|
||||
x = F.pad(x, padding)
|
||||
x_padded, self._halo_recv_top_buf, self._halo_recv_bottom_buf = halo_exchange(
|
||||
x,
|
||||
group=self.group,
|
||||
halo_size=self.halo_size,
|
||||
split_dim=self.split_dim,
|
||||
recv_top_buf=self._halo_recv_top_buf,
|
||||
recv_bottom_buf=self._halo_recv_bottom_buf,
|
||||
)
|
||||
shift, start, upper_bound = self._get_trim_params(x.shape[self.split_tensor_dim])
|
||||
x_padded, local_extent = self._assemble_input(x, cache_x)
|
||||
shift, start, upper_bound = self._get_trim_params(local_extent)
|
||||
if shift:
|
||||
x_padded = _narrow_along_dim(
|
||||
x_padded,
|
||||
@@ -532,6 +518,83 @@ class WanDistCausalConv3d(nn.Conv3d):
|
||||
out = _trim_local_conv_output(out, self.halo_size, start, upper_bound, split_dim=self.split_dim)
|
||||
return _zero_invalid_extent(out, split_dim=self.split_dim)
|
||||
|
||||
def _assemble_input(self, x: torch.Tensor, cache_x: torch.Tensor | None) -> tuple[torch.Tensor, int]:
|
||||
"""Build the conv input -- cached frames, causal/spatial zero padding and the halo columns -- in one pass.
|
||||
|
||||
The straightforward version wrote the activation three times per call: ``torch.cat`` of the cached
|
||||
frames, ``F.pad`` for the causal and spatial zeros, then another ``torch.cat`` to attach the halos the
|
||||
neighbours sent. Every causal conv of the decoder runs this on every latent frame, so at 480x832 that
|
||||
was the largest single source of memory traffic in the decode. Here the final tensor is allocated once
|
||||
and the cached frames and the new frames are copied straight into their slots; only the padding slices
|
||||
are zeroed. The halo rows are exchanged through contiguous send and receive buffers (a P2P op needs a
|
||||
contiguous tensor and the halo slot of a 5D tensor is a strided view) and copied into their slots. The
|
||||
conv sees the same tensor as before, byte for byte.
|
||||
|
||||
Returns the assembled tensor and the extent along the split dimension the trim parameters are keyed by
|
||||
(the extent before halos, as ``halo_exchange`` saw it).
|
||||
"""
|
||||
pad_w0, pad_w1, pad_h0, pad_h1, pad_t0, pad_t1 = self._padding
|
||||
cache_frames = 0
|
||||
if cache_x is not None and pad_t0 > 0:
|
||||
cache_x = cache_x.to(x.device)
|
||||
cache_frames = int(cache_x.shape[2])
|
||||
pad_t0 -= cache_frames
|
||||
assert pad_t0 >= 0, "Wan temporal cache exceeds the causal padding"
|
||||
rank, world_size = _rank_world(self.group)
|
||||
halo = self.halo_size if world_size > 1 else 0
|
||||
halo_h = halo if self.split_dim == "height" else 0
|
||||
halo_w = halo if self.split_dim == "width" else 0
|
||||
|
||||
batch, channels, frames, height, width = x.shape
|
||||
top, left = pad_h0 + halo_h, pad_w0 + halo_w
|
||||
total_frames = pad_t0 + cache_frames + frames + pad_t1
|
||||
total_height = top + height + pad_h1 + halo_h
|
||||
total_width = left + width + pad_w1 + halo_w
|
||||
buf = torch.empty((batch, channels, total_frames, total_height, total_width), dtype=x.dtype, device=x.device)
|
||||
# Zero only what the conv must read as zeros: the causal frames in
|
||||
# front (and any trailing ones) and the spatial padding rows/columns.
|
||||
# The halo columns are filled below.
|
||||
if pad_t0:
|
||||
buf[:, :, :pad_t0].zero_()
|
||||
if pad_t1:
|
||||
buf[:, :, total_frames - pad_t1 :].zero_()
|
||||
if pad_h0:
|
||||
buf[:, :, :, halo_h:top].zero_()
|
||||
if pad_h1:
|
||||
buf[:, :, :, total_height - halo_h - pad_h1 : total_height - halo_h].zero_()
|
||||
if pad_w0:
|
||||
buf[:, :, :, :, halo_w:left].zero_()
|
||||
if pad_w1:
|
||||
buf[:, :, :, :, total_width - halo_w - pad_w1 : total_width - halo_w].zero_()
|
||||
interior = buf[:, :, pad_t0 : pad_t0 + cache_frames + frames, top : top + height, left : left + width]
|
||||
if cache_frames:
|
||||
interior[:, :, :cache_frames].copy_(cache_x)
|
||||
interior[:, :, cache_frames:].copy_(x)
|
||||
else:
|
||||
interior.copy_(x)
|
||||
|
||||
dim = self.split_tensor_dim
|
||||
local_extent = buf.shape[dim] - 2 * halo
|
||||
if halo:
|
||||
# What halo_exchange sends: the padded tensor's first and last
|
||||
# ``halo`` rows along the split dimension, padding included.
|
||||
top_row_ref = _narrow_along_dim(buf, dim, halo, halo)
|
||||
bottom_row_ref = _narrow_along_dim(buf, dim, buf.shape[dim] - 2 * halo, halo)
|
||||
self._halo_recv_top_buf = _ensure_recv_buf(self._halo_recv_top_buf, top_row_ref)
|
||||
self._halo_recv_bottom_buf = _ensure_recv_buf(self._halo_recv_bottom_buf, bottom_row_ref)
|
||||
_halo_exchange_p2p(
|
||||
rank=rank,
|
||||
world_size=world_size,
|
||||
group=self.group,
|
||||
top_row_ref=top_row_ref,
|
||||
bottom_row_ref=bottom_row_ref,
|
||||
recv_top_buf=self._halo_recv_top_buf,
|
||||
recv_bottom_buf=self._halo_recv_bottom_buf,
|
||||
)
|
||||
_narrow_along_dim(buf, dim, 0, halo).copy_(self._halo_recv_top_buf)
|
||||
_narrow_along_dim(buf, dim, buf.shape[dim] - halo, halo).copy_(self._halo_recv_bottom_buf)
|
||||
return buf, local_extent
|
||||
|
||||
def _get_trim_params(self, local_extent: int) -> tuple[int, int, int]:
|
||||
trim_params = self._trim_cache.get(local_extent)
|
||||
if trim_params is None:
|
||||
|
||||
@@ -438,6 +438,17 @@ def init_distributed_environment(
|
||||
"world group already initialized with a different world size"
|
||||
)
|
||||
|
||||
# Now, initialize vLLM's distributed environment; we need to do this before initializing
|
||||
# model parallel in Omni. Otherwise, if we use vLLM's native coordinator, we may run into
|
||||
# issues with _NODE_COUNT / _WORLD (in vLLM, not the Omni _WORLD var above) being unset.
|
||||
vllm_parallel_state.init_distributed_environment(
|
||||
world_size=world_size,
|
||||
rank=rank,
|
||||
distributed_init_method=distributed_init_method,
|
||||
local_rank=local_rank,
|
||||
backend=backend,
|
||||
)
|
||||
|
||||
|
||||
def model_parallel_is_initialized():
|
||||
"""Check if tensor and pipeline parallel groups are initialized."""
|
||||
@@ -1061,8 +1072,8 @@ def destroy_distributed_environment():
|
||||
if _WORLD:
|
||||
_WORLD.destroy()
|
||||
_WORLD = None
|
||||
if torch.distributed.is_initialized():
|
||||
torch.distributed.destroy_process_group()
|
||||
# We only need to destroy / clear the Omni world; this takes care of the torch process groups
|
||||
vllm_parallel_state.destroy_distributed_environment()
|
||||
|
||||
|
||||
def destroy_distributed_env():
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.sched.interface import CachedRequestData
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
@@ -159,7 +165,7 @@ class DiffusionExecutor(ABC):
|
||||
# ranks are not silently dropped.
|
||||
self.collective_rpc("set_kv_cache_configs", args=(kv_cache_configs, resolved_max_model_len))
|
||||
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str]) -> None:
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str | tuple[str, int]]) -> None:
|
||||
"""Clear request rows on every Worker after Scheduler retirement."""
|
||||
|
||||
unique_request_ids = list(dict.fromkeys(request_ids))
|
||||
@@ -170,6 +176,35 @@ class DiffusionExecutor(ABC):
|
||||
args=(unique_request_ids,),
|
||||
)
|
||||
|
||||
def prepare_kv_for_forward(self, scheduler_output: DiffusionSchedulerOutput) -> KVConnectorOutput | None:
|
||||
if scheduler_output.kv_connector_metadata is None:
|
||||
return
|
||||
transfer_output = replace(
|
||||
scheduler_output,
|
||||
scheduled_new_reqs=[],
|
||||
scheduled_cached_reqs=CachedRequestData.make_empty(),
|
||||
kv_prefetch_job=None,
|
||||
)
|
||||
outputs: list[KVConnectorOutput] = self.collective_rpc(
|
||||
"prepare_kv_for_forward",
|
||||
args=(transfer_output,),
|
||||
unique_reply_rank=0,
|
||||
exec_all_ranks=True,
|
||||
)
|
||||
if len(outputs) != self.od_config.num_gpus or any(output.invalid_block_ids for output in outputs):
|
||||
# Missing ranks / invalid pages cannot establish safe ownership.
|
||||
raise RuntimeError("Diffusion KV receive failed on one or more ranks")
|
||||
completed = getattr(self, "_kv_receive_completed_ranks", {})
|
||||
for rank, output in enumerate(outputs):
|
||||
for request_id in output.finished_recving or ():
|
||||
completed.setdefault(request_id, set()).add(rank)
|
||||
finished = {request_id for request_id, ranks in completed.items() if len(ranks) == len(outputs)}
|
||||
for request_id in finished:
|
||||
del completed[request_id]
|
||||
self._kv_receive_completed_ranks = completed
|
||||
outputs[0].finished_recving = finished
|
||||
return outputs[0]
|
||||
|
||||
@abstractmethod
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the executor and release resources."""
|
||||
|
||||
@@ -282,6 +282,47 @@ def set_forward_context_denoise_step_idx(step_idx: int | None) -> None:
|
||||
ensure_active(step_idx)
|
||||
|
||||
|
||||
def get_paged_kv_computed_tokens() -> tuple[int, ...]:
|
||||
runtime = _forward_context.paged_kv_runtime if _forward_context is not None else None
|
||||
if runtime is None:
|
||||
return ()
|
||||
return tuple(row.kv_start_pos for row in runtime.metadata.prefill_rows)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def paged_kv_prefill(sequence_id: int, num_tokens: int):
|
||||
from dataclasses import replace
|
||||
|
||||
runtime = get_forward_context().paged_kv_runtime
|
||||
if runtime is None:
|
||||
raise RuntimeError("Paged KV prefill requires an active runtime")
|
||||
rows = runtime.metadata.prefill_rows
|
||||
matching_rows = [row for row in rows if row.sequence_id == sequence_id]
|
||||
if len(matching_rows) != 1:
|
||||
raise ValueError(
|
||||
f"Paged KV prefill requires exactly one active row for sequence {sequence_id}; found {len(matching_rows)}"
|
||||
)
|
||||
row = matching_rows[0]
|
||||
if type(num_tokens) is not int or not row.kv_start_pos < num_tokens <= row.seq_len:
|
||||
raise ValueError(
|
||||
"Paged KV prefill target must extend the active prefix without exceeding its allocation: "
|
||||
f"start={row.kv_start_pos}, target={num_tokens!r}, allocated={row.seq_len}"
|
||||
)
|
||||
prefill = replace(row, query_len=num_tokens - row.kv_start_pos, seq_len=num_tokens)
|
||||
batch = runtime.adapter.prepare_batch((prefill,))
|
||||
with runtime.adapter.activate(batch):
|
||||
yield
|
||||
runtime.metadata = replace(
|
||||
runtime.metadata,
|
||||
prefill_rows=tuple(
|
||||
replace(item, kv_start_pos=num_tokens, query_len=item.seq_len - num_tokens)
|
||||
if item.sequence_id == sequence_id
|
||||
else item
|
||||
for item in rows
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def set_forward_context_denoise_timestep(timestep: float | None) -> None:
|
||||
"""Set the normalized (descending, 1 -> 0) denoise timestep.
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@ from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionPayload,
|
||||
merge_interaction_metadata,
|
||||
synchronized_monotonic_time,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import supports_interaction_apply
|
||||
from vllm_omni.diffusion.models.interface import SupportsInteractionApply, supports_interaction_apply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -52,7 +53,7 @@ class InteractionCoordinator:
|
||||
|
||||
@property
|
||||
def needs_chunk_media(self) -> bool:
|
||||
"""Whether any registered handler needs chunk ``num_frames``/``fps``."""
|
||||
"""Whether any registered handler needs chunk media/latent counts + fps."""
|
||||
return any(handler.needs_chunk_media for handler in self._handlers.values())
|
||||
|
||||
def get_handler(self, modality: str) -> InteractionHandler:
|
||||
@@ -83,31 +84,109 @@ class InteractionCoordinator:
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
|
||||
def enqueue_parts(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
parts: list[tuple[str, InteractionPayload]],
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Ensure every modality is supported and every payload validates, then enqueue.
|
||||
|
||||
Composite events must not partially mutate queues when a later track is
|
||||
unsupported or carries an invalid payload.
|
||||
"""
|
||||
if not parts:
|
||||
raise ValueError("interaction event requires prompt and/or multi_modal_data")
|
||||
|
||||
# Reconcile rank-local samples so USP/SP shards share one arrival time.
|
||||
received_at = synchronized_monotonic_time(received_at)
|
||||
|
||||
handlers = [(self.get_handler(modality), payload) for modality, payload in parts]
|
||||
for handler, payload in handlers:
|
||||
handler.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
for (modality, payload), (handler, _) in zip(parts, handlers, strict=True):
|
||||
del handler
|
||||
self.enqueue(
|
||||
state,
|
||||
modality=modality,
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
|
||||
def maybe_prepare_initial_session(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
pipeline: SupportsInteractionApply,
|
||||
) -> InteractionChunkMetadata:
|
||||
"""Materialize non-lazy modality sessions before chunk 0 denoise.
|
||||
|
||||
Handlers with ``lazy_initialize_session=False`` (e.g. camera) must exist
|
||||
before the first chunk even with no client enqueue.
|
||||
"""
|
||||
num_media_frames: int | None = None
|
||||
fps: float | None = None
|
||||
num_latent_frames: int | None = None
|
||||
if any(
|
||||
(not handler.lazy_initialize_session) and handler.needs_chunk_media for handler in self._handlers.values()
|
||||
):
|
||||
media = pipeline.peek_chunk_media(state)
|
||||
num_media_frames = media.num_media_frames
|
||||
fps = media.fps
|
||||
num_latent_frames = media.num_latent_frames
|
||||
|
||||
boundary_at = synchronized_monotonic_time()
|
||||
chunk_index = state.chunk_index
|
||||
metas: list[InteractionChunkMetadata] = []
|
||||
for handler in self._handlers_in_apply_order():
|
||||
if handler.lazy_initialize_session:
|
||||
continue
|
||||
meta = handler.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=boundary_at,
|
||||
chunk_index=chunk_index,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
if meta is not None:
|
||||
metas.append(meta)
|
||||
return merge_interaction_metadata(metas)
|
||||
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata:
|
||||
"""Fan out chunk-boundary apply to handlers in stable order (prompt first)."""
|
||||
if chunk_index is None:
|
||||
chunk_index = state.chunk_index
|
||||
metas: list[InteractionChunkMetadata] = []
|
||||
for handler in self._handlers_in_apply_order():
|
||||
if handler.modality not in state.interaction_sessions:
|
||||
# This function is always called at chunk boundary without knowing if an interaction is really enqueued.
|
||||
# `state.interaction_sessions[this modality]` is lazy-populated after the first interaction is enqueued.
|
||||
# So, check here and skip a modality handler if this modality's session is not yet created.
|
||||
if handler.lazy_initialize_session and handler.modality not in state.interaction_sessions:
|
||||
# Lazy modalities skip apply until the first enqueue creates the session.
|
||||
continue
|
||||
meta = handler.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=boundary_at,
|
||||
chunk_index=chunk_index,
|
||||
num_frames=num_frames,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
if meta is not None:
|
||||
metas.append(meta)
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from vllm_omni.diffusion.interaction.types import synchronized_monotonic_time
|
||||
from vllm_omni.diffusion.models.interface import SupportsInteractionApply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
@@ -35,18 +35,21 @@ class InteractionMixin:
|
||||
"onto the pipeline before chunked generation"
|
||||
)
|
||||
|
||||
num_frames: int | None = None
|
||||
num_media_frames: int | None = None
|
||||
fps: float | None = None
|
||||
num_latent_frames: int | None = None
|
||||
if self._interaction_coordinator.needs_chunk_media:
|
||||
media = cast(SupportsInteractionApply, self).peek_chunk_media(state)
|
||||
num_frames = media.num_frames
|
||||
num_media_frames = media.num_media_frames
|
||||
fps = media.fps
|
||||
num_latent_frames = media.num_latent_frames
|
||||
|
||||
merged = self._interaction_coordinator.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=time.monotonic(),
|
||||
num_frames=num_frames,
|
||||
boundary_at=synchronized_monotonic_time(),
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
state.interaction_chunk_metadata = merged
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import ClassVar, Self
|
||||
from typing import ClassVar
|
||||
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
@@ -23,9 +25,14 @@ class InteractionHandler(ABC):
|
||||
"""
|
||||
|
||||
modality: ClassVar[str]
|
||||
# When True, chunk-boundary apply needs ``ChunkMediaSpec`` (num_frames/fps)
|
||||
# When True, chunk-boundary apply needs ``ChunkMediaSpec`` (frame count & fps)
|
||||
# Those information are useful when interaction handler needs interpolation/integration on a frame-by-frame basis
|
||||
needs_chunk_media: ClassVar[bool] = False
|
||||
# When True, the coordinator skips ``apply_at_chunk_boundary`` until a session
|
||||
# exists (normally created on the first enqueue). When False, every chunk
|
||||
# boundary runs apply even with no prior enqueue so the handler can create
|
||||
# its session and materialize default chunk data (e.g. identity camera hold).
|
||||
lazy_initialize_session: ClassVar[bool] = True
|
||||
|
||||
@classmethod
|
||||
def from_pipeline(cls, pipeline: object) -> Self:
|
||||
@@ -37,6 +44,21 @@ class InteractionHandler(ABC):
|
||||
del pipeline
|
||||
return cls()
|
||||
|
||||
@abstractmethod
|
||||
def validate_payload(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Validate a modality payload without mutating request state.
|
||||
|
||||
Used by ``InteractionCoordinator.enqueue_parts`` so composite events
|
||||
fail before any track is queued.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def enqueue(
|
||||
self,
|
||||
@@ -56,7 +78,9 @@ class InteractionHandler(ABC):
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None, # defaults to state.chunk_index when omitted
|
||||
num_frames: int | None = None, # only set when at least one interaction handler needs it
|
||||
fps: float | None = None, # only set when at least one interaction handler needs it
|
||||
# Optional chunk media information. Only present when at least one initialized interaction handler needs it
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance request-local state and materialize this chunk's effects."""
|
||||
@@ -0,0 +1,490 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Camera modality interaction handlers.
|
||||
|
||||
Payload is structural SE(3): ``translation`` (xyz) + unit
|
||||
quaternion ``rotation`` (x, y, z, w). WASD-style key tokens belong in
|
||||
clients, not in the engine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self, override
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionEvent,
|
||||
InteractionMode,
|
||||
InteractionPayload,
|
||||
InteractionSession,
|
||||
resolve_event_frame_offset,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
Vec3 = tuple[float, float, float]
|
||||
# Unit quaternion in ``(x, y, z, w)`` order. Identity is ``(0, 0, 0, 1)``.
|
||||
Quat = tuple[float, float, float, float]
|
||||
|
||||
_IDENTITY_QUAT: Quat = (0.0, 0.0, 0.0, 1.0)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraPose:
|
||||
"""Canonical absolute camera pose used by the shared timeline.
|
||||
|
||||
Coordinates follow Unity semantics: ``+X`` right, ``+Y`` up,
|
||||
``+Z`` forward. Session start is the identity transform;
|
||||
``target`` poses are relative to that origin.
|
||||
"""
|
||||
|
||||
translation: Vec3 = (0.0, 0.0, 0.0)
|
||||
rotation: Quat = _IDENTITY_QUAT
|
||||
|
||||
@classmethod
|
||||
def identity(cls) -> CameraPose:
|
||||
return cls()
|
||||
|
||||
def clone(self) -> CameraPose:
|
||||
return CameraPose(translation=self.translation, rotation=self.rotation)
|
||||
|
||||
def as_matrix(self) -> torch.Tensor:
|
||||
"""Return a 4x4 rigid transform from translation + unit quaternion."""
|
||||
mat = torch.eye(4, dtype=torch.float64)
|
||||
mat[:3, :3] = _quat_to_rotmat(self.rotation)
|
||||
mat[0, 3] = float(self.translation[0])
|
||||
mat[1, 3] = float(self.translation[1])
|
||||
mat[2, 3] = float(self.translation[2])
|
||||
return mat
|
||||
|
||||
@classmethod
|
||||
def from_matrix(cls, matrix: torch.Tensor) -> CameraPose:
|
||||
if matrix.shape != (4, 4):
|
||||
raise ValueError("camera pose matrix must be 4x4")
|
||||
rotation = _rotmat_to_quat(matrix[:3, :3].detach().cpu().double())
|
||||
translation = (
|
||||
float(matrix[0, 3]),
|
||||
float(matrix[1, 3]),
|
||||
float(matrix[2, 3]),
|
||||
)
|
||||
return cls(translation=translation, rotation=rotation)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class QueuedCameraEvent(InteractionEvent):
|
||||
"""Timestamped camera command waiting for the next chunk boundary."""
|
||||
|
||||
# Absolute pose for ``target``; per-frame SE3 delta for ``velocity``.
|
||||
pose: CameraPose = field(default_factory=CameraPose.identity)
|
||||
# Integer frame progress for ``target`` lerps (avoids float reciprocal drift).
|
||||
elapsed_transition_frames: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraSession(InteractionSession):
|
||||
"""Request-local camera timeline under ``state.interaction_sessions['camera']``."""
|
||||
|
||||
current_pose: CameraPose = field(default_factory=CameraPose.identity)
|
||||
pending_events: list[QueuedCameraEvent] = field(default_factory=list)
|
||||
# In-flight command; ``elapsed_transition_chunks`` lives on the event.
|
||||
active_event: QueuedCameraEvent | None = None
|
||||
target_source: CameraPose | None = None
|
||||
# Absolute C2W poses ``[num_latent_frames, 4, 4]`` for the most recent chunk.
|
||||
last_absolute_poses: torch.Tensor | None = None
|
||||
# Since a camera session is not lazily initialized, use this field to mark that a client enqueue is ever received.
|
||||
has_received_input: bool = False
|
||||
|
||||
|
||||
class SE3DeltaCameraHandler(InteractionHandler):
|
||||
"""Generic camera timeline that samples absolute poses per frame.
|
||||
|
||||
* ``mode=target``: lerp toward an absolute pose (relative to session start).
|
||||
* ``mode=velocity``: hold a structural SE3 delta until replaced.
|
||||
|
||||
``received_at`` is resolved on the media grid (``num_media_frames``/``fps``), then mapped onto latent steps.
|
||||
Later integration and ``last_absolute_poses`` aligns with ``num_latent_frames``.
|
||||
"""
|
||||
|
||||
modality: ClassVar[str] = "camera"
|
||||
needs_chunk_media: ClassVar[bool] = True
|
||||
# Camera conditioning must exist every chunk; apply creates the session and
|
||||
# materializes identity/hold poses before any client enqueue.
|
||||
lazy_initialize_session: ClassVar[bool] = False
|
||||
default_transition_chunks: ClassVar[int] = 1
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_pipeline(cls, pipeline: object) -> Self:
|
||||
"""It doesn't need anything from the pipeline (e.g., `encode_prompt` method)"""
|
||||
del pipeline
|
||||
return cls()
|
||||
|
||||
@override
|
||||
def validate_payload(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
if not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
|
||||
mode = payload.get("mode", "target")
|
||||
if mode not in ("target", "velocity"):
|
||||
raise ValueError("camera mode must be 'target' or 'velocity'")
|
||||
data = payload.get("data")
|
||||
if not isinstance(data, Mapping):
|
||||
raise ValueError("camera data must be an object")
|
||||
if "actions" in data:
|
||||
raise ValueError(
|
||||
"camera data.actions (WASD keys) is not accepted by the engine; "
|
||||
"send structural translation/rotation instead"
|
||||
)
|
||||
_parse_pose(data)
|
||||
if mode == "target":
|
||||
duration = self.default_transition_chunks if transition_chunks is None else int(transition_chunks)
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
del state
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
self.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
mode = payload.get("mode", "target")
|
||||
camera_mode = cast(InteractionMode, mode)
|
||||
data = cast(Mapping[str, object], payload.get("data"))
|
||||
pose = _parse_pose(data)
|
||||
if camera_mode == "target":
|
||||
duration = self.default_transition_chunks if transition_chunks is None else int(transition_chunks)
|
||||
else:
|
||||
duration = 0
|
||||
|
||||
session = state.interaction_sessions.setdefault("camera", CameraSession())
|
||||
assert isinstance(session, CameraSession)
|
||||
with session.lock:
|
||||
session.has_received_input = True
|
||||
session.pending_events.append(
|
||||
QueuedCameraEvent(
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
mode=camera_mode,
|
||||
transition_chunks=duration,
|
||||
pose=pose,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance camera state for one chunk and store latent-aligned poses.
|
||||
|
||||
.. note::
|
||||
Hardcoded the following policy of per-frame alignment:
|
||||
|
||||
- Resolve ``received_at`` on the media grid, then map each media index onto a latent step.
|
||||
- Integrate one velocity step per **latent frame**, so holding speed ``0.05`` for a chunk with
|
||||
``num_latent_frames=3`` yields total travel ``0.15``.
|
||||
- ``last_absolute_poses.shape[0] == num_latent_frames``: interpolation is latent-aligned.
|
||||
|
||||
If future models need different scale/alignment policies, can refactor interaction registry
|
||||
to be able to mark a policy.
|
||||
"""
|
||||
del chunk_index
|
||||
if num_media_frames is None or fps is None:
|
||||
raise ValueError("SE3DeltaCameraHandler requires chunk num_media_frames and fps")
|
||||
if num_latent_frames is None:
|
||||
num_latent_frames = num_media_frames
|
||||
if int(num_latent_frames) <= 0:
|
||||
raise ValueError(f"num_latent_frames must be > 0, got {num_latent_frames}")
|
||||
|
||||
session = state.interaction_sessions.setdefault("camera", CameraSession())
|
||||
assert isinstance(session, CameraSession)
|
||||
with session.lock:
|
||||
poses, started, active, completed = self._step_one_chunk(
|
||||
session,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
boundary_at=boundary_at,
|
||||
)
|
||||
if poses:
|
||||
session.last_absolute_poses = torch.stack([p.as_matrix() for p in poses], dim=0)
|
||||
else:
|
||||
session.last_absolute_poses = torch.zeros((0, 4, 4), dtype=torch.float64)
|
||||
|
||||
return InteractionChunkMetadata(
|
||||
started_event_ids=started,
|
||||
active_event_ids=active,
|
||||
completed_event_ids=completed,
|
||||
)
|
||||
|
||||
def _step_one_chunk(
|
||||
self,
|
||||
session: CameraSession,
|
||||
*,
|
||||
num_media_frames: int,
|
||||
fps: float,
|
||||
num_latent_frames: int,
|
||||
boundary_at: float,
|
||||
) -> tuple[list[CameraPose], list[str], list[str], list[str]]:
|
||||
"""Sample absolute poses for this chunk under target/velocity semantics."""
|
||||
num_media_frames = max(int(num_media_frames), 1)
|
||||
num_latent_frames = max(int(num_latent_frames), 1)
|
||||
pending = list(session.pending_events)
|
||||
session.pending_events.clear()
|
||||
|
||||
by_latent: dict[int, list[QueuedCameraEvent]] = {}
|
||||
for event in pending:
|
||||
media_frame = resolve_event_frame_offset(
|
||||
received_at=event.received_at,
|
||||
previous_boundary_at=session.last_boundary_at,
|
||||
num_frames=num_media_frames,
|
||||
fps=fps,
|
||||
)
|
||||
latent_idx = _media_frame_to_latent(
|
||||
media_frame,
|
||||
num_media_frames=num_media_frames,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
by_latent.setdefault(latent_idx, []).append(event)
|
||||
for events in by_latent.values():
|
||||
events.sort(key=lambda item: item.received_at)
|
||||
|
||||
started: list[str] = []
|
||||
completed: list[str] = []
|
||||
seen_completed: set[str] = set()
|
||||
poses: list[CameraPose] = []
|
||||
|
||||
def _mark_completed(event_id: str) -> None:
|
||||
if event_id not in seen_completed:
|
||||
seen_completed.add(event_id)
|
||||
completed.append(event_id)
|
||||
|
||||
for latent_idx in range(num_latent_frames):
|
||||
for event in by_latent.get(latent_idx, []):
|
||||
started.append(event.event_id)
|
||||
cancelled_id = self._activate_event(session, event)
|
||||
if cancelled_id is not None:
|
||||
_mark_completed(cancelled_id)
|
||||
just_completed = self._step_one_frame(session, num_latent_frames)
|
||||
poses.append(session.current_pose.clone())
|
||||
if just_completed is not None:
|
||||
_mark_completed(just_completed)
|
||||
|
||||
active: list[str] = []
|
||||
if session.active_event is not None:
|
||||
active.append(session.active_event.event_id)
|
||||
|
||||
session.last_boundary_at = boundary_at
|
||||
return poses, started, active, completed
|
||||
|
||||
def _activate_event(self, session: CameraSession, event: QueuedCameraEvent) -> str | None:
|
||||
"""Activate ``event``, returning the event_id cancelled by this replacement if any."""
|
||||
cancelled_id: str | None = None
|
||||
if session.active_event is not None and session.active_event.event_id != event.event_id:
|
||||
cancelled_id = session.active_event.event_id
|
||||
|
||||
event.elapsed_transition_chunks = 0.0
|
||||
event.elapsed_transition_frames = 0
|
||||
session.active_event = event
|
||||
if event.mode == "target":
|
||||
session.target_source = session.current_pose.clone()
|
||||
else:
|
||||
session.target_source = None
|
||||
return cancelled_id
|
||||
|
||||
def _clear_active_target(self, session: CameraSession) -> str:
|
||||
"""Snap to the target pose, clear the active target track, and return its event_id."""
|
||||
assert session.active_event is not None and session.active_event.mode == "target"
|
||||
event = session.active_event
|
||||
event_id = event.event_id
|
||||
session.current_pose = event.pose.clone()
|
||||
session.active_event = None
|
||||
session.target_source = None
|
||||
return event_id
|
||||
|
||||
def _step_one_frame(self, session: CameraSession, total_num_frames_this_chunk: int) -> str | None:
|
||||
"""Advance the active camera command by one frame."""
|
||||
event = session.active_event
|
||||
if event is None:
|
||||
return None
|
||||
|
||||
if event.mode == "target":
|
||||
duration = event.transition_chunks
|
||||
source = session.target_source or session.current_pose
|
||||
target = event.pose
|
||||
if duration <= 0:
|
||||
return self._clear_active_target(session)
|
||||
|
||||
total_frames = max(1, int(round(duration * float(total_num_frames_this_chunk))))
|
||||
event.elapsed_transition_frames += 1
|
||||
event.elapsed_transition_chunks = event.elapsed_transition_frames / float(total_num_frames_this_chunk)
|
||||
alpha = min(1.0, event.elapsed_transition_frames / float(total_frames))
|
||||
session.current_pose = _lerp_pose(source, target, alpha)
|
||||
if event.elapsed_transition_frames >= total_frames:
|
||||
return self._clear_active_target(session)
|
||||
return None
|
||||
|
||||
# Velocity: apply the held structural SE3 delta once per frame.
|
||||
session.current_pose = _compose_pose(session.current_pose, event.pose)
|
||||
return None
|
||||
|
||||
|
||||
def _media_frame_to_latent(
|
||||
media_frame: int,
|
||||
*,
|
||||
num_media_frames: int,
|
||||
num_latent_frames: int,
|
||||
) -> int:
|
||||
"""Map a media-timeline frame index onto the latent control grid."""
|
||||
if num_latent_frames <= 1 or num_media_frames <= 1:
|
||||
return 0
|
||||
return min(int(media_frame) * int(num_latent_frames) // int(num_media_frames), num_latent_frames - 1)
|
||||
|
||||
|
||||
def _as_xyz(value: object, *, name: str) -> Vec3:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)) or len(value) != 3:
|
||||
raise ValueError(f"camera {name} must be a length-3 list/tuple")
|
||||
if any(math.isnan(v) or math.isinf(v) for v in value):
|
||||
raise ValueError(f"camera {name} must be non-nan and non-inf")
|
||||
return (float(value[0]), float(value[1]), float(value[2]))
|
||||
|
||||
|
||||
def _as_quat(value: object, *, name: str) -> Quat:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)) or len(value) != 4:
|
||||
raise ValueError(f"camera {name} must be a length-4 list/tuple (x, y, z, w)")
|
||||
if any(math.isnan(v) or math.isinf(v) for v in value):
|
||||
raise ValueError(f"camera {name} must be non-nan and non-inf")
|
||||
return _quat_normalize((float(value[0]), float(value[1]), float(value[2]), float(value[3])))
|
||||
|
||||
|
||||
def _parse_pose(data: Mapping[str, object]) -> CameraPose:
|
||||
translation = _as_xyz(data.get("translation", (0.0, 0.0, 0.0)), name="translation")
|
||||
rotation = _as_quat(data.get("rotation", _IDENTITY_QUAT), name="rotation")
|
||||
return CameraPose(translation=translation, rotation=rotation)
|
||||
|
||||
|
||||
def _lerp(a: float, b: float, alpha: float) -> float:
|
||||
return a + (b - a) * alpha
|
||||
|
||||
|
||||
def _lerp_pose(source: CameraPose, target: CameraPose, alpha: float) -> CameraPose:
|
||||
alpha = min(1.0, max(0.0, alpha))
|
||||
return CameraPose(
|
||||
translation=cast(
|
||||
Vec3,
|
||||
tuple(_lerp(s, t, alpha) for s, t in zip(source.translation, target.translation)),
|
||||
),
|
||||
rotation=_quat_nlerp(source.rotation, target.rotation, alpha),
|
||||
)
|
||||
|
||||
|
||||
def _compose_pose(base: CameraPose, delta: CameraPose) -> CameraPose:
|
||||
"""Apply ``delta`` after ``base`` in the session frame (T_new = T_base @ T_delta)."""
|
||||
return CameraPose.from_matrix(base.as_matrix() @ delta.as_matrix())
|
||||
|
||||
|
||||
def _quat_normalize(q: Quat) -> Quat:
|
||||
x, y, z, w = q
|
||||
norm = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
if norm <= 0.0:
|
||||
raise ValueError("camera rotation quaternion must be non-zero")
|
||||
return (x / norm, y / norm, z / norm, w / norm)
|
||||
|
||||
|
||||
def _quat_nlerp(a: Quat, b: Quat, alpha: float) -> Quat:
|
||||
"""Normalized linear interpolation; flips ``b`` when needed for shortest path."""
|
||||
dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
|
||||
if dot < 0.0:
|
||||
b = (-b[0], -b[1], -b[2], -b[3])
|
||||
return _quat_normalize(
|
||||
(
|
||||
_lerp(a[0], b[0], alpha),
|
||||
_lerp(a[1], b[1], alpha),
|
||||
_lerp(a[2], b[2], alpha),
|
||||
_lerp(a[3], b[3], alpha),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _quat_to_rotmat(q: Quat) -> torch.Tensor:
|
||||
x, y, z, w = q
|
||||
xx, yy, zz = x * x, y * y, z * z
|
||||
xy, xz, yz = x * y, x * z, y * z
|
||||
wx, wy, wz = w * x, w * y, w * z
|
||||
return torch.tensor(
|
||||
[
|
||||
[1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)],
|
||||
[2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)],
|
||||
[2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)],
|
||||
],
|
||||
dtype=torch.float64,
|
||||
)
|
||||
|
||||
|
||||
def _rotmat_to_quat(rotation: torch.Tensor) -> Quat:
|
||||
"""Convert a 3x3 rotation matrix to a unit quaternion ``(x, y, z, w)``."""
|
||||
m = rotation
|
||||
trace = float(m[0, 0] + m[1, 1] + m[2, 2])
|
||||
if trace > 0.0:
|
||||
s = math.sqrt(trace + 1.0) * 2.0
|
||||
w = 0.25 * s
|
||||
x = (float(m[2, 1]) - float(m[1, 2])) / s
|
||||
y = (float(m[0, 2]) - float(m[2, 0])) / s
|
||||
z = (float(m[1, 0]) - float(m[0, 1])) / s
|
||||
elif float(m[0, 0]) > float(m[1, 1]) and float(m[0, 0]) > float(m[2, 2]):
|
||||
s = math.sqrt(1.0 + float(m[0, 0]) - float(m[1, 1]) - float(m[2, 2])) * 2.0
|
||||
w = (float(m[2, 1]) - float(m[1, 2])) / s
|
||||
x = 0.25 * s
|
||||
y = (float(m[0, 1]) + float(m[1, 0])) / s
|
||||
z = (float(m[0, 2]) + float(m[2, 0])) / s
|
||||
elif float(m[1, 1]) > float(m[2, 2]):
|
||||
s = math.sqrt(1.0 + float(m[1, 1]) - float(m[0, 0]) - float(m[2, 2])) * 2.0
|
||||
w = (float(m[0, 2]) - float(m[2, 0])) / s
|
||||
x = (float(m[0, 1]) + float(m[1, 0])) / s
|
||||
y = 0.25 * s
|
||||
z = (float(m[1, 2]) + float(m[2, 1])) / s
|
||||
else:
|
||||
s = math.sqrt(1.0 + float(m[2, 2]) - float(m[0, 0]) - float(m[1, 1])) * 2.0
|
||||
w = (float(m[1, 0]) - float(m[0, 1])) / s
|
||||
x = (float(m[0, 2]) + float(m[2, 0])) / s
|
||||
y = (float(m[1, 2]) + float(m[2, 1])) / s
|
||||
z = 0.25 * s
|
||||
return _quat_normalize((x, y, z, w))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CameraPose",
|
||||
"CameraSession",
|
||||
"QueuedCameraEvent",
|
||||
"SE3DeltaCameraHandler",
|
||||
]
|
||||
@@ -90,6 +90,7 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
"""
|
||||
|
||||
modality: ClassVar[str] = "prompt"
|
||||
lazy_initialize_session: ClassVar[bool] = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -113,16 +114,14 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
)
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
def validate_payload(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Prompt updates are last-write-win and unbuffered at chunk boundary."""
|
||||
prompt = payload.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt:
|
||||
raise ValueError("prompt must be non-empty")
|
||||
@@ -136,6 +135,27 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Prompt updates are last-write-win and unbuffered at chunk boundary."""
|
||||
self.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
prompt = payload.get("prompt")
|
||||
assert isinstance(prompt, str)
|
||||
duration = DEFAULT_TRANSITION_CHUNKS if transition_chunks is None else transition_chunks
|
||||
|
||||
target_prompt_embeds, _ = self._encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=None,
|
||||
@@ -164,12 +184,13 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance or start prompt interpolation before the next chunk."""
|
||||
# Prompt lerp is chunk-LWW; media timeline and caller chunk_index unused.
|
||||
del chunk_index, num_frames, fps
|
||||
del chunk_index, num_media_frames, fps, num_latent_frames
|
||||
session = state.interaction_sessions.get("prompt")
|
||||
assert isinstance(session, PromptSession)
|
||||
|
||||
|
||||
@@ -5,12 +5,13 @@ A pipeline only declares the modalities that it supports.
|
||||
And a pipeline can choose which handler for each modality (there can be more than one handler for a modality).
|
||||
|
||||
Outer key: pipeline architecture name (``od_config.model_class_name``).
|
||||
Inner key: modality name (e.g. ``\"prompt\"``).
|
||||
Inner key: modality name (e.g. ``\"camera\"``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.camera import SE3DeltaCameraHandler
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.prompt import PromptInteractionHandler
|
||||
|
||||
STRUCTURED_HANDLER_REGISTRY: dict[str, dict[str, type[InteractionHandler]]] = {
|
||||
@@ -21,4 +22,7 @@ STRUCTURED_HANDLER_REGISTRY: dict[str, dict[str, type[InteractionHandler]]] = {
|
||||
"HeliosPyramidPipeline": {
|
||||
"prompt": PromptInteractionHandler,
|
||||
},
|
||||
"LingBotWorldCausalDMDPipeline": {
|
||||
"camera": SE3DeltaCameraHandler,
|
||||
},
|
||||
}
|
||||
@@ -1,38 +1,75 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared types for midway interaction handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
|
||||
# Wire payload for one modality track. Handlers validate keys they need.
|
||||
InteractionPayload = Mapping[str, object]
|
||||
|
||||
# Shared command semantics across modalities that support them.
|
||||
# Prompt specialization uses ``"target"`` only.
|
||||
InteractionMode = Literal["target"]
|
||||
# Prompt specialization narrows this to ``"target"`` only.
|
||||
InteractionMode = Literal["target", "velocity"]
|
||||
|
||||
|
||||
def synchronized_monotonic_time(stamp: float | None = None) -> float:
|
||||
"""Return a monotonic timestamp shared across DiT ranks.
|
||||
|
||||
``submit_interaction`` and chunk-boundary apply run as collectives, but
|
||||
``time.monotonic()`` is rank-local. Under USP/SP, inter-rank skew that
|
||||
straddles a ``1/fps`` bucket edge would schedule the same event onto
|
||||
different frames per shard. Rank 0's stamp is broadcast (callers may pass
|
||||
a local sample; non-source ranks' values are ignored).
|
||||
"""
|
||||
if stamp is None:
|
||||
stamp = time.monotonic()
|
||||
if not torch.distributed.is_initialized():
|
||||
return stamp
|
||||
try:
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_world_group
|
||||
|
||||
group = get_world_group()
|
||||
except Exception:
|
||||
return stamp
|
||||
if group.world_size <= 1:
|
||||
return stamp
|
||||
return group.broadcast_object(stamp, src=0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChunkMediaSpec:
|
||||
"""Media extent of one generation chunk, for interaction timeline mapping."""
|
||||
"""Decoded media extent and latent step count for one generation chunk.
|
||||
|
||||
num_frames: int
|
||||
Attributes:
|
||||
num_media_frames: Number of frames in this chunk when decoded into playable media.
|
||||
fps: Frames per second of the media.
|
||||
num_latent_frames: Number of latent frames in this chunk (internal DiT units).
|
||||
"""
|
||||
|
||||
num_media_frames: int
|
||||
fps: float
|
||||
num_latent_frames: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.num_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_frames must be > 0, got {self.num_frames}")
|
||||
if self.num_media_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_media_frames must be > 0, got {self.num_media_frames}")
|
||||
if self.num_latent_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_latent_frames must be > 0, got {self.num_latent_frames}")
|
||||
if self.fps <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.fps must be > 0, got {self.fps}")
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return float(self.num_frames) / float(self.fps)
|
||||
return float(self.num_media_frames) / float(self.fps)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
@@ -41,6 +78,7 @@ class InteractionEvent:
|
||||
|
||||
Example:
|
||||
- ``QueuedPromptEvent`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
- ``QueuedCameraEvent`` in ``vllm_omni.diffusion.interaction.modality_handlers.camera``
|
||||
"""
|
||||
|
||||
event_id: str
|
||||
@@ -60,12 +98,37 @@ class InteractionSession:
|
||||
|
||||
Example:
|
||||
- ``PromptSession`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
- ``CameraSession`` in ``vllm_omni.diffusion.interaction.modality_handlers.camera``
|
||||
"""
|
||||
|
||||
lock: Lock = field(default_factory=Lock, repr=False)
|
||||
last_boundary_at: float | None = None
|
||||
|
||||
|
||||
def resolve_event_frame_offset(
|
||||
*,
|
||||
received_at: float,
|
||||
previous_boundary_at: float | None,
|
||||
num_frames: int,
|
||||
fps: float,
|
||||
) -> int:
|
||||
"""Map an event arrival time onto ``[0, num_frames - 1]`` for this chunk.
|
||||
|
||||
* Uses ``floor((received_at - previous_boundary_at) * fps)``.
|
||||
* Events without a prior boundary (or with non-positive fps) map to frame 0.
|
||||
* Offsets past the represented media window are clamped to the final frame.
|
||||
"""
|
||||
num_frames = max(int(num_frames), 1)
|
||||
if previous_boundary_at is None or fps <= 0:
|
||||
return 0
|
||||
offset = math.floor((received_at - previous_boundary_at) * float(fps))
|
||||
if offset < 0:
|
||||
return 0
|
||||
if offset >= num_frames:
|
||||
return num_frames - 1
|
||||
return int(offset)
|
||||
|
||||
|
||||
@dataclass
|
||||
class InteractionChunkMetadata:
|
||||
"""Per-modality (or merged) event-id bookkeeping for one chunk boundary."""
|
||||
|
||||
@@ -124,7 +124,8 @@ if HAS_TRITON:
|
||||
eps: tl.constexpr,
|
||||
heads_per_program: tl.constexpr,
|
||||
):
|
||||
token = tl.program_id(0)
|
||||
# Long-video Q/K views can span more than 2**31 elements of fused QKV storage.
|
||||
token = tl.program_id(0).to(tl.int64)
|
||||
head_group = tl.program_id(1)
|
||||
heads = head_group * heads_per_program + tl.arange(0, heads_per_program)
|
||||
dims = tl.arange(0, head_dim)
|
||||
@@ -216,7 +217,8 @@ if HAS_TRITON:
|
||||
(partial rotary or lane padding) the output is the normalized value
|
||||
unchanged.
|
||||
"""
|
||||
token = tl.program_id(0)
|
||||
# Long-video Q/K views can span more than 2**31 elements of fused QKV storage.
|
||||
token = tl.program_id(0).to(tl.int64)
|
||||
head_group = tl.program_id(1)
|
||||
dims = tl.arange(0, padded_dim)
|
||||
dim_mask = dims < head_dim
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Bit-exact paired Q/K full-width interleaved RoPE for CUDA.
|
||||
|
||||
The operator accepts already-normalized BF16 query and key tensors in BSND
|
||||
layout and full-width FP32 cosine/sine tables. It deliberately performs two
|
||||
round-to-nearest FP32 multiplies followed by one round-to-nearest FP32 add,
|
||||
then rounds only once when storing BF16 output. This matches Diffusers'
|
||||
``apply_rotary_emb`` arithmetic while combining its separate Q and K calls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch.library import Library
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
_HEAD_DIM = 128
|
||||
_HEADS_PER_PROGRAM = 4
|
||||
|
||||
|
||||
if HAS_TRITON:
|
||||
|
||||
@triton.jit
|
||||
def _mul_rn_f32(x, y):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="mul.rn.f32 $0, $1, $2;",
|
||||
constraints="=f,f,f",
|
||||
args=[x, y],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _add_rn_f32(x, y):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="add.rn.f32 $0, $1, $2;",
|
||||
constraints="=f,f,f",
|
||||
args=[x, y],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
@triton.jit
|
||||
def _qk_rope_exact_kernel(
|
||||
q_ptr,
|
||||
k_ptr,
|
||||
cos_ptr,
|
||||
sin_ptr,
|
||||
q_output_ptr,
|
||||
k_output_ptr,
|
||||
q_stride_token,
|
||||
q_stride_head,
|
||||
q_stride_dim,
|
||||
k_stride_token,
|
||||
k_stride_head,
|
||||
k_stride_dim,
|
||||
q_output_stride_token,
|
||||
q_output_stride_head,
|
||||
q_output_stride_dim,
|
||||
k_output_stride_token,
|
||||
k_output_stride_head,
|
||||
k_output_stride_dim,
|
||||
table_stride_sequence,
|
||||
table_stride_dim,
|
||||
sequence,
|
||||
num_heads: tl.constexpr,
|
||||
head_dim: tl.constexpr,
|
||||
heads_per_program: tl.constexpr,
|
||||
):
|
||||
token = tl.program_id(0)
|
||||
group = tl.program_id(1)
|
||||
is_key = tl.program_id(2) == 1
|
||||
heads = group * heads_per_program + tl.arange(0, heads_per_program)
|
||||
dims = tl.arange(0, head_dim)
|
||||
valid = heads[:, None] < num_heads
|
||||
|
||||
q_offsets = token * q_stride_token + heads[:, None] * q_stride_head + dims[None, :] * q_stride_dim
|
||||
k_offsets = token * k_stride_token + heads[:, None] * k_stride_head + dims[None, :] * k_stride_dim
|
||||
input_ptrs = tl.where(is_key, k_ptr + k_offsets, q_ptr + q_offsets)
|
||||
|
||||
pair_dims = dims ^ 1
|
||||
q_pair_offsets = token * q_stride_token + heads[:, None] * q_stride_head + pair_dims[None, :] * q_stride_dim
|
||||
k_pair_offsets = token * k_stride_token + heads[:, None] * k_stride_head + pair_dims[None, :] * k_stride_dim
|
||||
pair_ptrs = tl.where(is_key, k_ptr + k_pair_offsets, q_ptr + q_pair_offsets)
|
||||
values = tl.load(input_ptrs, mask=valid, other=0.0).to(tl.float32)
|
||||
pairs = tl.load(pair_ptrs, mask=valid, other=0.0).to(tl.float32)
|
||||
signed_pairs = tl.where((dims[None, :] & 1) == 0, -pairs, pairs)
|
||||
|
||||
sequence_index = token % sequence
|
||||
table_offsets = sequence_index * table_stride_sequence + dims * table_stride_dim
|
||||
cos = tl.load(cos_ptr + table_offsets).to(tl.float32)[None, :]
|
||||
sin = tl.load(sin_ptr + table_offsets).to(tl.float32)[None, :]
|
||||
|
||||
# Do not let the compiler contract this expression into an FMA. The
|
||||
# reference has two independently rounded FP32 multiplies and one
|
||||
# independently rounded FP32 add, followed by the final BF16 store.
|
||||
first = _mul_rn_f32(values, cos)
|
||||
second = _mul_rn_f32(signed_pairs, sin)
|
||||
output = _add_rn_f32(first, second)
|
||||
q_output_offsets = (
|
||||
token * q_output_stride_token + heads[:, None] * q_output_stride_head + dims[None, :] * q_output_stride_dim
|
||||
)
|
||||
k_output_offsets = (
|
||||
token * k_output_stride_token + heads[:, None] * k_output_stride_head + dims[None, :] * k_output_stride_dim
|
||||
)
|
||||
output_ptrs = tl.where(
|
||||
is_key,
|
||||
k_output_ptr + k_output_offsets,
|
||||
q_output_ptr + q_output_offsets,
|
||||
)
|
||||
tl.store(output_ptrs, output, mask=valid)
|
||||
|
||||
|
||||
def fused_qk_rope_supported(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> bool:
|
||||
"""Return whether the exact CUDA kernel can consume these tensors."""
|
||||
|
||||
if not (
|
||||
HAS_TRITON
|
||||
and torch.version.hip is None
|
||||
and current_platform.is_cuda()
|
||||
and not torch.is_grad_enabled()
|
||||
and q.is_cuda
|
||||
and k.is_cuda
|
||||
and q.device == k.device
|
||||
and q.dtype is torch.bfloat16
|
||||
and k.dtype is q.dtype
|
||||
and q.ndim == 4
|
||||
and k.shape == q.shape
|
||||
and q.numel() > 0
|
||||
and q.is_contiguous()
|
||||
and k.is_contiguous()
|
||||
):
|
||||
return False
|
||||
|
||||
batch, sequence, _heads, head_dim = q.shape
|
||||
del batch
|
||||
if head_dim != _HEAD_DIM:
|
||||
return False
|
||||
if not (
|
||||
cos.shape == (sequence, head_dim)
|
||||
and sin.shape == cos.shape
|
||||
and cos.device == q.device
|
||||
and sin.device == q.device
|
||||
and cos.dtype is torch.float32
|
||||
and sin.dtype is torch.float32
|
||||
and cos.is_contiguous()
|
||||
and sin.is_contiguous()
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _launch_fused_qk_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
q_output = torch.empty_like(q)
|
||||
k_output = torch.empty_like(k)
|
||||
tokens = q.shape[0] * q.shape[1]
|
||||
head_groups = triton.cdiv(q.shape[2], _HEADS_PER_PROGRAM)
|
||||
grid = (tokens, head_groups, 2)
|
||||
with torch.accelerator.device_index(q.device.index):
|
||||
_qk_rope_exact_kernel[grid](
|
||||
q,
|
||||
k,
|
||||
cos,
|
||||
sin,
|
||||
q_output,
|
||||
k_output,
|
||||
q.stride(1),
|
||||
q.stride(2),
|
||||
q.stride(3),
|
||||
k.stride(1),
|
||||
k.stride(2),
|
||||
k.stride(3),
|
||||
q_output.stride(1),
|
||||
q_output.stride(2),
|
||||
q_output.stride(3),
|
||||
k_output.stride(1),
|
||||
k_output.stride(2),
|
||||
k_output.stride(3),
|
||||
cos.stride(0),
|
||||
cos.stride(1),
|
||||
q.shape[1],
|
||||
num_heads=q.shape[2],
|
||||
head_dim=q.shape[-1],
|
||||
heads_per_program=_HEADS_PER_PROGRAM,
|
||||
num_warps=4,
|
||||
)
|
||||
return q_output, k_output
|
||||
|
||||
|
||||
def _fused_qk_rope_impl(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if not fused_qk_rope_supported(q, k, cos, sin):
|
||||
raise ValueError("fused_qk_rope received unsupported inputs")
|
||||
return _launch_fused_qk_rope(q, k, cos, sin)
|
||||
|
||||
|
||||
def _fused_qk_rope_fake(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del cos, sin
|
||||
return torch.empty_like(q), torch.empty_like(k)
|
||||
|
||||
|
||||
_OMNI_OP_LIB = Library("vllm_omni", "FRAGMENT")
|
||||
if not hasattr(torch.ops.vllm_omni, "fused_qk_rope"):
|
||||
direct_register_custom_op(
|
||||
op_name="fused_qk_rope",
|
||||
op_func=_fused_qk_rope_impl,
|
||||
fake_impl=_fused_qk_rope_fake,
|
||||
mutates_args=[],
|
||||
target_lib=_OMNI_OP_LIB,
|
||||
)
|
||||
|
||||
|
||||
def fused_qk_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply paired full-width adjacent/interleaved RoPE on CUDA."""
|
||||
|
||||
if not fused_qk_rope_supported(q, k, cos, sin):
|
||||
raise ValueError("fused_qk_rope requires contiguous CUDA BF16 Q/K and contiguous full-width CUDA FP32 tables")
|
||||
return torch.ops.vllm_omni.fused_qk_rope(q, k, cos, sin)
|
||||
|
||||
|
||||
__all__ = ["fused_qk_rope", "fused_qk_rope_supported"]
|
||||
@@ -112,13 +112,16 @@ def _rms_norm_indexed_scale_shift_kernel(
|
||||
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
variance = tl.sum(x * x, axis=0) / hidden_size
|
||||
# Keep RMSNorm and AdaLN intermediates in FP32 on every architecture.
|
||||
# Rounding the normalized value to BF16 before the affine transform
|
||||
# changes the fused computation, including values at rounding boundaries.
|
||||
normalized = x * tl.rsqrt(variance + eps) * weight
|
||||
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
output = normalized * (1.0 + scale) + shift
|
||||
tl.store(
|
||||
output_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
output,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
@@ -162,9 +165,10 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
|
||||
normalized = updated * tl.rsqrt(variance + eps) * weight
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
output = normalized * (1.0 + scale) + shift
|
||||
tl.store(
|
||||
modulated_out_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
output,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from importlib.util import find_spec
|
||||
|
||||
import torch
|
||||
@@ -163,75 +166,3 @@ class RMSNorm(CustomOp):
|
||||
out = self.weight.to(torch.float32) * out
|
||||
out = out.to(input_dtype)
|
||||
return (out, residual) if residual is not None else out
|
||||
|
||||
|
||||
class RMSNormVAE(CustomOp):
|
||||
"""Root Mean Square Layer Normalization for Channel-First or Last"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
channel_first: bool = True,
|
||||
images: bool = True,
|
||||
bias: bool = False,
|
||||
epsilon: float = 1e-6,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
broadcastable_dims = (1, 1, 1) if not images else (1, 1)
|
||||
shape = (dim, *broadcastable_dims) if channel_first else (dim,)
|
||||
|
||||
self.channel_first = channel_first
|
||||
self.scale = dim**0.5
|
||||
self.gamma = nn.Parameter(torch.ones(shape))
|
||||
self.bias = nn.Parameter(torch.zeros(shape)) if bias else None
|
||||
self.epsilon = epsilon
|
||||
|
||||
self.gamma_rmsnorm = None
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_hip(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_npu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
import torch_npu
|
||||
|
||||
if self.gamma_rmsnorm is None:
|
||||
self.gamma_rmsnorm = self.gamma.reshape(-1)
|
||||
|
||||
if self.channel_first:
|
||||
x = x.transpose(1, -1)
|
||||
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0].transpose(1, -1)
|
||||
else:
|
||||
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0]
|
||||
|
||||
if self.bias is not None:
|
||||
out = out + self.bias
|
||||
return out
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
out = (
|
||||
F.normalize(
|
||||
x,
|
||||
dim=(1 if self.channel_first else -1),
|
||||
eps=self.epsilon,
|
||||
)
|
||||
* self.scale
|
||||
* self.gamma
|
||||
)
|
||||
if self.bias is not None:
|
||||
out = out + self.bias
|
||||
return out
|
||||
@@ -344,140 +344,6 @@ def apply_rope_to_qk(
|
||||
return query, key
|
||||
|
||||
|
||||
class WanS2VRotaryPosEmbed(torch.nn.Module):
|
||||
"""Precompute complex-valued RoPE embeddings for S2V multi-grid positions.
|
||||
|
||||
Owns the base frequency buffer and provides forward() to compute position
|
||||
embeddings given hidden_states (for shape) and grid_sizes.
|
||||
"""
|
||||
|
||||
def __init__(self, num_heads: int, head_dim: int, max_seq_len: int = 1024):
|
||||
super().__init__()
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = head_dim
|
||||
d = head_dim
|
||||
freqs = torch.cat(
|
||||
[
|
||||
self._rope_params(max_seq_len, d - 4 * (d // 6)),
|
||||
self._rope_params(max_seq_len, 2 * (d // 6)),
|
||||
self._rope_params(max_seq_len, 2 * (d // 6)),
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
self.register_buffer("freqs", freqs.to(torch.complex64), persistent=False)
|
||||
|
||||
@staticmethod
|
||||
@torch.amp.autocast(current_omni_platform.device_type, enabled=False)
|
||||
def _rope_params(max_seq_len, dim, theta=10000):
|
||||
if dim % 2 != 0:
|
||||
raise ValueError(f"dim ({dim}) must be even")
|
||||
freqs = torch.outer(
|
||||
torch.arange(max_seq_len), 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float64).div(dim))
|
||||
)
|
||||
return torch.polar(torch.ones_like(freqs), freqs)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
grid_sizes: list,
|
||||
trainable_freqs: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Precompute RoPE embeddings for the given grid layout.
|
||||
|
||||
Args:
|
||||
hidden_states: Tensor [B, S, ...] (used for batch/seq shape and device)
|
||||
grid_sizes: Grid specification (list of [offsets, sizes, totals])
|
||||
trainable_freqs: Optional trainable frequency overrides for t_f < 0
|
||||
|
||||
Returns:
|
||||
Complex tensor [B, S, 1, head_dim//2] of precomputed position embeddings
|
||||
"""
|
||||
b, s = hidden_states.shape[0], hidden_states.shape[1]
|
||||
c = self.head_dim // 2
|
||||
device = hidden_states.device
|
||||
|
||||
freqs = self.freqs.to(device)
|
||||
if trainable_freqs is not None:
|
||||
freqs_input = [freqs, trainable_freqs]
|
||||
else:
|
||||
freqs_input = freqs
|
||||
|
||||
if isinstance(freqs_input, list):
|
||||
trainable_f = freqs_input[1]
|
||||
freqs_split = freqs_input[0]
|
||||
else:
|
||||
trainable_f = None
|
||||
freqs_split = freqs_input
|
||||
freqs_split = freqs_split.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
|
||||
|
||||
output = torch.empty((b, s, 1, c), device=device, dtype=torch.complex64)
|
||||
seq_bucket = [0]
|
||||
if not isinstance(grid_sizes, list):
|
||||
grid_sizes = [grid_sizes]
|
||||
for g in grid_sizes:
|
||||
if not isinstance(g, list):
|
||||
g = [torch.zeros_like(g), g]
|
||||
batch_size = g[0].shape[0]
|
||||
for i in range(batch_size):
|
||||
f_o, h_o, w_o = g[0][i]
|
||||
f, h, w = g[1][i]
|
||||
t_f, t_h, t_w = g[2][i]
|
||||
seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o
|
||||
seq_len = int(seq_f * seq_h * seq_w)
|
||||
if seq_len > 0:
|
||||
if t_f > 0:
|
||||
assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0
|
||||
seq_f_int = int(seq_f)
|
||||
seq_h_int = int(seq_h)
|
||||
seq_w_int = int(seq_w)
|
||||
|
||||
if f_o >= 0:
|
||||
f_sam = torch.linspace(int(f_o), int(t_f + f_o) - 1, seq_f_int, device=device).long()
|
||||
else:
|
||||
f_sam = torch.linspace(int(-f_o), int(-t_f - f_o) + 1, seq_f_int, device=device).long()
|
||||
h_sam = torch.linspace(int(h_o), int(t_h + h_o) - 1, seq_h_int, device=device).long()
|
||||
w_sam = torch.linspace(int(w_o), int(t_w + w_o) - 1, seq_w_int, device=device).long()
|
||||
|
||||
freqs_0 = torch.index_select(freqs_split[0] if f_o >= 0 else freqs_split[0].conj(), 0, f_sam)
|
||||
freqs_0 = freqs_0.view(seq_f_int, 1, 1, -1)
|
||||
|
||||
freqs_i = torch.cat(
|
||||
[
|
||||
freqs_0.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
torch.index_select(freqs_split[1], 0, h_sam)
|
||||
.view(1, seq_h_int, 1, -1)
|
||||
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
torch.index_select(freqs_split[2], 0, w_sam)
|
||||
.view(1, 1, seq_w_int, -1)
|
||||
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
],
|
||||
dim=-1,
|
||||
).reshape(seq_len, 1, -1)
|
||||
elif t_f < 0:
|
||||
freqs_i = trainable_f.unsqueeze(1)
|
||||
output[i, seq_bucket[-1] : seq_bucket[-1] + seq_len] = freqs_i
|
||||
seq_bucket.append(seq_bucket[-1] + seq_len)
|
||||
return output
|
||||
|
||||
|
||||
class RotaryEmbeddingWanS2V(RotaryEmbeddingWan):
|
||||
"""Apply RoPE using precomputed complex freqs for Wan S2V main transformer.
|
||||
|
||||
Converts complex freqs (from WanS2VRotaryPosEmbed) to cos/sin and delegates
|
||||
to RotaryEmbeddingWan for platform-optimized application (float32 kernel).
|
||||
Under TP, freqs has 1 head — broadcasts automatically via cos/sin.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(is_neox_style=False, half_head_dim=True)
|
||||
|
||||
def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
freqs_sliced = freqs[:, : x.size(1)]
|
||||
cos = freqs_sliced.real.to(x.dtype)
|
||||
sin = freqs_sliced.imag.to(x.dtype)
|
||||
return super().forward(x, cos, sin)
|
||||
|
||||
|
||||
class RotaryEmbeddingS2VGrid(torch.nn.Module):
|
||||
"""Grid-based RoPE for S2V motioner/init attention.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from diffusers.loaders.lora_conversion_utils import (
|
||||
from safetensors.torch import load_file
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_from_pipeline
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
@@ -120,6 +121,22 @@ def _prepare_lora_delta(
|
||||
return delta, used_keys
|
||||
|
||||
|
||||
def _resolve_lora_compute_device() -> torch.device | None:
|
||||
"""Return the local accelerator device if actually usable, else None.
|
||||
|
||||
get_local_device() may return cuda:N/npu:N even when no physical device is
|
||||
present, so probe with a tiny allocation before trusting the lookup.
|
||||
"""
|
||||
try:
|
||||
dev = get_local_device()
|
||||
if dev.type != "cpu":
|
||||
torch.empty(1, device=dev)
|
||||
return dev
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _load_lora_state_dict(
|
||||
pretrained_model_name_or_path: str,
|
||||
weights_name: str | None = None,
|
||||
@@ -270,6 +287,9 @@ class LoraLoaderMixin:
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
# Resolve the accelerator fallback once, outside the parameter loop.
|
||||
accel_dev = _resolve_lora_compute_device()
|
||||
|
||||
for name, params in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
@@ -280,7 +300,7 @@ class LoraLoaderMixin:
|
||||
else:
|
||||
continue
|
||||
|
||||
compute_dev = params.device if params.device.type != "cpu" else None
|
||||
compute_dev = params.device if params.device.type != "cpu" else accel_dev
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
@@ -324,6 +344,9 @@ class LoraLoaderMixin:
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
# Resolve the accelerator fallback once, outside the parameter loop.
|
||||
accel_dev = _resolve_lora_compute_device()
|
||||
|
||||
for name, param in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
@@ -334,7 +357,7 @@ class LoraLoaderMixin:
|
||||
else:
|
||||
continue
|
||||
|
||||
compute_dev = param.device if param.device.type != "cpu" else None
|
||||
compute_dev = param.device if param.device.type != "cpu" else accel_dev
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections.abc import Generator, Iterable, Sequence
|
||||
from collections.abc import Callable, Generator, Iterable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -481,8 +481,14 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
)
|
||||
|
||||
def _get_expected_parameter_names(self, model: nn.Module) -> set[str]:
|
||||
"""Return parameter names that should be covered by strict load checks."""
|
||||
all_parameter_names = {name for name, _ in model.named_parameters()}
|
||||
"""Return parameter names that should be covered by strict load checks.
|
||||
|
||||
A parameter with an initialized checkpoint default can explicitly set
|
||||
``is_checkpoint_optional``. It is still loaded when present on disk.
|
||||
"""
|
||||
all_parameter_names = {
|
||||
name for name, param in model.named_parameters() if not getattr(param, "is_checkpoint_optional", False)
|
||||
}
|
||||
sources = self._get_weight_sources(model)
|
||||
|
||||
# Keep strict behavior if no source metadata exists.
|
||||
@@ -673,10 +679,21 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
with set_default_torch_dtype(self.od_config.dtype):
|
||||
if self.parallel_config.use_hsdp:
|
||||
model = self._load_model_with_hsdp(
|
||||
target_device=device, load_format=load_format, custom_pipeline_name=custom_pipeline_name
|
||||
target_device=device,
|
||||
load_format=load_format,
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
offload_after_quant=offload_after_quant,
|
||||
)
|
||||
else:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=False)
|
||||
# The model is headed back to host memory right after online
|
||||
# quantization, so over-wide NPU-unquantizable fallback weights
|
||||
# load straight into host memory instead of round-tripping
|
||||
# through the accelerator (~24 GiB startup peak on MiniMax H3).
|
||||
from vllm_omni.quantization.int8_config import load_unquantizable_fallback_on_cpu
|
||||
|
||||
fallback_ctx = load_unquantizable_fallback_on_cpu() if offload_after_quant else contextlib.nullcontext()
|
||||
with fallback_ctx:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=False)
|
||||
|
||||
resolved_offload = resolve_offload(self.od_config)
|
||||
distributed_offload = resolved_offload.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE
|
||||
@@ -715,8 +732,9 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
if unsupported_methods:
|
||||
raise ValueError(
|
||||
"DLO+AllGather supports online quantization only for "
|
||||
"per-tensor FP8, INT8, and MXFP8 linears; unsupported "
|
||||
f"online methods: {', '.join(sorted(unsupported_methods))}. "
|
||||
"per-tensor FP8, INT8, and MXFP8 linears "
|
||||
"(host-loaded unquantized fallback layers are also allowed); "
|
||||
f"unsupported online methods: {', '.join(sorted(unsupported_methods))}. "
|
||||
"Use rank-local transfer for the affected component or "
|
||||
"disable online quantization."
|
||||
)
|
||||
@@ -853,9 +871,24 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
del model
|
||||
return self.load_fresh_canonical_model()
|
||||
raise
|
||||
self._log_w4a8_fallback_load_summaries(model)
|
||||
self._attach_offload_startup_state(model)
|
||||
return model
|
||||
|
||||
@staticmethod
|
||||
def _log_w4a8_fallback_load_summaries(model: nn.Module) -> None:
|
||||
"""Ask discovered DiTs to report W4A8 state at the common load exit.
|
||||
|
||||
Each DiT derives readiness from its processed layers, so a deferred
|
||||
weight plan cannot be mistaken for the ordinary or HSDP load path.
|
||||
"""
|
||||
components = ModuleDiscovery.discover(model)
|
||||
for component_name, dit in zip(components.dit_names, components.dits):
|
||||
candidate = getattr(dit, "_log_w4a8_fallback_load_summary", None)
|
||||
if callable(candidate):
|
||||
reporter = cast(Callable[[str], None], candidate)
|
||||
reporter(component_name)
|
||||
|
||||
@staticmethod
|
||||
def _request_offload_after_quant(model: nn.Module) -> int:
|
||||
"""Ask online-quant layers to return to host memory once quantized.
|
||||
@@ -909,6 +942,11 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
scale, packing, or aliasing layouts (e.g. dual-scale fp4 pairs,
|
||||
swizzled or NZ hardware formats) and remain fail-closed until
|
||||
validated.
|
||||
|
||||
``UnquantizedHostLinearMethod`` is also allowed: it backs layers too
|
||||
wide for npu_quant_matmul, loads their weights straight into host
|
||||
memory, and its runtime layout is a plain contiguous bf16 weight —
|
||||
identical to the ordinary unquantized path DLO already shards.
|
||||
"""
|
||||
from vllm.model_executor.layers.quantization.online.fp8 import (
|
||||
Fp8PerTensorOnlineLinearMethod,
|
||||
@@ -917,6 +955,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
from vllm_omni.quantization.int8_config import (
|
||||
Int8OnlineLinearMethod,
|
||||
NPUInt8OnlineLinearMethod,
|
||||
UnquantizedHostLinearMethod,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -938,6 +977,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
Fp8PerTensorOnlineLinearMethod,
|
||||
Int8OnlineLinearMethod,
|
||||
NPUInt8OnlineLinearMethod,
|
||||
UnquantizedHostLinearMethod,
|
||||
*mxfp8_online_methods,
|
||||
)
|
||||
|
||||
@@ -1065,6 +1105,16 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
# that have loaded weights tracking currently.
|
||||
if loaded_weights is not None:
|
||||
weights_not_loaded = weights_to_load - loaded_weights
|
||||
# Offline formats can require scales that older online loaders
|
||||
# were allowed to synthesize. Do not apply that legacy tolerance
|
||||
# to an explicitly required checkpoint tensor.
|
||||
required_missing = {
|
||||
name
|
||||
for name, param in model.named_parameters()
|
||||
if name in weights_not_loaded and getattr(param, "is_checkpoint_required", False)
|
||||
}
|
||||
if required_missing:
|
||||
raise ValueError(f"Required weights were not initialized from checkpoint: {required_missing}")
|
||||
# NOTE: if the model is quantized, ignore not_loaded check for scale
|
||||
# weights. ModelOpt FP8 carries a per-tensor `weight_scale` and a
|
||||
# static activation `input_scale`, which the quant method may
|
||||
@@ -1177,6 +1227,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
target_device: torch.device,
|
||||
load_format: str = "default",
|
||||
custom_pipeline_name: str | type[nn.Module] | None = None,
|
||||
offload_after_quant: bool = False,
|
||||
) -> nn.Module:
|
||||
"""Load model with HSDP sharding for inference.
|
||||
|
||||
@@ -1200,40 +1251,54 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
# mapping (QKV fusion, etc.).
|
||||
if load_format == "diffusers":
|
||||
raise ValueError("HSDP is not supported with the diffusers adapter load format")
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=True)
|
||||
world_size = 1
|
||||
rank = 0
|
||||
if torch.distributed.is_initialized():
|
||||
world_size = torch.distributed.get_world_size()
|
||||
rank = torch.distributed.get_rank()
|
||||
# Same host-fallback bound as the ordinary path: with a quant config the
|
||||
# HSDP path initializes on the accelerator (hsdp_defer_to_cpu=False), so
|
||||
# over-wide NPU-unquantizable fallback weights would otherwise round-trip
|
||||
# through the device before apply_hsdp_to_model shards them. Loading them
|
||||
# straight into host memory keeps the load-time device peak at the
|
||||
# quantizable layers alone; sharding then distributes the fallback like
|
||||
# any other parameter. Broadcast loading excludes online quantization
|
||||
# already, so the context below only ever matters on the ordinary
|
||||
# per-rank branch -- but spanning both is harmless.
|
||||
from vllm_omni.quantization.int8_config import load_unquantizable_fallback_on_cpu
|
||||
|
||||
has_online_quant = self._has_online_quant(model) or (
|
||||
self.quant_config is not None and not getattr(self.quant_config, "is_checkpoint_quantized", False)
|
||||
)
|
||||
enable_broadcast = bool(getattr(self.od_config, "enable_broadcast_weight_load", False)) and world_size > 1
|
||||
fallback_ctx = load_unquantizable_fallback_on_cpu() if offload_after_quant else contextlib.nullcontext()
|
||||
with fallback_ctx:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=True)
|
||||
world_size = 1
|
||||
rank = 0
|
||||
if torch.distributed.is_initialized():
|
||||
world_size = torch.distributed.get_world_size()
|
||||
rank = torch.distributed.get_rank()
|
||||
|
||||
if enable_broadcast and has_online_quant:
|
||||
logger.info(
|
||||
"Worker %d: Online quantization detected; falling back to ordinary per-rank weight loading for HSDP",
|
||||
rank,
|
||||
has_online_quant = self._has_online_quant(model) or (
|
||||
self.quant_config is not None and not getattr(self.quant_config, "is_checkpoint_quantized", False)
|
||||
)
|
||||
enable_broadcast = False
|
||||
enable_broadcast = bool(getattr(self.od_config, "enable_broadcast_weight_load", False)) and world_size > 1
|
||||
|
||||
if enable_broadcast:
|
||||
if rank == 0:
|
||||
if enable_broadcast and has_online_quant:
|
||||
logger.info(
|
||||
"Worker %d: Online quantization detected; falling back to ordinary "
|
||||
"per-rank weight loading for HSDP",
|
||||
rank,
|
||||
)
|
||||
enable_broadcast = False
|
||||
|
||||
if enable_broadcast:
|
||||
if rank == 0:
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
self._broadcast_model_weights(model, target_device=target_device, src_rank=0)
|
||||
if (
|
||||
rank != 0
|
||||
and getattr(self.od_config, "lora_backend", None) in (LoRABackend.DISTILL, "distill")
|
||||
and getattr(self.od_config, "lora_path", None)
|
||||
and hasattr(model, "load_lora_weights")
|
||||
):
|
||||
setattr(model, "lora_is_fused", True)
|
||||
else:
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
self._broadcast_model_weights(model, target_device=target_device, src_rank=0)
|
||||
if (
|
||||
rank != 0
|
||||
and getattr(self.od_config, "lora_backend", None) in (LoRABackend.DISTILL, "distill")
|
||||
and getattr(self.od_config, "lora_path", None)
|
||||
and hasattr(model, "load_lora_weights")
|
||||
):
|
||||
setattr(model, "lora_is_fused", True)
|
||||
else:
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
|
||||
# Quantization methods must finish while parameters are ordinary local
|
||||
# tensors. Some post-load transforms use operations (for example,
|
||||
|
||||
@@ -30,8 +30,7 @@ Two environmental factors mask the race on main:
|
||||
``cached_files`` (plural) which batch-resolves every shard listed in the
|
||||
index up-front via ``os.path.isfile`` and raises immediately if any shard
|
||||
is still sitting under its ``*.incomplete`` name. Same wave of v5 changes
|
||||
that introduced ``tie_weights(missing_keys=..., recompute_mapping=...)``
|
||||
(see the Dynin shim in ``dynin_omni_token2text.py``).
|
||||
that introduced ``tie_weights(missing_keys=..., recompute_mapping=...)``.
|
||||
* CI shares ``HF_HOME=/fsx/hf_cache`` across pipelines (both the
|
||||
``vllm-omni`` and ``vllm-omni-rebase`` pipelines mount the same FS). That
|
||||
cache is normally warm for long-lived repos like ``Qwen-Image-Edit-2509``,
|
||||
@@ -195,19 +194,22 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
flock_held = False
|
||||
|
||||
# --- fcntl.flock path ---
|
||||
fcntl_mod: Any = None
|
||||
try:
|
||||
import fcntl # type: ignore[import-not-found]
|
||||
except ImportError: # pragma: no cover - non-POSIX (Windows)
|
||||
fcntl = None
|
||||
import fcntl as _fcntl
|
||||
|
||||
if fcntl is not None:
|
||||
fcntl_mod = _fcntl
|
||||
except ImportError: # pragma: no cover - non-POSIX (Windows)
|
||||
pass
|
||||
|
||||
if fcntl_mod is not None:
|
||||
try:
|
||||
lock_dir = _node_lock_dir()
|
||||
except OSError as exc:
|
||||
logger.warning("Could not allocate lock dir for prefetch of %s (%s); skipping flock", model, exc)
|
||||
fcntl = None # force dotfile fallback
|
||||
fcntl_mod = None # force dotfile fallback
|
||||
|
||||
if fcntl is not None and lock_dir is not None:
|
||||
if fcntl_mod is not None and lock_dir is not None:
|
||||
lock_path = os.path.join(lock_dir, _safe_repo_filename(model))
|
||||
try:
|
||||
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
@@ -217,7 +219,7 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
|
||||
if fd is not None:
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
fcntl_mod.flock(fd, fcntl_mod.LOCK_EX)
|
||||
flock_held = True
|
||||
logger.info("Acquired flock prefetch lock for %s at %s", model, lock_path)
|
||||
except OSError as exc:
|
||||
@@ -249,9 +251,9 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if flock_held and fd is not None:
|
||||
if flock_held and fd is not None and fcntl_mod is not None:
|
||||
with contextlib.suppress(OSError):
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
fcntl_mod.flock(fd, fcntl_mod.LOCK_UN)
|
||||
if fd is not None:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
|
||||
@@ -17,6 +17,10 @@ class DiffusionModelMetadata:
|
||||
supported_control_upload_types: tuple[str, ...] = ()
|
||||
attention_mask_free: bool = False
|
||||
final_output_type: str | None = None
|
||||
# Whether ``/v1/videos`` accepts source media plus per-token video/audio
|
||||
# noise masks for latent initialization. Unknown pipelines must remain
|
||||
# opted out so uploaded files never reach a model that cannot consume them.
|
||||
supports_latent_mask_editing: bool = False
|
||||
|
||||
|
||||
# FLUX.2 Klein supports up to four reference images.
|
||||
@@ -52,6 +56,7 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=9,
|
||||
supports_mixed_reference_inputs=True,
|
||||
supports_latent_mask_editing=True,
|
||||
final_output_type="video",
|
||||
# H3 represents alignment padding as a second packed sequence. The
|
||||
# packed TRTLLM backend consumes cu_seqlens and isolates that padding.
|
||||
@@ -66,6 +71,7 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=9,
|
||||
supports_mixed_reference_inputs=True,
|
||||
supports_latent_mask_editing=True,
|
||||
final_output_type="video",
|
||||
attention_mask_free=True,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from vllm_omni.diffusion.models.anima.pipeline_anima import AnimaPipeline
|
||||
|
||||
__all__ = [
|
||||
"AnimaPipeline",
|
||||
]
|
||||
@@ -0,0 +1,321 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections.abc import Iterable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
|
||||
ANIMA_TEXT_CONDITIONER_CONFIG = {
|
||||
"source_dim": 1024,
|
||||
"target_dim": 1024,
|
||||
"model_dim": 1024,
|
||||
"num_layers": 6,
|
||||
"num_attention_heads": 16,
|
||||
"mlp_ratio": 4.0,
|
||||
"target_vocab_size": 32128,
|
||||
"use_self_attention": True,
|
||||
"use_layer_norm": False,
|
||||
"min_sequence_length": 512,
|
||||
}
|
||||
|
||||
|
||||
def _rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
hidden_states_1 = hidden_states[..., : hidden_states.shape[-1] // 2]
|
||||
hidden_states_2 = hidden_states[..., hidden_states.shape[-1] // 2 :]
|
||||
return torch.cat((-hidden_states_2, hidden_states_1), dim=-1)
|
||||
|
||||
|
||||
def _apply_rotary_pos_emb(
|
||||
hidden_states: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
unsqueeze_dim: int = 1,
|
||||
) -> torch.Tensor:
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
return (hidden_states * cos) + (_rotate_half(hidden_states) * sin)
|
||||
|
||||
|
||||
class AnimaRotaryEmbedding(nn.Module):
|
||||
def __init__(self, head_dim: int, rope_theta: float = 10000.0) -> None:
|
||||
super().__init__()
|
||||
inv_freq = 1.0 / (
|
||||
rope_theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).to(dtype=torch.float32) / head_dim)
|
||||
)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
||||
inv_freq_expanded = inv_freq_expanded.to(hidden_states.device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
return cos.to(dtype=hidden_states.dtype), sin.to(dtype=hidden_states.dtype)
|
||||
|
||||
|
||||
class AnimaTextConditionerAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
query_dim: int,
|
||||
context_dim: int,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = num_attention_heads * attention_head_dim
|
||||
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.attention_head_dim = attention_head_dim
|
||||
self.q_proj = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.q_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
|
||||
self.k_proj = nn.Linear(context_dim, inner_dim, bias=False)
|
||||
self.k_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
|
||||
self.v_proj = nn.Linear(context_dim, inner_dim, bias=False)
|
||||
self.o_proj = nn.Linear(inner_dim, query_dim, bias=False)
|
||||
self.attn = Attention(
|
||||
num_heads=num_attention_heads,
|
||||
head_size=attention_head_dim,
|
||||
softmax_scale=1.0 / (attention_head_dim**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=num_attention_heads,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
encoder_input_shape = encoder_hidden_states.shape[:-1]
|
||||
|
||||
query = self.q_proj(hidden_states)
|
||||
key = self.k_proj(encoder_hidden_states)
|
||||
value = self.v_proj(encoder_hidden_states)
|
||||
|
||||
query = query.view(*input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
key = key.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
value = value.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
|
||||
query = self.q_norm(query)
|
||||
key = self.k_norm(key)
|
||||
|
||||
if position_embeddings is not None:
|
||||
if encoder_position_embeddings is None:
|
||||
raise ValueError("encoder_position_embeddings is required with rotary embeddings.")
|
||||
cos, sin = position_embeddings
|
||||
query = _apply_rotary_pos_emb(query, cos, sin, unsqueeze_dim=2)
|
||||
cos, sin = encoder_position_embeddings
|
||||
key = _apply_rotary_pos_emb(key, cos, sin, unsqueeze_dim=2)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).contiguous()
|
||||
return self.o_proj(hidden_states)
|
||||
|
||||
|
||||
class AnimaTextConditionerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
source_dim: int,
|
||||
model_dim: int,
|
||||
num_attention_heads: int = 16,
|
||||
mlp_ratio: float = 4.0,
|
||||
use_self_attention: bool = True,
|
||||
use_layer_norm: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.use_self_attention = use_self_attention
|
||||
norm_cls = nn.LayerNorm if use_layer_norm else nn.RMSNorm
|
||||
norm_kwargs = {} if use_layer_norm else {"eps": 1e-6}
|
||||
|
||||
if use_self_attention:
|
||||
self.norm_self_attn = norm_cls(model_dim, **norm_kwargs)
|
||||
self.self_attn = AnimaTextConditionerAttention(
|
||||
query_dim=model_dim,
|
||||
context_dim=model_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=model_dim // num_attention_heads,
|
||||
prefix=f"{prefix}.self_attn" if prefix else "self_attn",
|
||||
)
|
||||
|
||||
self.norm_cross_attn = norm_cls(model_dim, **norm_kwargs)
|
||||
self.cross_attn = AnimaTextConditionerAttention(
|
||||
query_dim=model_dim,
|
||||
context_dim=source_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=model_dim // num_attention_heads,
|
||||
prefix=f"{prefix}.cross_attn" if prefix else "cross_attn",
|
||||
)
|
||||
self.norm_mlp = norm_cls(model_dim, **norm_kwargs)
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(model_dim, int(model_dim * mlp_ratio)),
|
||||
nn.GELU(),
|
||||
nn.Linear(int(model_dim * mlp_ratio), model_dim),
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
target_attention_mask: torch.Tensor | None = None,
|
||||
source_attention_mask: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
source_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.use_self_attention:
|
||||
norm_hidden_states = self.norm_self_attn(hidden_states)
|
||||
attn_hidden_states = self.self_attn(
|
||||
norm_hidden_states,
|
||||
attention_mask=target_attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
encoder_position_embeddings=position_embeddings,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states
|
||||
|
||||
norm_hidden_states = self.norm_cross_attn(hidden_states)
|
||||
attn_hidden_states = self.cross_attn(
|
||||
norm_hidden_states,
|
||||
attention_mask=source_attention_mask,
|
||||
encoder_hidden_states=encoder_hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
encoder_position_embeddings=source_position_embeddings,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states
|
||||
hidden_states = hidden_states + self.mlp(self.norm_mlp(hidden_states))
|
||||
return hidden_states
|
||||
|
||||
|
||||
def is_conditioner_block_module(name: str, module: nn.Module) -> bool:
|
||||
return "blocks" in name and name.split(".")[-1].isdigit()
|
||||
|
||||
|
||||
class AnimaTextConditioner(nn.Module):
|
||||
_repeated_blocks = ["AnimaTextConditionerBlock"]
|
||||
_hsdp_shard_conditions = [is_conditioner_block_module]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
source_dim: int = 1024,
|
||||
target_dim: int = 1024,
|
||||
model_dim: int = 1024,
|
||||
num_layers: int = 6,
|
||||
num_attention_heads: int = 16,
|
||||
mlp_ratio: float = 4.0,
|
||||
target_vocab_size: int = 32128,
|
||||
use_self_attention: bool = True,
|
||||
use_layer_norm: bool = False,
|
||||
min_sequence_length: int = 512,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = SimpleNamespace(
|
||||
source_dim=source_dim,
|
||||
target_dim=target_dim,
|
||||
model_dim=model_dim,
|
||||
num_layers=num_layers,
|
||||
num_attention_heads=num_attention_heads,
|
||||
mlp_ratio=mlp_ratio,
|
||||
target_vocab_size=target_vocab_size,
|
||||
use_self_attention=use_self_attention,
|
||||
use_layer_norm=use_layer_norm,
|
||||
min_sequence_length=min_sequence_length,
|
||||
extra_config=kwargs,
|
||||
)
|
||||
self.embed = nn.Embedding(target_vocab_size, target_dim)
|
||||
self.in_proj = nn.Linear(target_dim, model_dim) if model_dim != target_dim else nn.Identity()
|
||||
self.rotary_emb = AnimaRotaryEmbedding(model_dim // num_attention_heads)
|
||||
self.blocks = nn.ModuleList(
|
||||
[
|
||||
AnimaTextConditionerBlock(
|
||||
source_dim=source_dim,
|
||||
model_dim=model_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
mlp_ratio=mlp_ratio,
|
||||
use_self_attention=use_self_attention,
|
||||
use_layer_norm=use_layer_norm,
|
||||
prefix=f"blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
self.out_proj = nn.Linear(model_dim, target_dim)
|
||||
self.norm = nn.RMSNorm(target_dim, eps=1e-6)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
@staticmethod
|
||||
def _prepare_attention_mask(attention_mask: torch.Tensor | None) -> torch.Tensor | None:
|
||||
if attention_mask is None:
|
||||
return None
|
||||
return attention_mask.to(torch.bool)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
source_hidden_states: torch.Tensor,
|
||||
target_input_ids: torch.Tensor,
|
||||
target_attention_mask: torch.Tensor | None = None,
|
||||
source_attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
target_attention_mask = self._prepare_attention_mask(target_attention_mask)
|
||||
source_attention_mask = self._prepare_attention_mask(source_attention_mask)
|
||||
|
||||
hidden_states = self.embed(target_input_ids).to(dtype=source_hidden_states.dtype)
|
||||
hidden_states = self.in_proj(hidden_states)
|
||||
|
||||
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
||||
source_position_ids = torch.arange(source_hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
source_position_embeddings = self.rotary_emb(hidden_states, source_position_ids)
|
||||
|
||||
for block in self.blocks:
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
source_hidden_states,
|
||||
target_attention_mask=target_attention_mask,
|
||||
source_attention_mask=source_attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
source_position_embeddings=source_position_embeddings,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(self.out_proj(hidden_states))
|
||||
|
||||
if target_attention_mask is not None:
|
||||
hidden_states = hidden_states * target_attention_mask.to(hidden_states).unsqueeze(-1)
|
||||
|
||||
if hidden_states.shape[1] < self.config.min_sequence_length:
|
||||
hidden_states = F.pad(hidden_states, (0, 0, 0, self.config.min_sequence_length - hidden_states.shape[1]))
|
||||
|
||||
return hidden_states
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
params = dict(self.named_parameters())
|
||||
loaded = set()
|
||||
for name, tensor in weights:
|
||||
if name not in params:
|
||||
continue
|
||||
param = params[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, tensor)
|
||||
loaded.add(name)
|
||||
return loaded
|
||||
@@ -0,0 +1,705 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections.abc import Iterable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from diffusers.models.embeddings import Timesteps, apply_rotary_emb
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
|
||||
|
||||
ANIMA_TRANSFORMER_CONFIG = {
|
||||
"in_channels": 16,
|
||||
"out_channels": 16,
|
||||
"num_attention_heads": 16,
|
||||
"attention_head_dim": 128,
|
||||
"num_layers": 28,
|
||||
"mlp_ratio": 4.0,
|
||||
"text_embed_dim": 1024,
|
||||
"adaln_lora_dim": 256,
|
||||
"max_size": (128, 240, 240),
|
||||
"patch_size": (1, 2, 2),
|
||||
"rope_scale": (1.0, 4.0, 4.0),
|
||||
"concat_padding_mask": True,
|
||||
"extra_pos_embed_type": None,
|
||||
}
|
||||
|
||||
|
||||
# NOTE: We import and use diffusers' `apply_rotary_emb` instead of a custom native implementation
|
||||
# to prevent numerical drift in bfloat16. Diffusers upcasts queries, keys, and rotary frequency
|
||||
# tensors to float32 before computing the rotation, and casts back to bfloat16 at the end.
|
||||
# Performing the entire computation in bfloat16 accumulates precision errors across the 28
|
||||
# transformer blocks, which is heavily amplified by Classifier-Free Guidance (CFG).
|
||||
|
||||
|
||||
class CosmosPatchEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
patch_size: tuple[int, int, int],
|
||||
bias: bool = True,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.patch_size = patch_size
|
||||
self.proj = nn.Linear(in_channels * patch_size[0] * patch_size[1] * patch_size[2], out_channels, bias=bias)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
||||
p_t, p_h, p_w = self.patch_size
|
||||
hidden_states = hidden_states.reshape(
|
||||
batch_size,
|
||||
num_channels,
|
||||
num_frames // p_t,
|
||||
p_t,
|
||||
height // p_h,
|
||||
p_h,
|
||||
width // p_w,
|
||||
p_w,
|
||||
)
|
||||
hidden_states = hidden_states.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7)
|
||||
return self.proj(hidden_states)
|
||||
|
||||
|
||||
class CosmosTimestepEmbedding(nn.Module):
|
||||
def __init__(self, in_features: int, out_features: int) -> None:
|
||||
super().__init__()
|
||||
self.linear_1 = nn.Linear(in_features, out_features, bias=False)
|
||||
self.activation = nn.SiLU()
|
||||
self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False)
|
||||
|
||||
def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
|
||||
emb = self.linear_1(timesteps)
|
||||
emb = self.activation(emb)
|
||||
return self.linear_2(emb)
|
||||
|
||||
|
||||
class CosmosEmbedding(nn.Module):
|
||||
def __init__(self, embedding_dim: int, condition_dim: int) -> None:
|
||||
super().__init__()
|
||||
self.time_proj = Timesteps(embedding_dim, flip_sin_to_cos=True, downscale_freq_shift=0.0)
|
||||
self.t_embedder = CosmosTimestepEmbedding(embedding_dim, condition_dim)
|
||||
self.norm = nn.RMSNorm(embedding_dim, eps=1e-6)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, timestep: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
timesteps_proj = self.time_proj(timestep).type_as(hidden_states)
|
||||
temb = self.t_embedder(timesteps_proj)
|
||||
embedded_timestep = self.norm(timesteps_proj)
|
||||
return temb, embedded_timestep
|
||||
|
||||
|
||||
class CosmosAdaLayerNorm(nn.Module):
|
||||
def __init__(self, in_features: int, hidden_features: int) -> None:
|
||||
super().__init__()
|
||||
self.embedding_dim = in_features
|
||||
self.activation = nn.SiLU()
|
||||
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
|
||||
self.linear_1 = nn.Linear(in_features, hidden_features, bias=False)
|
||||
self.linear_2 = nn.Linear(hidden_features, 2 * in_features, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
embedded_timestep = self.activation(embedded_timestep)
|
||||
embedded_timestep = self.linear_1(embedded_timestep)
|
||||
embedded_timestep = self.linear_2(embedded_timestep)
|
||||
|
||||
if temb is not None:
|
||||
embedded_timestep = embedded_timestep + temb[..., : 2 * self.embedding_dim]
|
||||
|
||||
shift, scale = embedded_timestep.chunk(2, dim=-1)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if embedded_timestep.ndim == 2:
|
||||
shift, scale = (x.unsqueeze(1) for x in (shift, scale))
|
||||
|
||||
return hidden_states * (1 + scale) + shift
|
||||
|
||||
|
||||
class CosmosAdaLayerNormZero(nn.Module):
|
||||
def __init__(self, in_features: int, hidden_features: int | None = None) -> None:
|
||||
super().__init__()
|
||||
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
|
||||
self.activation = nn.SiLU()
|
||||
self.linear_1 = (
|
||||
nn.Identity() if hidden_features is None else nn.Linear(in_features, hidden_features, bias=False)
|
||||
)
|
||||
self.linear_2 = nn.Linear(hidden_features or in_features, 3 * in_features, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
embedded_timestep = self.activation(embedded_timestep)
|
||||
embedded_timestep = self.linear_1(embedded_timestep)
|
||||
embedded_timestep = self.linear_2(embedded_timestep)
|
||||
|
||||
if temb is not None:
|
||||
embedded_timestep = embedded_timestep + temb
|
||||
|
||||
shift, scale, gate = embedded_timestep.chunk(3, dim=-1)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if embedded_timestep.ndim == 2:
|
||||
shift, scale, gate = (x.unsqueeze(1) for x in (shift, scale, gate))
|
||||
|
||||
hidden_states = hidden_states * (1 + scale) + shift
|
||||
return hidden_states, gate
|
||||
|
||||
|
||||
class CosmosGELU(nn.Module):
|
||||
def __init__(self, dim: int, inner_dim: int, bias: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.proj = nn.Linear(dim, inner_dim, bias=bias)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return F.gelu(self.proj(hidden_states))
|
||||
|
||||
|
||||
class CosmosFeedForward(nn.Module):
|
||||
def __init__(self, dim: int, mult: float = 4.0, bias: bool = False) -> None:
|
||||
super().__init__()
|
||||
inner_dim = int(dim * mult)
|
||||
self.net = nn.ModuleList(
|
||||
[
|
||||
CosmosGELU(dim, inner_dim, bias=bias),
|
||||
nn.Identity(),
|
||||
nn.Linear(inner_dim, dim, bias=bias),
|
||||
]
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
for module in self.net:
|
||||
hidden_states = module(hidden_states)
|
||||
return hidden_states
|
||||
|
||||
|
||||
class CosmosAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
query_dim: int,
|
||||
cross_attention_dim: int | None = None,
|
||||
heads: int = 8,
|
||||
dim_head: int = 64,
|
||||
out_bias: bool = False,
|
||||
img_context: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = heads * dim_head
|
||||
cross_attention_dim = query_dim if cross_attention_dim is None else cross_attention_dim
|
||||
|
||||
self.heads = heads
|
||||
self.dim_head = dim_head
|
||||
self.out_dim = inner_dim
|
||||
self.query_dim = query_dim
|
||||
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=False)
|
||||
self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=False)
|
||||
self.norm_q = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.norm_k = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.to_out = nn.ModuleList([nn.Linear(inner_dim, query_dim, bias=out_bias), nn.Identity()])
|
||||
self.attn = Attention(
|
||||
num_heads=heads,
|
||||
head_size=dim_head,
|
||||
softmax_scale=1.0 / (dim_head**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=heads,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
self.img_context = img_context
|
||||
if img_context:
|
||||
self.q_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.k_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.v_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.q_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.k_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.img_attn = Attention(
|
||||
num_heads=heads,
|
||||
head_size=dim_head,
|
||||
softmax_scale=1.0 / (dim_head**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=heads,
|
||||
prefix=f"{prefix}.img_attn" if prefix else "img_attn",
|
||||
)
|
||||
|
||||
def _attention(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
encoder_seq_len = encoder_hidden_states.shape[1]
|
||||
|
||||
query = self.to_q(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = self.to_k(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
|
||||
value = self.to_v(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
|
||||
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
|
||||
if image_rotary_emb is not None:
|
||||
# We use diffusers' apply_rotary_emb to leverage its internal float32 rotation upcasting
|
||||
# logic, resolving the bfloat16 cumulative precision drift vs. the reference pipeline.
|
||||
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
|
||||
return hidden_states.flatten(2, 3).type_as(query)
|
||||
|
||||
def _image_attention(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
img_context: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
img_seq_len = img_context.shape[1]
|
||||
|
||||
query = self.q_img(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = self.k_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
|
||||
value = self.v_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
|
||||
|
||||
query = self.q_img_norm(query)
|
||||
key = self.k_img_norm(key)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.img_attn(query, key, value, attn_metadata=attn_metadata)
|
||||
return hidden_states.flatten(2, 3).type_as(query)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None] | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.img_context:
|
||||
if not isinstance(encoder_hidden_states, tuple):
|
||||
raise ValueError("Expected encoder_hidden_states as (text_context, img_context).")
|
||||
text_context, img_context = encoder_hidden_states
|
||||
text_mask, img_mask = attention_mask if attention_mask is not None else (None, None)
|
||||
query_states = hidden_states
|
||||
hidden_states = self._attention(query_states, text_context, text_mask, image_rotary_emb)
|
||||
if img_context is not None:
|
||||
hidden_states = hidden_states + self._image_attention(query_states, img_context, img_mask)
|
||||
else:
|
||||
hidden_states = self._attention(hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb)
|
||||
|
||||
hidden_states = self.to_out[0](hidden_states)
|
||||
return self.to_out[1](hidden_states)
|
||||
|
||||
|
||||
class CosmosTransformerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
cross_attention_dim: int,
|
||||
mlp_ratio: float = 4.0,
|
||||
adaln_lora_dim: int = 256,
|
||||
out_bias: bool = False,
|
||||
img_context: bool = False,
|
||||
before_proj: bool = False,
|
||||
after_proj: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
hidden_size = num_attention_heads * attention_head_dim
|
||||
|
||||
self.norm1 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.img_context = img_context
|
||||
self.attn1 = CosmosAttention(
|
||||
query_dim=hidden_size,
|
||||
cross_attention_dim=None,
|
||||
heads=num_attention_heads,
|
||||
dim_head=attention_head_dim,
|
||||
out_bias=out_bias,
|
||||
prefix=f"{prefix}.attn1" if prefix else "attn1",
|
||||
)
|
||||
self.norm2 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.attn2 = CosmosAttention(
|
||||
query_dim=hidden_size,
|
||||
cross_attention_dim=cross_attention_dim,
|
||||
heads=num_attention_heads,
|
||||
dim_head=attention_head_dim,
|
||||
out_bias=out_bias,
|
||||
img_context=img_context,
|
||||
prefix=f"{prefix}.attn2" if prefix else "attn2",
|
||||
)
|
||||
self.norm3 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.ff = CosmosFeedForward(hidden_size, mult=mlp_ratio, bias=out_bias)
|
||||
|
||||
self.before_proj = nn.Linear(hidden_size, hidden_size) if before_proj else None
|
||||
self.after_proj = nn.Linear(hidden_size, hidden_size) if after_proj else None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
extra_pos_emb: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
controlnet_residual: torch.Tensor | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
block_idx: int | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
if self.before_proj is not None:
|
||||
hidden_states = self.before_proj(hidden_states) + latents
|
||||
|
||||
if extra_pos_emb is not None:
|
||||
hidden_states = hidden_states + extra_pos_emb
|
||||
|
||||
norm_hidden_states, gate = self.norm1(hidden_states, embedded_timestep, temb)
|
||||
attn_output = self.attn1(norm_hidden_states, image_rotary_emb=image_rotary_emb)
|
||||
hidden_states = hidden_states + gate * attn_output
|
||||
|
||||
norm_hidden_states, gate = self.norm2(hidden_states, embedded_timestep, temb)
|
||||
attn_output = self.attn2(
|
||||
norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
||||
)
|
||||
hidden_states = hidden_states + gate * attn_output
|
||||
|
||||
norm_hidden_states, gate = self.norm3(hidden_states, embedded_timestep, temb)
|
||||
ff_output = self.ff(norm_hidden_states)
|
||||
hidden_states = hidden_states + gate * ff_output
|
||||
|
||||
if controlnet_residual is not None:
|
||||
if self.after_proj is not None:
|
||||
raise ValueError("controlnet_residual is incompatible with after_proj.")
|
||||
hidden_states = hidden_states + controlnet_residual
|
||||
|
||||
if self.after_proj is not None:
|
||||
return hidden_states, self.after_proj(hidden_states)
|
||||
|
||||
return hidden_states
|
||||
|
||||
|
||||
class CosmosRotaryPosEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
max_size: tuple[int, int, int] = (128, 240, 240),
|
||||
patch_size: tuple[int, int, int] = (1, 2, 2),
|
||||
base_fps: int = 24,
|
||||
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
|
||||
self.patch_size = patch_size
|
||||
self.base_fps = base_fps
|
||||
|
||||
self.dim_h = hidden_size // 6 * 2
|
||||
self.dim_w = hidden_size // 6 * 2
|
||||
self.dim_t = hidden_size - self.dim_h - self.dim_w
|
||||
|
||||
self.h_ntk_factor = rope_scale[1] ** (self.dim_h / (self.dim_h - 2))
|
||||
self.w_ntk_factor = rope_scale[2] ** (self.dim_w / (self.dim_w - 2))
|
||||
self.t_ntk_factor = rope_scale[0] ** (self.dim_t / (self.dim_t - 2))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, fps: float | None = None) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
_, _, num_frames, height, width = hidden_states.shape
|
||||
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
|
||||
device = hidden_states.device
|
||||
|
||||
h_theta = 10000.0 * self.h_ntk_factor
|
||||
w_theta = 10000.0 * self.w_ntk_factor
|
||||
t_theta = 10000.0 * self.t_ntk_factor
|
||||
|
||||
seq = torch.arange(max(self.max_size), device=device, dtype=torch.float32)
|
||||
dim_h_range = torch.arange(0, self.dim_h, 2, device=device, dtype=torch.float32)[: self.dim_h // 2] / self.dim_h
|
||||
dim_w_range = torch.arange(0, self.dim_w, 2, device=device, dtype=torch.float32)[: self.dim_w // 2] / self.dim_w
|
||||
dim_t_range = torch.arange(0, self.dim_t, 2, device=device, dtype=torch.float32)[: self.dim_t // 2] / self.dim_t
|
||||
h_spatial_freqs = 1.0 / (h_theta**dim_h_range)
|
||||
w_spatial_freqs = 1.0 / (w_theta**dim_w_range)
|
||||
temporal_freqs = 1.0 / (t_theta**dim_t_range)
|
||||
|
||||
emb_h = torch.outer(seq[: pe_size[1]], h_spatial_freqs)[None, :, None, :].repeat(pe_size[0], 1, pe_size[2], 1)
|
||||
emb_w = torch.outer(seq[: pe_size[2]], w_spatial_freqs)[None, None, :, :].repeat(pe_size[0], pe_size[1], 1, 1)
|
||||
if fps is None:
|
||||
emb_t = torch.outer(seq[: pe_size[0]], temporal_freqs)
|
||||
else:
|
||||
emb_t = torch.outer(seq[: pe_size[0]] / fps * self.base_fps, temporal_freqs)
|
||||
emb_t = emb_t[:, None, None, :].repeat(1, pe_size[1], pe_size[2], 1)
|
||||
|
||||
freqs = torch.cat([emb_t, emb_h, emb_w] * 2, dim=-1).flatten(0, 2).float()
|
||||
return torch.cos(freqs), torch.sin(freqs)
|
||||
|
||||
|
||||
class CosmosLearnablePositionalEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
max_size: tuple[int, int, int],
|
||||
patch_size: tuple[int, int, int],
|
||||
eps: float = 1e-6,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
|
||||
self.patch_size = patch_size
|
||||
self.eps = eps
|
||||
self.pos_emb_t = nn.Parameter(torch.zeros(self.max_size[0], hidden_size))
|
||||
self.pos_emb_h = nn.Parameter(torch.zeros(self.max_size[1], hidden_size))
|
||||
self.pos_emb_w = nn.Parameter(torch.zeros(self.max_size[2], hidden_size))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, _, num_frames, height, width = hidden_states.shape
|
||||
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
|
||||
|
||||
emb_t = self.pos_emb_t[: pe_size[0]][None, :, None, None, :].repeat(batch_size, 1, pe_size[1], pe_size[2], 1)
|
||||
emb_h = self.pos_emb_h[: pe_size[1]][None, None, :, None, :].repeat(batch_size, pe_size[0], 1, pe_size[2], 1)
|
||||
emb_w = self.pos_emb_w[: pe_size[2]][None, None, None, :, :].repeat(batch_size, pe_size[0], pe_size[1], 1, 1)
|
||||
emb = (emb_t + emb_h + emb_w).flatten(1, 3)
|
||||
|
||||
norm = torch.linalg.vector_norm(emb, dim=-1, keepdim=True, dtype=torch.float32)
|
||||
norm = torch.add(self.eps, norm, alpha=np.sqrt(norm.numel() / emb.numel()))
|
||||
return (emb / norm).type_as(hidden_states)
|
||||
|
||||
|
||||
class AnimaTransformer3DModel(nn.Module):
|
||||
_repeated_blocks = ["CosmosTransformerBlock"]
|
||||
_hsdp_shard_conditions = [is_transformer_block_module]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int = 16,
|
||||
out_channels: int = 16,
|
||||
num_attention_heads: int = 32,
|
||||
attention_head_dim: int = 128,
|
||||
num_layers: int = 28,
|
||||
mlp_ratio: float = 4.0,
|
||||
text_embed_dim: int = 1024,
|
||||
adaln_lora_dim: int = 256,
|
||||
max_size: tuple[int, int, int] = (128, 240, 240),
|
||||
patch_size: tuple[int, int, int] = (1, 2, 2),
|
||||
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
|
||||
concat_padding_mask: bool = True,
|
||||
extra_pos_embed_type: str | None = "learnable",
|
||||
use_crossattn_projection: bool = False,
|
||||
crossattn_proj_in_channels: int = 1024,
|
||||
encoder_hidden_states_channels: int = 1024,
|
||||
controlnet_block_every_n: int | None = None,
|
||||
img_context_dim_in: int | None = None,
|
||||
img_context_num_tokens: int = 256,
|
||||
img_context_dim_out: int = 2048,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
hidden_size = num_attention_heads * attention_head_dim
|
||||
self.config = SimpleNamespace(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
num_layers=num_layers,
|
||||
mlp_ratio=mlp_ratio,
|
||||
text_embed_dim=text_embed_dim,
|
||||
adaln_lora_dim=adaln_lora_dim,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
rope_scale=rope_scale,
|
||||
concat_padding_mask=concat_padding_mask,
|
||||
extra_pos_embed_type=extra_pos_embed_type,
|
||||
use_crossattn_projection=use_crossattn_projection,
|
||||
crossattn_proj_in_channels=crossattn_proj_in_channels,
|
||||
encoder_hidden_states_channels=encoder_hidden_states_channels,
|
||||
controlnet_block_every_n=controlnet_block_every_n,
|
||||
img_context_dim_in=img_context_dim_in,
|
||||
img_context_num_tokens=img_context_num_tokens,
|
||||
img_context_dim_out=img_context_dim_out,
|
||||
extra_config=kwargs,
|
||||
)
|
||||
|
||||
patch_embed_in_channels = in_channels + 1 if concat_padding_mask else in_channels
|
||||
self.patch_embed = CosmosPatchEmbed(patch_embed_in_channels, hidden_size, patch_size, bias=False)
|
||||
self.rope = CosmosRotaryPosEmbed(
|
||||
hidden_size=attention_head_dim,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
rope_scale=rope_scale,
|
||||
)
|
||||
self.learnable_pos_embed: CosmosLearnablePositionalEmbed | None = None
|
||||
if extra_pos_embed_type == "learnable":
|
||||
self.learnable_pos_embed = CosmosLearnablePositionalEmbed(
|
||||
hidden_size=hidden_size,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
)
|
||||
self.time_embed = CosmosEmbedding(hidden_size, hidden_size)
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
CosmosTransformerBlock(
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
cross_attention_dim=text_embed_dim,
|
||||
mlp_ratio=mlp_ratio,
|
||||
adaln_lora_dim=adaln_lora_dim,
|
||||
out_bias=False,
|
||||
img_context=img_context_dim_in is not None and img_context_dim_in > 0,
|
||||
prefix=f"transformer_blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
self.norm_out = CosmosAdaLayerNorm(hidden_size, adaln_lora_dim)
|
||||
self.proj_out = nn.Linear(hidden_size, patch_size[0] * patch_size[1] * patch_size[2] * out_channels, bias=False)
|
||||
|
||||
self.crossattn_proj: nn.Module | None = None
|
||||
if use_crossattn_projection:
|
||||
self.crossattn_proj = nn.Sequential(
|
||||
nn.Linear(crossattn_proj_in_channels, encoder_hidden_states_channels, bias=True),
|
||||
nn.GELU(),
|
||||
)
|
||||
|
||||
self.img_context_proj: nn.Module | None = None
|
||||
if img_context_dim_in:
|
||||
self.img_context_proj = nn.Sequential(
|
||||
nn.Linear(img_context_dim_in, img_context_dim_out, bias=True),
|
||||
nn.GELU(),
|
||||
)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
timestep: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
|
||||
block_controlnet_hidden_states: list[torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
fps: float | None = None,
|
||||
condition_mask: torch.Tensor | None = None,
|
||||
padding_mask: torch.Tensor | None = None,
|
||||
return_dict: bool = True,
|
||||
) -> Transformer2DModelOutput | tuple[torch.Tensor]:
|
||||
batch_size, _, num_frames, height, width = hidden_states.shape
|
||||
|
||||
if condition_mask is not None:
|
||||
hidden_states = torch.cat([hidden_states, condition_mask], dim=1)
|
||||
|
||||
if self.config.concat_padding_mask:
|
||||
if padding_mask is None:
|
||||
raise ValueError("padding_mask is required when concat_padding_mask=True.")
|
||||
padding_mask_resized = F.interpolate(
|
||||
padding_mask,
|
||||
size=list(hidden_states.shape[-2:]),
|
||||
mode="nearest",
|
||||
)
|
||||
hidden_states = torch.cat(
|
||||
[hidden_states, padding_mask_resized.unsqueeze(2).repeat(batch_size, 1, num_frames, 1, 1)],
|
||||
dim=1,
|
||||
)
|
||||
|
||||
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim != 2:
|
||||
attention_mask = attention_mask.squeeze(1).squeeze(1)
|
||||
|
||||
image_rotary_emb = self.rope(hidden_states, fps=fps)
|
||||
extra_pos_emb = self.learnable_pos_embed(hidden_states) if self.learnable_pos_embed is not None else None
|
||||
|
||||
p_t, p_h, p_w = self.config.patch_size
|
||||
post_patch_num_frames = num_frames // p_t
|
||||
post_patch_height = height // p_h
|
||||
post_patch_width = width // p_w
|
||||
|
||||
hidden_states = self.patch_embed(hidden_states)
|
||||
hidden_states = hidden_states.flatten(1, 3)
|
||||
|
||||
if timestep.ndim == 1:
|
||||
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
|
||||
elif timestep.ndim == 5:
|
||||
if timestep.shape != (batch_size, 1, num_frames, 1, 1):
|
||||
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1], got {timestep.shape}.")
|
||||
timestep = timestep.flatten()
|
||||
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
|
||||
temb, embedded_timestep = (
|
||||
x.view(batch_size, post_patch_num_frames, 1, 1, -1)
|
||||
.expand(-1, -1, post_patch_height, post_patch_width, -1)
|
||||
.flatten(1, 3)
|
||||
for x in (temb, embedded_timestep)
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1] or [T], got {timestep.shape}.")
|
||||
|
||||
text_context, img_context = (
|
||||
encoder_hidden_states if isinstance(encoder_hidden_states, tuple) else (encoder_hidden_states, None)
|
||||
)
|
||||
if self.config.use_crossattn_projection:
|
||||
if self.crossattn_proj is None:
|
||||
raise ValueError("crossattn_proj is required when use_crossattn_projection=True.")
|
||||
text_context = self.crossattn_proj(text_context)
|
||||
if img_context is not None and self.config.img_context_dim_in:
|
||||
if self.img_context_proj is None:
|
||||
raise ValueError("img_context_proj is required when img_context_dim_in is set.")
|
||||
img_context = self.img_context_proj(img_context)
|
||||
processed_encoder_hidden_states = (
|
||||
(text_context, img_context) if isinstance(encoder_hidden_states, tuple) else text_context
|
||||
)
|
||||
|
||||
controlnet_block_index_map = {}
|
||||
if block_controlnet_hidden_states is not None:
|
||||
n_blocks = len(self.transformer_blocks)
|
||||
controlnet_block_index_map = {
|
||||
block_idx: block_controlnet_hidden_states[idx]
|
||||
for idx, block_idx in list(enumerate(range(0, n_blocks, self.config.controlnet_block_every_n)))
|
||||
}
|
||||
|
||||
for block_idx, block in enumerate(self.transformer_blocks):
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
processed_encoder_hidden_states,
|
||||
embedded_timestep,
|
||||
temb,
|
||||
image_rotary_emb,
|
||||
extra_pos_emb,
|
||||
attention_mask,
|
||||
controlnet_block_index_map.get(block_idx),
|
||||
)
|
||||
|
||||
hidden_states = self.norm_out(hidden_states, embedded_timestep, temb)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
hidden_states = hidden_states.unflatten(2, (p_h, p_w, p_t, -1))
|
||||
hidden_states = hidden_states.unflatten(1, (post_patch_num_frames, post_patch_height, post_patch_width))
|
||||
hidden_states = hidden_states.permute(0, 7, 1, 6, 2, 4, 3, 5)
|
||||
hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
||||
|
||||
if not return_dict:
|
||||
return (hidden_states,)
|
||||
|
||||
return Transformer2DModelOutput(sample=hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
params = dict(self.named_parameters())
|
||||
loaded = set()
|
||||
for name, tensor in weights:
|
||||
if name not in params:
|
||||
continue
|
||||
param = params[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, tensor)
|
||||
loaded.add(name)
|
||||
return loaded
|
||||
@@ -0,0 +1,795 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from diffusers.image_processor import VaeImageProcessor
|
||||
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from safetensors.torch import load_file
|
||||
from torch import nn
|
||||
from transformers import AutoTokenizer, Qwen3Model, T5TokenizerFast
|
||||
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import DistributedAutoencoderKLQwenImage
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.models.anima.anima_text_conditioner import (
|
||||
ANIMA_TEXT_CONDITIONER_CONFIG,
|
||||
AnimaTextConditioner,
|
||||
)
|
||||
from vllm_omni.diffusion.models.anima.anima_transformer import ANIMA_TRANSFORMER_CONFIG, AnimaTransformer3DModel
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.offloader.config import OffloadStrategy, resolve_offload_strategy
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.utils.size_utils import normalize_min_aligned_size
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ANIMA_VAE_SCALE_FACTOR = 8
|
||||
|
||||
|
||||
def retrieve_timesteps(
|
||||
scheduler: Any,
|
||||
num_inference_steps: int | None = None,
|
||||
device: str | torch.device | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
if timesteps is not None and sigmas is not None:
|
||||
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
||||
if timesteps is not None:
|
||||
if "timesteps" not in inspect.signature(scheduler.set_timesteps).parameters:
|
||||
raise ValueError(
|
||||
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
||||
f" timestep schedules. Please check whether you are using the correct scheduler."
|
||||
)
|
||||
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
elif sigmas is not None:
|
||||
if "sigmas" not in inspect.signature(scheduler.set_timesteps).parameters:
|
||||
raise ValueError(
|
||||
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
||||
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
||||
)
|
||||
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
else:
|
||||
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
if num_inference_steps is None:
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
return cast(torch.Tensor, scheduler_timesteps), num_inference_steps
|
||||
|
||||
|
||||
_ANIMA_ORIGINAL_TRANSFORMER_RENAMES = {
|
||||
"t_embedder.1": "time_embed.t_embedder",
|
||||
"t_embedding_norm": "time_embed.norm",
|
||||
"blocks": "transformer_blocks",
|
||||
"adaln_modulation_self_attn.1": "norm1.linear_1",
|
||||
"adaln_modulation_self_attn.2": "norm1.linear_2",
|
||||
"adaln_modulation_cross_attn.1": "norm2.linear_1",
|
||||
"adaln_modulation_cross_attn.2": "norm2.linear_2",
|
||||
"adaln_modulation_mlp.1": "norm3.linear_1",
|
||||
"adaln_modulation_mlp.2": "norm3.linear_2",
|
||||
"self_attn": "attn1",
|
||||
"cross_attn": "attn2",
|
||||
"q_proj": "to_q",
|
||||
"k_proj": "to_k",
|
||||
"v_proj": "to_v",
|
||||
"output_proj": "to_out.0",
|
||||
"q_norm": "norm_q",
|
||||
"k_norm": "norm_k",
|
||||
"mlp.layer1": "ff.net.0.proj",
|
||||
"mlp.layer2": "ff.net.2",
|
||||
"x_embedder.proj.1": "patch_embed.proj",
|
||||
"final_layer.adaln_modulation.1": "norm_out.linear_1",
|
||||
"final_layer.adaln_modulation.2": "norm_out.linear_2",
|
||||
"final_layer.linear": "proj_out",
|
||||
}
|
||||
|
||||
_ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS = (
|
||||
"accum_video_sample_counter",
|
||||
"accum_image_sample_counter",
|
||||
"accum_iteration",
|
||||
"accum_train_in_hours",
|
||||
"pos_embedder.seq",
|
||||
"pos_embedder.dim_spatial_range",
|
||||
"pos_embedder.dim_temporal_range",
|
||||
"_extra_state",
|
||||
)
|
||||
|
||||
|
||||
def _anima_vae_scale_factor_from_vae(vae: Any) -> int:
|
||||
vae_config = getattr(vae, "config", None)
|
||||
spatial_compression_ratio = getattr(vae_config, "spatial_compression_ratio", None)
|
||||
if spatial_compression_ratio is not None:
|
||||
return int(spatial_compression_ratio)
|
||||
temporal_downsample = getattr(vae, "temperal_downsample", None)
|
||||
if temporal_downsample is not None:
|
||||
return int(2 ** len(temporal_downsample))
|
||||
return ANIMA_VAE_SCALE_FACTOR
|
||||
|
||||
|
||||
def get_anima_post_process_func(od_config: OmniDiffusionConfig) -> Callable[[torch.Tensor], Any]:
|
||||
image_processor = VaeImageProcessor(vae_scale_factor=ANIMA_VAE_SCALE_FACTOR)
|
||||
|
||||
def post_process_func(images: torch.Tensor) -> Any:
|
||||
return image_processor.postprocess(images)
|
||||
|
||||
return post_process_func
|
||||
|
||||
|
||||
class AnimaPipeline(nn.Module, DiffusionPipelineProfilerMixin, ProgressBarMixin):
|
||||
"""Native Anima model path.
|
||||
|
||||
The Anima transformer checkpoint is distributed as a single safetensors
|
||||
file. This loader builds the native pipeline components and runs the denoise
|
||||
transformer/text-conditioner directly.
|
||||
"""
|
||||
|
||||
supports_step_execution = False
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, device: torch.device | str | None = None) -> None:
|
||||
super().__init__()
|
||||
self.od_config = od_config
|
||||
self.parallel_config = od_config.parallel_config
|
||||
self.device = device or get_local_device()
|
||||
self.weights_sources: list[str] = []
|
||||
|
||||
self._raise_unsupported_features()
|
||||
|
||||
self._interrupt = False
|
||||
self._guidance_scale = 1.0
|
||||
self._num_timesteps = 0
|
||||
self._current_timestep = None
|
||||
self._profiler_initialized = False
|
||||
|
||||
def _raise_unsupported_features(self) -> None:
|
||||
pc = self.od_config.parallel_config
|
||||
if pc.cfg_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support CFG parallel. Validate native CFG first.")
|
||||
if pc.sequence_parallel_size is not None and pc.sequence_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support sequence parallelism. Add an _sp_plan first.")
|
||||
if pc.tensor_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support tensor parallelism. Port TP linears first.")
|
||||
if pc.use_hsdp:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support HSDP. Validate sharding after native load.")
|
||||
if self.od_config.cache_backend not in ("none", None):
|
||||
raise NotImplementedError("AnimaPipeline does not yet support TeaCache or Cache-DiT.")
|
||||
if self.od_config.quantization_config is not None:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support quantized checkpoints.")
|
||||
if resolve_offload_strategy(self.od_config) is not OffloadStrategy.NONE:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support CPU offload.")
|
||||
|
||||
@staticmethod
|
||||
def _sub_state_dict(state_dict: dict[str, torch.Tensor], prefix: str) -> dict[str, torch.Tensor]:
|
||||
return {key.removeprefix(prefix): value for key, value in state_dict.items() if key.startswith(prefix)}
|
||||
|
||||
@staticmethod
|
||||
def _convert_original_transformer_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
if "patch_embed.proj.weight" in state_dict:
|
||||
return state_dict
|
||||
|
||||
# The raw Anima checkpoint uses the original training names for a
|
||||
# Cosmos-style denoiser. Convert those keys to the local
|
||||
# AnimaTransformer3DModel module names before strict loading.
|
||||
converted_state_dict = {}
|
||||
for key, value in state_dict.items():
|
||||
new_key = key.removeprefix("net.")
|
||||
if any(drop_key in new_key for drop_key in _ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS):
|
||||
continue
|
||||
for old_key, new_name in _ANIMA_ORIGINAL_TRANSFORMER_RENAMES.items():
|
||||
new_key = new_key.replace(old_key, new_name)
|
||||
if new_key in converted_state_dict:
|
||||
raise ValueError(f"Duplicate converted Anima transformer key: {new_key}")
|
||||
converted_state_dict[new_key] = value
|
||||
return converted_state_dict
|
||||
|
||||
@staticmethod
|
||||
def _split_single_file_state_dict(
|
||||
state_dict: dict[str, torch.Tensor],
|
||||
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
||||
transformer_state_dict = AnimaPipeline._sub_state_dict(state_dict, "transformer.")
|
||||
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "text_conditioner.")
|
||||
if transformer_state_dict and text_conditioner_state_dict:
|
||||
return transformer_state_dict, text_conditioner_state_dict
|
||||
|
||||
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "net.llm_adapter.")
|
||||
if text_conditioner_state_dict:
|
||||
transformer_state_dict = {
|
||||
key: value for key, value in state_dict.items() if not key.startswith("net.llm_adapter.")
|
||||
}
|
||||
return transformer_state_dict, text_conditioner_state_dict
|
||||
|
||||
raise ValueError(
|
||||
"Anima native loader could not find text-conditioner weights. Expected either "
|
||||
"`text_conditioner.*` Diffusers keys or `net.llm_adapter.*` original Anima keys."
|
||||
)
|
||||
|
||||
def _load_native_denoiser_components(
|
||||
self,
|
||||
state_dict: dict[str, torch.Tensor] | None = None,
|
||||
) -> tuple[AnimaTransformer3DModel, AnimaTextConditioner]:
|
||||
if state_dict is None:
|
||||
model_path = self.od_config.model
|
||||
if not isinstance(model_path, str) or not os.path.isfile(model_path):
|
||||
raise ValueError(f"AnimaPipeline currently requires a local file path, got: {model_path}")
|
||||
|
||||
state_dict = load_file(model_path, device="cpu")
|
||||
transformer_state_dict, text_conditioner_state_dict = self._split_single_file_state_dict(state_dict)
|
||||
del state_dict
|
||||
transformer_state_dict = self._convert_original_transformer_state_dict(transformer_state_dict)
|
||||
|
||||
config_path = Path(self.od_config.model).with_suffix(".json")
|
||||
config = json.loads(config_path.read_text()) if config_path.is_file() else {}
|
||||
text_conditioner_config = {**ANIMA_TEXT_CONDITIONER_CONFIG, **config.get("text_conditioner", {})}
|
||||
transformer_config = {**ANIMA_TRANSFORMER_CONFIG, **config.get("transformer", {})}
|
||||
|
||||
native_text_conditioner = AnimaTextConditioner(**cast(dict[str, Any], text_conditioner_config))
|
||||
native_text_conditioner.load_state_dict(text_conditioner_state_dict, strict=True)
|
||||
native_text_conditioner.to(device=self.device, dtype=self.od_config.dtype)
|
||||
del text_conditioner_state_dict
|
||||
|
||||
native_transformer = AnimaTransformer3DModel(**cast(dict[str, Any], transformer_config))
|
||||
native_transformer.load_state_dict(transformer_state_dict, strict=True)
|
||||
native_transformer.to(device=self.device, dtype=self.od_config.dtype)
|
||||
del transformer_state_dict
|
||||
|
||||
return native_transformer, native_text_conditioner
|
||||
|
||||
def _component_path(self, name: str, default_model: str) -> str:
|
||||
custom_args = self.od_config.custom_pipeline_args or {}
|
||||
return str(custom_args.get(f"{name}_model", custom_args.get(f"{name}_path", default_model)))
|
||||
|
||||
@staticmethod
|
||||
def _from_pretrained_kwargs(model: str, subfolder: str | None = None) -> dict[str, Any]:
|
||||
kwargs: dict[str, Any] = {"local_files_only": os.path.exists(model)}
|
||||
if subfolder is not None and os.path.isdir(os.path.join(model, subfolder)):
|
||||
kwargs["subfolder"] = subfolder
|
||||
return kwargs
|
||||
|
||||
def _load_outer_components(self) -> tuple[Any, Any, Any, Any, Any]:
|
||||
custom_args = self.od_config.custom_pipeline_args or {}
|
||||
components_model_value = custom_args.get("components_model", custom_args.get("components_path"))
|
||||
if components_model_value is None:
|
||||
if not isinstance(self.od_config.model, str):
|
||||
raise ValueError("AnimaPipeline requires `model` or `components_model` to load outer components.")
|
||||
checkpoint_dir = os.path.dirname(os.path.abspath(self.od_config.model))
|
||||
components_model = checkpoint_dir if os.path.isdir(checkpoint_dir) else self.od_config.model
|
||||
else:
|
||||
components_model = str(components_model_value)
|
||||
|
||||
text_encoder_model = self._component_path("text_encoder", components_model)
|
||||
vae_model = self._component_path("vae", components_model)
|
||||
tokenizer_model = self._component_path("tokenizer", components_model)
|
||||
t5_tokenizer_model = self._component_path("t5_tokenizer", components_model)
|
||||
|
||||
text_encoder = Qwen3Model.from_pretrained(
|
||||
text_encoder_model,
|
||||
torch_dtype=self.od_config.dtype,
|
||||
**self._from_pretrained_kwargs(text_encoder_model, "text_encoder"),
|
||||
).to(self.device)
|
||||
vae = DistributedAutoencoderKLQwenImage.from_pretrained(
|
||||
vae_model,
|
||||
torch_dtype=self.od_config.dtype,
|
||||
**self._from_pretrained_kwargs(vae_model, "vae"),
|
||||
).to(self.device)
|
||||
tokenizer = AutoTokenizer.from_pretrained(
|
||||
tokenizer_model,
|
||||
**self._from_pretrained_kwargs(tokenizer_model, "tokenizer"),
|
||||
)
|
||||
t5_tokenizer = T5TokenizerFast.from_pretrained(
|
||||
t5_tokenizer_model,
|
||||
**self._from_pretrained_kwargs(t5_tokenizer_model, "t5_tokenizer"),
|
||||
)
|
||||
|
||||
scheduler_model = self._component_path("scheduler", components_model)
|
||||
has_scheduler_config = os.path.isfile(os.path.join(scheduler_model, "scheduler_config.json")) or os.path.isdir(
|
||||
os.path.join(scheduler_model, "scheduler")
|
||||
)
|
||||
if has_scheduler_config:
|
||||
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
||||
scheduler_model,
|
||||
**self._from_pretrained_kwargs(scheduler_model, "scheduler"),
|
||||
)
|
||||
else:
|
||||
scheduler = FlowMatchEulerDiscreteScheduler(shift=3.0)
|
||||
|
||||
return text_encoder, tokenizer, t5_tokenizer, vae, scheduler
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]] | None = None) -> set[str]:
|
||||
logger.info("Loading Anima transformer/text-conditioner directly from single-file checkpoint.")
|
||||
state_dict = dict(weights) if weights is not None else None
|
||||
loaded = set(state_dict.keys()) if state_dict is not None else set()
|
||||
if not state_dict:
|
||||
state_dict = None
|
||||
with set_current_diffusion_config(self.od_config):
|
||||
native_transformer, native_text_conditioner = self._load_native_denoiser_components(state_dict)
|
||||
text_encoder, tokenizer, t5_tokenizer, vae, scheduler = self._load_outer_components()
|
||||
|
||||
self.transformer = native_transformer
|
||||
self.text_conditioner = native_text_conditioner
|
||||
self.text_encoder = text_encoder
|
||||
self.tokenizer = tokenizer
|
||||
self.t5_tokenizer = t5_tokenizer
|
||||
self.vae = vae
|
||||
self.scheduler = scheduler
|
||||
self.vae_scale_factor = _anima_vae_scale_factor_from_vae(self.vae)
|
||||
self._setup_profiler()
|
||||
return loaded
|
||||
|
||||
def _setup_profiler(self) -> None:
|
||||
if self._profiler_initialized:
|
||||
return
|
||||
self.setup_diffusion_pipeline_profiler(
|
||||
profiler_targets=["vae.decode", "diffuse", "text_encoder.forward"],
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler,
|
||||
)
|
||||
self._profiler_initialized = True
|
||||
|
||||
def _extract_prompts(self, prompts: list[Any]) -> tuple[str | list[str] | None, str | list[str] | None]:
|
||||
"""Extract prompt and negative_prompt from OmniPromptType list."""
|
||||
prompt = [p if isinstance(p, str) else (p.get("prompt") or "") for p in prompts] or None
|
||||
if all(isinstance(p, str) or p.get("negative_prompt") is None for p in prompts):
|
||||
negative_prompt = None
|
||||
elif prompts:
|
||||
negative_prompt = ["" if isinstance(p, str) else (p.get("negative_prompt") or "") for p in prompts]
|
||||
else:
|
||||
negative_prompt = None
|
||||
return prompt, negative_prompt
|
||||
|
||||
def _get_qwen_prompt_embeds(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
max_sequence_length: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
|
||||
text_inputs = self.tokenizer(
|
||||
prompt,
|
||||
padding="longest",
|
||||
max_length=max_sequence_length,
|
||||
truncation=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
text_input_ids = text_inputs.input_ids.to(device)
|
||||
prompt_attention_mask = text_inputs.attention_mask.to(device)
|
||||
if text_input_ids.shape[-1] == 0:
|
||||
text_input_ids = text_input_ids.new_zeros((text_input_ids.shape[0], 1))
|
||||
prompt_attention_mask = prompt_attention_mask.new_zeros((prompt_attention_mask.shape[0], 1))
|
||||
|
||||
prompt_embeds = self.text_encoder(
|
||||
input_ids=text_input_ids,
|
||||
attention_mask=prompt_attention_mask,
|
||||
output_hidden_states=False,
|
||||
).last_hidden_state
|
||||
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
||||
prompt_embeds = prompt_embeds * prompt_attention_mask.to(prompt_embeds).unsqueeze(-1)
|
||||
|
||||
return prompt_embeds, prompt_attention_mask
|
||||
|
||||
def _get_t5_prompt_ids(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
max_sequence_length: int,
|
||||
device: torch.device,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
|
||||
text_inputs = self.t5_tokenizer(
|
||||
prompt,
|
||||
padding="longest",
|
||||
max_length=max_sequence_length,
|
||||
truncation=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
return text_inputs.input_ids.to(device), text_inputs.attention_mask.to(device)
|
||||
|
||||
def encode_prompt(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
prepare_unconditional_embeds: bool = True,
|
||||
max_sequence_length: int = 512,
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
device = device or self.device
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
batch_size = len(prompt)
|
||||
|
||||
prompt_embeds, prompt_attention_mask = self._get_qwen_prompt_embeds(
|
||||
prompt=prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
t5_input_ids, t5_attention_mask = self._get_t5_prompt_ids(
|
||||
prompt=prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
)
|
||||
|
||||
negative_prompt_embeds = None
|
||||
negative_prompt_attention_mask = None
|
||||
negative_t5_input_ids = None
|
||||
negative_t5_attention_mask = None
|
||||
if prepare_unconditional_embeds:
|
||||
if negative_prompt is None:
|
||||
negative_prompt = ""
|
||||
if isinstance(negative_prompt, str):
|
||||
negative_prompt = [negative_prompt] * batch_size
|
||||
elif len(negative_prompt) != batch_size:
|
||||
raise ValueError(
|
||||
f"`negative_prompt` length ({len(negative_prompt)}) must match prompt batch size ({batch_size})."
|
||||
)
|
||||
|
||||
negative_prompt_embeds, negative_prompt_attention_mask = self._get_qwen_prompt_embeds(
|
||||
prompt=negative_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
negative_t5_input_ids, negative_t5_attention_mask = self._get_t5_prompt_ids(
|
||||
prompt=negative_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
)
|
||||
|
||||
return {
|
||||
"qwen_prompt_embeds": prompt_embeds,
|
||||
"qwen_attention_mask": prompt_attention_mask,
|
||||
"t5_input_ids": t5_input_ids,
|
||||
"t5_attention_mask": t5_attention_mask,
|
||||
"negative_qwen_prompt_embeds": negative_prompt_embeds,
|
||||
"negative_qwen_attention_mask": negative_prompt_attention_mask,
|
||||
"negative_t5_input_ids": negative_t5_input_ids,
|
||||
"negative_t5_attention_mask": negative_t5_attention_mask,
|
||||
}
|
||||
|
||||
def condition_prompt_embeds(
|
||||
self,
|
||||
qwen_prompt_embeds: torch.Tensor,
|
||||
qwen_attention_mask: torch.Tensor,
|
||||
t5_input_ids: torch.Tensor,
|
||||
t5_attention_mask: torch.Tensor,
|
||||
device: torch.device | None = None,
|
||||
conditioning_dtype: torch.dtype | None = None,
|
||||
output_dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
device = device or self.device
|
||||
conditioning_dtype = conditioning_dtype or self.text_conditioner.dtype
|
||||
output_dtype = output_dtype or self.transformer.dtype
|
||||
|
||||
prompt_embeds = self.text_conditioner(
|
||||
source_hidden_states=qwen_prompt_embeds.to(device=device, dtype=conditioning_dtype),
|
||||
target_input_ids=t5_input_ids.to(device),
|
||||
target_attention_mask=t5_attention_mask.to(device),
|
||||
source_attention_mask=qwen_attention_mask.to(device),
|
||||
)
|
||||
return prompt_embeds.to(dtype=output_dtype, device=device)
|
||||
|
||||
def prepare_latents(
|
||||
self,
|
||||
batch_size: int,
|
||||
num_channels_latents: int,
|
||||
height: int,
|
||||
width: int,
|
||||
dtype: torch.dtype | None = None,
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
device = device or self.device
|
||||
dtype = dtype or self.transformer.dtype
|
||||
if latents is not None:
|
||||
return latents.to(device=device, dtype=dtype)
|
||||
|
||||
latent_height = height // self.vae_scale_factor
|
||||
latent_width = width // self.vae_scale_factor
|
||||
shape = (batch_size, num_channels_latents, 1, latent_height, latent_width)
|
||||
|
||||
if isinstance(generator, list) and len(generator) != batch_size:
|
||||
raise ValueError(
|
||||
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
||||
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
||||
)
|
||||
|
||||
# Draw latents in float32 then cast
|
||||
latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
|
||||
sigma_max = (
|
||||
getattr(self.scheduler.config, "sigma_max", 1.0)
|
||||
if hasattr(self, "scheduler") and hasattr(self.scheduler, "config")
|
||||
else 1.0
|
||||
)
|
||||
return latents.to(dtype=dtype) * sigma_max
|
||||
|
||||
def prepare_timesteps(
|
||||
self,
|
||||
num_inference_steps: int,
|
||||
sigmas: list[float] | None = None,
|
||||
device: torch.device | None = None,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
device = device or self.device
|
||||
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
||||
return retrieve_timesteps(
|
||||
self.scheduler,
|
||||
device=device,
|
||||
sigmas=sigmas,
|
||||
)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
latents: torch.Tensor,
|
||||
padding_mask: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
do_true_cfg: bool,
|
||||
true_cfg_scale: float,
|
||||
) -> torch.Tensor:
|
||||
self.scheduler.set_begin_index(0)
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for i, t in enumerate(timesteps):
|
||||
if self.interrupt:
|
||||
continue
|
||||
self._current_timestep = t
|
||||
|
||||
# Broadcast timestep to match batch size
|
||||
timestep = t.expand(latents.shape[0]).to(dtype=self.transformer.dtype, device=latents.device)
|
||||
timestep = timestep / 1000.0 # normalize to 0..1 range
|
||||
|
||||
# Predict noise
|
||||
latent_model_input = latents.to(self.transformer.dtype)
|
||||
|
||||
# Positive pass
|
||||
noise_pred = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
timestep=timestep,
|
||||
encoder_hidden_states=prompt_embeds,
|
||||
padding_mask=padding_mask,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
|
||||
# Negative / uncond pass
|
||||
if do_true_cfg and negative_prompt_embeds is not None:
|
||||
noise_pred_uncond = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
timestep=timestep,
|
||||
encoder_hidden_states=negative_prompt_embeds,
|
||||
padding_mask=padding_mask,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
noise_pred = noise_pred_uncond + true_cfg_scale * (noise_pred - noise_pred_uncond)
|
||||
|
||||
# Scheduler step
|
||||
latents_dtype = latents.dtype
|
||||
latents = self.scheduler.step(noise_pred.to(latents_dtype), t, latents, return_dict=False)[0]
|
||||
if latents.dtype != latents_dtype:
|
||||
latents = latents.to(latents_dtype)
|
||||
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def decode_latents(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
output_type: str = "pil",
|
||||
) -> DiffusionOutput:
|
||||
"""Decode final latents."""
|
||||
if output_type == "latent":
|
||||
return DiffusionOutput(
|
||||
output=latents,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
latents = latents.to(self.vae.dtype)
|
||||
latents_mean = (
|
||||
torch.tensor(self.vae.config.latents_mean)
|
||||
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
||||
.to(latents.device, latents.dtype)
|
||||
)
|
||||
latents_std = (
|
||||
torch.tensor(self.vae.config.latents_std)
|
||||
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
||||
.to(latents.device, latents.dtype)
|
||||
)
|
||||
latents = latents * latents_std + latents_mean
|
||||
image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
|
||||
return DiffusionOutput(
|
||||
output=image,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
true_cfg_scale: float = 4.0,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_inference_steps: int = 50,
|
||||
sigmas: list[float] | None = None,
|
||||
guidance_scale: float = 4.0,
|
||||
num_images_per_prompt: int = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
output_type: str | None = "pil",
|
||||
max_sequence_length: int = 512,
|
||||
) -> list[DiffusionOutput]:
|
||||
if req.num_reqs != 1:
|
||||
raise ValueError("AnimaPipeline supports one request per forward.")
|
||||
extracted_prompt, negative_prompt = self._extract_prompts(req.prompts)
|
||||
prompt = extracted_prompt or prompt
|
||||
if prompt is None:
|
||||
prompt = ""
|
||||
|
||||
height = req.sampling_params.height or height or 1024
|
||||
width = req.sampling_params.width or width or 1024
|
||||
height, width = normalize_min_aligned_size(height, width, self.vae_scale_factor * 2)
|
||||
if height is None or width is None:
|
||||
raise ValueError("AnimaPipeline requires resolved height and width.")
|
||||
height = int(height)
|
||||
width = int(width)
|
||||
if req.sampling_params.output_type is not None:
|
||||
output_type = req.sampling_params.output_type
|
||||
output_type = output_type or "pil"
|
||||
|
||||
num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps
|
||||
sigmas = req.sampling_params.sigmas or sigmas
|
||||
max_sequence_length = req.sampling_params.max_sequence_length or max_sequence_length
|
||||
generator = req.sampling_params.generator or generator
|
||||
if req.sampling_params.guidance_scale_provided:
|
||||
guidance_scale = req.sampling_params.guidance_scale
|
||||
if req.sampling_params.true_cfg_scale is None:
|
||||
true_cfg_scale = guidance_scale
|
||||
if req.sampling_params.true_cfg_scale is not None:
|
||||
true_cfg_scale = req.sampling_params.true_cfg_scale
|
||||
num_images_per_prompt = (
|
||||
req.sampling_params.num_outputs_per_prompt
|
||||
if req.sampling_params.num_outputs_per_prompt > 0
|
||||
else num_images_per_prompt
|
||||
)
|
||||
|
||||
self._guidance_scale = guidance_scale
|
||||
self._interrupt = False
|
||||
|
||||
if isinstance(prompt, str):
|
||||
batch_size = 1
|
||||
else:
|
||||
batch_size = len(prompt)
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0
|
||||
|
||||
# Encode prompts
|
||||
enc_out = self.encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
prepare_unconditional_embeds=do_true_cfg,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=self.device,
|
||||
dtype=self.text_encoder.dtype,
|
||||
)
|
||||
qwen_prompt_embeds = enc_out["qwen_prompt_embeds"]
|
||||
qwen_attention_mask = enc_out["qwen_attention_mask"]
|
||||
t5_input_ids = enc_out["t5_input_ids"]
|
||||
t5_attention_mask = enc_out["t5_attention_mask"]
|
||||
if (
|
||||
qwen_prompt_embeds is None
|
||||
or qwen_attention_mask is None
|
||||
or t5_input_ids is None
|
||||
or t5_attention_mask is None
|
||||
):
|
||||
raise ValueError("Anima prompt encoding did not produce all required positive embeddings.")
|
||||
|
||||
# Condition prompt embeds
|
||||
prompt_embeds = self.condition_prompt_embeds(
|
||||
qwen_prompt_embeds=qwen_prompt_embeds,
|
||||
qwen_attention_mask=qwen_attention_mask,
|
||||
t5_input_ids=t5_input_ids,
|
||||
t5_attention_mask=t5_attention_mask,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
negative_prompt_embeds = None
|
||||
negative_qwen_prompt_embeds = enc_out["negative_qwen_prompt_embeds"]
|
||||
if do_true_cfg and negative_qwen_prompt_embeds is not None:
|
||||
negative_qwen_attention_mask = enc_out["negative_qwen_attention_mask"]
|
||||
negative_t5_input_ids = enc_out["negative_t5_input_ids"]
|
||||
negative_t5_attention_mask = enc_out["negative_t5_attention_mask"]
|
||||
if (
|
||||
negative_qwen_attention_mask is None
|
||||
or negative_t5_input_ids is None
|
||||
or negative_t5_attention_mask is None
|
||||
):
|
||||
raise ValueError("Anima prompt encoding did not produce all required negative embeddings.")
|
||||
negative_prompt_embeds = self.condition_prompt_embeds(
|
||||
qwen_prompt_embeds=negative_qwen_prompt_embeds,
|
||||
qwen_attention_mask=negative_qwen_attention_mask,
|
||||
t5_input_ids=negative_t5_input_ids,
|
||||
t5_attention_mask=negative_t5_attention_mask,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
# Repeat for num_images_per_prompt
|
||||
_, seq_len, _ = prompt_embeds.shape
|
||||
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
||||
|
||||
if negative_prompt_embeds is not None:
|
||||
_, seq_len, _ = negative_prompt_embeds.shape
|
||||
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
||||
|
||||
# Prepare latents
|
||||
latents = self.prepare_latents(
|
||||
batch_size=batch_size * num_images_per_prompt,
|
||||
num_channels_latents=16, # Cosmos/Anima has 16 channels
|
||||
height=height,
|
||||
width=width,
|
||||
dtype=torch.float32,
|
||||
device=self.device,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
)
|
||||
|
||||
# Prepare padding mask
|
||||
padding_mask = latents.new_zeros(1, 1, height, width, dtype=self.transformer.dtype)
|
||||
|
||||
# Prepare timesteps
|
||||
timesteps, num_inference_steps = self.prepare_timesteps(
|
||||
num_inference_steps=num_inference_steps,
|
||||
sigmas=sigmas,
|
||||
device=self.device,
|
||||
)
|
||||
self._num_timesteps = len(timesteps)
|
||||
|
||||
# Denoise loop
|
||||
latents = self.diffuse(
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
latents=latents,
|
||||
padding_mask=padding_mask,
|
||||
timesteps=timesteps,
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=true_cfg_scale,
|
||||
)
|
||||
|
||||
self._current_timestep = None
|
||||
return [self.decode_latents(latents, output_type=output_type)]
|
||||
|
||||
@property
|
||||
def guidance_scale(self) -> float:
|
||||
return self._guidance_scale
|
||||
|
||||
@property
|
||||
def num_timesteps(self) -> int:
|
||||
return self._num_timesteps
|
||||
|
||||
@property
|
||||
def current_timestep(self) -> torch.Tensor | None:
|
||||
return self._current_timestep
|
||||
|
||||
@property
|
||||
def interrupt(self) -> bool:
|
||||
return self._interrupt
|
||||
Loaded 100 of 769 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user