Skip to content

Commit 8ee0796

Browse files
9wutongclaude
andauthored
perf: capture the qwen3-vl vision encoder in an acl graph. (#2737)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent de667ed commit 8ee0796

13 files changed

Lines changed: 567 additions & 8 deletions

File tree

‎docs/src/content/docs/en/cli_reference.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,8 @@ Current support covers ordinary non-PD text inference with prefix caching enable
234234
| `enable_graph_vmm_pool` | `bool` | `true` | Whether to enable a VMM-backed CUDA graph memory pool for multi-shape graph memory reuse. |
235235
| `max_tokens_for_graph_mode` | `int32` | `2048` | Maximum number of tokens for graph execution. `0` means no limit. |
236236
| `acl_graph_decode_batch_size_limit` | `int32` | `16` | Decode batch size threshold for ACL graph on NPU. When the actual decode batch size exceeds this value, ACL graph decode falls back to eager mode to avoid OOM. |
237+
| `enable_graph_mm_encoder` | `bool` | `false` | Whether to capture the Python Qwen3-VL multimodal encoder (its ViT) as ACL graphs. Requires `enable_graph`. `enable_graph` captures decode steps only, so a request carrying an image still dispatches the encoder from the Host one operator at a time — about 29 ms on one 910B2, independent of the image size. With this flag that dispatch is removed and replay reproduces the eager output bit for bit. `mm_encoder_graph_capture_shapes` bounds how many shapes are captured. The flag applies to the serving command line only: offline inference (the Python `LLM`/`VLM` API) does not carry it to its workers, so the encoder stays eager there. |
238+
| `mm_encoder_graph_capture_shapes` | `int32` | `8` | How many encode shapes the Python Qwen3-VL multimodal encoder may capture as ACL graphs when `enable_graph_mm_encoder` is set. A shape is the grid (`t`/`h`/`w`, in order) of every image in one encode call; it is captured on its first occurrence and replayed for every later encode of the same shape, while shapes beyond this count stay eager, chosen before the encoder runs rather than after a failure. `0` also disables capture. A captured shape costs device memory in proportion to its patch count — on one 910B2, about 30 MB to 40 MB at 256 to 784 patches and about 120 MB at 3136 — but the graph pool is shared across shapes, so later captures cost less than the first ones and a shape captured after a larger one can even return memory. Over an MMBench run that captured 64 shapes, free HBM fell by about 1.1 GB in total, about 17 MB per shape. Capture happens after the KV cache is allocated, so it draws on the memory `max_memory_utilization` leaves over rather than on the cache, whose size is unchanged. Size it to the deployment's shape count: a fixed resolution at low concurrency has few shapes, high concurrency groups several images into one encode, and free-form image sizes saturate any practical value, leaving the rest eager. |
237239
| `block_draft_graph_warmup_max_kv_len` | `int32` | `0` | Pre-capture power-of-two KV capacity buckets for independent Python block-draft ACL graphs (DSpark/DFlash2, including GLM MLA drafts). `0` covers the full model context; a positive value selects the bucket covering that length; `-1` retains lazy capacity capture. Required existing warmup shapes are always retained, even above a positive limit. Requests beyond the warmup limit can still grow graphs lazily. More buckets increase startup time and draft graph memory. Does not change target, MTP, context-write or optional whole-round unified graph warmup. |
238240
| `enable_shm` | `bool` | `false` | Whether to enable shared memory for model execution. |
239241
| `use_contiguous_input_buffer` | `bool` | `true` | Whether to use a contiguous device input buffer for model execution. |

‎docs/src/content/docs/en/features/graph_mode.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@ In the xLLM engine, Graph Mode provides the following:
1919
### Piecewise Graph
2020
- When some operators do not support graph capture and thus break the full graph, each segment (piece) after the break is captured as a separate graph. This maximizes graph-mode benefits even when the full graph cannot be captured, and is commonly used for prefill and chunked prefill.
2121

22+
### Multimodal Encoder Graph
23+
- `enable_graph` captures decode steps, so the vision encoder still dispatches one operator at a
24+
time from the Host. With `enable_graph_mm_encoder`, Python Qwen3-VL captures a separate encoder
25+
graph per **encode shape** -- the grid (`t`/`h`/`w`, in order) of every image in one encode
26+
call. The encode shape fixes every tensor shape and every Host scalar inside the encoder (patch count, frame
27+
boundaries, rotary tables, interpolation weights), so replay only writes the new pixels and the
28+
Host attention lengths captured inside the graph stay correct without task updates. A shape is
29+
captured on its first occurrence and replayed afterwards, and replay reproduces the eager output
30+
bit for bit. `mm_encoder_graph_capture_shapes` bounds how many shapes are captured; the rest
31+
stay eager. Both flags apply to the serving command line, and the encoder stays eager in
32+
offline inference.
2233
### Multi-Shape Reusable Memory Pool
2334
- To avoid waste from separate memory buffers (input, output, and intermediate tensors) per shape, we use an expandable memory pool. Multiple shapes share the pool base address, with different shapes using different offsets from that base.
2435

‎docs/src/content/docs/zh/cli_reference.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,8 @@ xLLM 使用 gflags 管理服务启动参数。`--model <PATH>` 是唯一必填
234234
| `enable_graph_vmm_pool` | `bool` | `true` | 是否启用 VMM-backed CUDA graph memory pool,用于多 shape graph 的显存复用。 |
235235
| `max_tokens_for_graph_mode` | `int32` | `2048` | 图执行最大 token 数;`0` 表示不限制。 |
236236
| `acl_graph_decode_batch_size_limit` | `int32` | `16` | NPU 上 ACL graph 的 decode batch size 阈值;实际 decode batch size 超过该值时,ACL graph decode 会回退到 eager 模式以避免 OOM。 |
237+
| `enable_graph_mm_encoder` | `bool` | `false` | 是否把 Python Qwen3-VL 的多模态编码器(ViT)捕获为 ACL graph。需要同时开启 `enable_graph`。`enable_graph` 只捕获 decode 阶段,带图请求的编码器仍逐算子由 Host 下发(单卡 910B2 实测约 29 ms,且与图片大小无关);开启本项后该段 Host 下发被消除,重放结果与 eager 逐位一致。捕获的 shape 数量由 `mm_encoder_graph_capture_shapes` 限制。本项只在服务端命令行生效:offline 推理(Python `LLM`/`VLM` 接口)不向 worker 传递它,编码器在该路径上保持 eager。 |
238+
| `mm_encoder_graph_capture_shapes` | `int32` | `8` | `enable_graph_mm_encoder` 开启时,Python Qwen3-VL 多模态编码器最多捕获多少种 encode shape。一种 shape 是一次 encode 调用中所有图片的 grid(`t`/`h`/`w` 及其顺序);首次遇到时捕获,之后相同 shape 直接重放,超出该数量的 shape 保持 eager,且该判定在编码器执行之前做出。`0` 同样表示不捕获。每种 shape 额外占用的显存随其 patch 数增长:单卡 910B2 实测 256~784 patch 约 30~40 MB,3136 patch 约 120 MB;但图池跨 shape 共享,后续捕获比最初几次便宜,在更大 shape 之后捕获的 shape 甚至会把显存还回去。一次捕获了 64 种 shape 的 MMBench 实测中,free HBM 总共下降约 1.1 GB,平均约 17 MB/shape。捕获发生在 KV cache 分配之后,占用的是 `max_memory_utilization` 留下的余量,不改变 KV cache 容量。该数量应按部署的 shape 数设置:固定分辨率、低并发时 shape 很少;高并发会把多张图片合并到同一次 encode,自由分辨率的图片流量则会用满任何实际取值,超出的部分保持 eager。 |
237239
| `block_draft_graph_warmup_max_kv_len` | `int32` | `0` | 仅为 Python block draft 的独立 ACL graph(DSpark/DFlash2,包括 GLM MLA draft)预捕获按 2 的幂增长的 KV 容量桶。`0` 覆盖完整模型上下文;正数预捕获到覆盖该长度的容量桶;`-1` 保留按需捕获。已有 warmup 必需的形状始终保留,即使超过正数上限。超过预捕获上界的请求仍可在线扩桶。更多容量桶会增加启动时间和 draft 图显存占用;不改变 target、MTP、context-write 或可选整轮 unified graph 的预热策略。 |
238240
| `enable_shm` | `bool` | `false` | 是否为模型执行启用共享内存。 |
239241
| `use_contiguous_input_buffer` | `bool` | `true` | 是否使用连续的 device input buffer 执行模型。 |

‎docs/src/content/docs/zh/features/graph_mode.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ xLLM 支持 Graph Mode,通过预捕获计算图并在后续执行中重放,
1919
### Piecewise Graph
2020
- 当部分算子不支持 graph 导致整图无法捕获(break graph)时,对 break 之后的各段(piece)分别捕获 graph。这样在无法整图捕获的情况下,仍能尽可能获得 graph mode 的收益,常用于 prefill、chunked_prefill 等场景。
2121

22+
### 多模态编码器图
23+
- `enable_graph` 捕获的是 decode 阶段,视觉编码器仍然逐算子由 Host 下发。开启
24+
`enable_graph_mm_encoder` 后,Python Qwen3-VL 按 **一次 encode 调用的 shape**
25+
(各图片的 `t`/`h`/`w` 及其顺序)捕获独立的 encoder 图:该 shape 决定了
26+
编码器内部的全部形状与 Host 标量(patch 数、帧边界、rotary 表、插值权重),因此重放只需写入新的
27+
pixel 数据,图内的 Host attention 长度无需更新。首次遇到某 shape 时捕获,之后相同 shape 直接重放,
28+
重放结果与 eager 逐位一致。捕获数量由 `mm_encoder_graph_capture_shapes` 限制,超出的 shape 保持 eager。
29+
这两项只在服务端命令行生效,offline 推理路径上编码器保持 eager。
2230
### 多 shape 复用的显存池
2331
- 为了避免不同 shape 的 graph capture 分别占用独立显存,我们让不同 capture 使用不同虚拟地址空间,并共享同一组底层物理内存;同时,输入 tensor 通过持久化 buffer 与 slice 方式复用。
2432

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
# Copyright 2026 The xLLM Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://github.com/xLLM-AI/xllm/blob/main/LICENSE
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Vision encoder graph admission, layout keying and output ownership."""
16+
17+
from contextlib import nullcontext
18+
from types import SimpleNamespace
19+
from unittest.mock import Mock
20+
21+
import pytest
22+
import torch
23+
24+
from xllm.python.model_executor.runners.vision_acl_graph import VisionAclGraphRunner
25+
from xllm.python.models.qwen3_vl import Qwen3VLVisionTransformer, _host_grid_rows
26+
27+
_PIXEL_COLUMNS = 8
28+
29+
30+
def _pixels(patches: int, fill: float = 1.0) -> torch.Tensor:
31+
return torch.full((patches, _PIXEL_COLUMNS), fill)
32+
33+
34+
@pytest.fixture
35+
def vision_model() -> SimpleNamespace:
36+
"""A stand-in encoder: one output row per spatial-merge group of patches."""
37+
38+
def forward(pixel_values: torch.Tensor, grid_rows: list[list[int]]) -> torch.Tensor:
39+
rows = sum(t * h * w for t, h, w in grid_rows) // 4
40+
return pixel_values[:rows, :2] * 2.0
41+
42+
return SimpleNamespace(side_effect=Mock(side_effect=forward))
43+
44+
45+
@pytest.fixture
46+
def runner(monkeypatch: pytest.MonkeyPatch, vision_model: SimpleNamespace) -> VisionAclGraphRunner:
47+
monkeypatch.setattr(
48+
torch,
49+
"npu",
50+
SimpleNamespace(
51+
current_stream=Mock(return_value=Mock()),
52+
Stream=Mock(return_value=Mock()),
53+
stream=Mock(side_effect=lambda *args: nullcontext()),
54+
NPUGraph=Mock(side_effect=Mock),
55+
graph=Mock(side_effect=lambda *args, **kwargs: nullcontext()),
56+
graph_pool_handle=Mock(return_value=(0, 0)),
57+
mem_get_info=Mock(return_value=(1 << 40, 1 << 40)),
58+
),
59+
raising=False,
60+
)
61+
# The runner only calls the encoder, so a plain callable stands in for it.
62+
model = vision_model.side_effect
63+
return VisionAclGraphRunner(model, torch.device("cpu"), max_graphs=2)
64+
65+
66+
def test_layout_is_captured_once_and_replayed(runner: VisionAclGraphRunner) -> None:
67+
grid = [[1, 2, 2]]
68+
first = runner.execute(_pixels(4), grid)
69+
captures = torch.npu.graph.call_count
70+
second = runner.execute(_pixels(4, fill=3.0), grid)
71+
72+
assert runner.captured_graphs == 1
73+
assert torch.npu.graph.call_count == captures, "a second call of a known layout must not capture again"
74+
assert first.shape == second.shape
75+
76+
77+
def test_distinct_layouts_get_distinct_graphs(runner: VisionAclGraphRunner) -> None:
78+
runner.execute(_pixels(4), [[1, 2, 2]])
79+
runner.execute(_pixels(16), [[1, 4, 4]])
80+
assert runner.captured_graphs == 2
81+
82+
# Two images of a captured geometry are a layout of their own: the grouped
83+
# encode is what fills the device, so it is what gets captured, and the
84+
# budget decides whether this one can be.
85+
captures = torch.npu.graph.call_count
86+
runner.execute(_pixels(8), [[1, 2, 2], [1, 2, 2]])
87+
assert runner.captured_graphs == 2, "the budget is two graphs"
88+
assert torch.npu.graph.call_count == captures
89+
assert runner.eager_encodes == 1
90+
91+
92+
def test_budget_exhaustion_keeps_a_layout_eager(runner: VisionAclGraphRunner, vision_model: SimpleNamespace) -> None:
93+
runner.execute(_pixels(4), [[1, 2, 2]])
94+
runner.execute(_pixels(16), [[1, 4, 4]])
95+
captures = torch.npu.graph.call_count
96+
calls = vision_model.side_effect.call_count
97+
98+
rejected = runner.execute(_pixels(36), [[1, 6, 6]])
99+
assert torch.npu.graph.call_count == captures
100+
assert vision_model.side_effect.call_count == calls + 1, "the over-budget layout must run the encoder eagerly"
101+
assert rejected.shape[0] == 9
102+
assert runner.eager_encodes == 1
103+
104+
# An over-budget layout is not retried, and nothing is remembered per
105+
# layout: the budget never frees up, so such state would grow with the
106+
# variety of the traffic rather than with the deployment's geometry count.
107+
runner.execute(_pixels(36), [[1, 6, 6]])
108+
runner.execute(_pixels(64), [[1, 8, 8]])
109+
assert torch.npu.graph.call_count == captures
110+
assert runner.eager_encodes == 3
111+
assert runner.captured_graphs == 2
112+
assert not [name for name in vars(runner) if "reject" in name]
113+
114+
115+
def test_replay_output_is_not_the_captured_buffer(runner: VisionAclGraphRunner) -> None:
116+
grid = [[1, 2, 2]]
117+
runner.execute(_pixels(4), grid)
118+
kept = runner.execute(_pixels(4, fill=2.0), grid)
119+
captured = next(iter(runner._graphs.values())).static_output
120+
# The framework keeps the encoder output across prefill chunks and in its
121+
# encoder cache, while the next replay overwrites the captured buffer, so
122+
# the two must not be the same storage.
123+
assert kept.data_ptr() != captured.data_ptr()
124+
assert torch.equal(kept, captured)
125+
126+
127+
def test_pixel_rows_must_match_the_grid(runner: VisionAclGraphRunner) -> None:
128+
# A grid that does not describe these pixels would slice the wrong rows.
129+
with pytest.raises(ValueError, match="pixel rows"):
130+
runner.execute(_pixels(5), [[1, 2, 2]])
131+
132+
133+
def test_frame_boundaries_match_the_device_formula() -> None:
134+
for grid_rows in ([[1, 2, 2]], [[1, 4, 6], [1, 2, 2]], [[3, 2, 4]], [[2, 4, 4], [1, 6, 6], [4, 2, 2]]):
135+
grid = torch.tensor(grid_rows, dtype=torch.int32)
136+
expected = torch.repeat_interleave(grid[:, 1] * grid[:, 2], grid[:, 0]).cumsum(dim=0, dtype=torch.int32)
137+
assert Qwen3VLVisionTransformer._compute_frame_boundaries(grid_rows) == expected.tolist()
138+
139+
140+
def test_host_grid_rows_accepts_both_grid_forms() -> None:
141+
# The captured path resolves the grid to Host rows; the Qwen3.5 composer
142+
# still passes a device tensor, and both have to reach the same rows.
143+
rows = [[1, 4, 6], [2, 2, 2]]
144+
assert _host_grid_rows(rows) is rows
145+
converted = _host_grid_rows(torch.tensor(rows, dtype=torch.int32))
146+
assert converted == rows
147+
assert all(isinstance(value, int) for row in converted for value in row)

‎xllm/core/distributed_runtime/worker_server.cpp‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,14 @@ void WorkerServer::create_server(const runtime::Options& options,
8989
options.enable_graph_mode_decode_no_padding())
9090
.enable_prefill_piecewise_graph(
9191
options.enable_prefill_piecewise_graph())
92-
.max_tokens_for_graph_mode(options.max_tokens_for_graph_mode());
92+
.max_tokens_for_graph_mode(options.max_tokens_for_graph_mode())
93+
// Offline workers receive graph settings through runtime::Options, and
94+
// the multimodal encoder graph has no slot there or in the spawn
95+
// protocol. Leaving the gflags in force here would capture on a
96+
// setting the offline caller can neither reach nor size, so the
97+
// encoder stays eager on this path. Every offline worker evaluates
98+
// this branch, so all ranks agree.
99+
.enable_graph_mm_encoder(/*enable_graph_mm_encoder=*/false);
93100
}
94101
#if defined(USE_NPU)
95102
KernelConfig::get_instance().npu_kernel_backend(options.npu_kernel_backend());

‎xllm/core/framework/config/execution_config.cpp‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,22 @@ DEFINE_int32(block_draft_graph_warmup_max_kv_len,
4747
"Requests beyond the warmup limit can still grow graphs lazily. "
4848
"Does not change target or MTP graph warmup.");
4949

50+
DEFINE_bool(enable_graph_mm_encoder,
51+
false,
52+
"Whether to capture the Python Qwen3-VL multimodal encoder as ACL "
53+
"graphs. Requires enable_graph. The encoder is captured per encode "
54+
"shape and replayed for every later encode of the same shape, "
55+
"which removes its Host dispatch from the request.");
56+
57+
DEFINE_int32(mm_encoder_graph_capture_shapes,
58+
8,
59+
"How many encode shapes the Python Qwen3-VL multimodal encoder "
60+
"may capture as ACL graphs, when enable_graph_mm_encoder is set. "
61+
"A shape is the grid of every image in one encode call; it is "
62+
"captured on its first occurrence and replayed for every later "
63+
"encode of the same shape, while shapes beyond this count stay "
64+
"eager.");
65+
5066
DEFINE_bool(enable_graph_double_buffer,
5167
true,
5268
"Whether to enable double-buffered ACL graph persistent params "
@@ -135,6 +151,8 @@ void ExecutionConfig::from_flags() {
135151
XLLM_CONFIG_ASSIGN_FROM_FLAG(enable_graph);
136152
XLLM_CONFIG_ASSIGN_FROM_FLAG(disable_graph_warmup);
137153
XLLM_CONFIG_ASSIGN_FROM_FLAG(block_draft_graph_warmup_max_kv_len);
154+
XLLM_CONFIG_ASSIGN_FROM_FLAG(enable_graph_mm_encoder);
155+
XLLM_CONFIG_ASSIGN_FROM_FLAG(mm_encoder_graph_capture_shapes);
138156
XLLM_CONFIG_ASSIGN_FROM_FLAG(enable_graph_double_buffer);
139157
XLLM_CONFIG_ASSIGN_FROM_FLAG(enable_graph_mode_decode_no_padding);
140158
XLLM_CONFIG_ASSIGN_FROM_FLAG(enable_prefill_piecewise_graph);
@@ -157,6 +175,8 @@ void ExecutionConfig::from_json(const JsonReader& json) {
157175
XLLM_CONFIG_ASSIGN_FROM_JSON(enable_graph);
158176
XLLM_CONFIG_ASSIGN_FROM_JSON(disable_graph_warmup);
159177
XLLM_CONFIG_ASSIGN_FROM_JSON(block_draft_graph_warmup_max_kv_len);
178+
XLLM_CONFIG_ASSIGN_FROM_JSON(enable_graph_mm_encoder);
179+
XLLM_CONFIG_ASSIGN_FROM_JSON(mm_encoder_graph_capture_shapes);
160180
XLLM_CONFIG_ASSIGN_FROM_JSON(enable_graph_double_buffer);
161181
XLLM_CONFIG_ASSIGN_FROM_JSON(enable_graph_mode_decode_no_padding);
162182
XLLM_CONFIG_ASSIGN_FROM_JSON(enable_prefill_piecewise_graph);
@@ -185,6 +205,10 @@ void ExecutionConfig::append_config_json(
185205
config_json, default_config, disable_graph_warmup);
186206
APPEND_CONFIG_JSON_VALUE_IF_NOT_DEFAULT(
187207
config_json, default_config, block_draft_graph_warmup_max_kv_len);
208+
APPEND_CONFIG_JSON_VALUE_IF_NOT_DEFAULT(
209+
config_json, default_config, enable_graph_mm_encoder);
210+
APPEND_CONFIG_JSON_VALUE_IF_NOT_DEFAULT(
211+
config_json, default_config, mm_encoder_graph_capture_shapes);
188212
APPEND_CONFIG_JSON_VALUE_IF_NOT_DEFAULT(
189213
config_json, default_config, enable_graph_double_buffer);
190214
APPEND_CONFIG_JSON_VALUE_IF_NOT_DEFAULT(

0 commit comments

Comments
 (0)