Skip to content

Commit 729fd08

Browse files
committed
[None][feat] trtllm_modeling_v2 tune: warn when a perf config's CUDA graphs stop short
The high-throughput perf config captured CUDA graphs up to batch 32 (`cuda_graph_config.max_batch_size: 32`) at concurrency 128 under attention DP 4. Each rank held 32 live requests on average and 40-46 at its peaks, so decode fell back to eager for hours of measurements; capturing 1..128 raised total throughput 61%. Nothing in the spec checks or the campaign said so. `tune.spec.capture_shortfalls` reads each perf config's resolved LLM-API options (the identity configs, or the derived ones without writing them) and flags a config that turns CUDA graphs off, or whose largest captured batch, as the LLM API resolves it, is below the live requests one rank holds: the concurrency over the attention-DP ranks times 1.5 for uneven finishes, capped by the concurrency and the engine's `max_batch_size`. The intake lint reports each as a `perf-cuda-graph-coverage` warning with the capture that covers it, and the tune stage journals it (and records it in the perf ledger) when it starts. It stays a warning: the campaign measures the config as written. INTAKE.md says how to size the capture. Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
1 parent 54dbc55 commit 729fd08

6 files changed

Lines changed: 192 additions & 17 deletions

File tree

‎agent-flow/agent_flow/workflows/trtllm_modeling_v2/README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ The agent prepares the spec and launches the workflow; missing inputs must be re
3030

3131
**The agent writes the spec by following [spec/INTAKE.md](spec/INTAKE.md)**: `trtllm-modeling-v2 intake
3232
derive` writes a starting spec (no `site.yaml` needed), and `trtllm-modeling-v2 intake lint` checks
33-
it for slow or stalling choices (eager gates, a batch below the claimed concurrency, a member too
33+
it for slow or stalling choices (eager gates, a batch below the claimed concurrency, a perf
34+
config whose CUDA graphs stop below the live requests a rank holds, a member too
3435
narrow for one engine, disaggregation wider than a session, variant cross products, variants that
3536
boot at every member, a feature proven
3637
at several members or again under another axis, unusable accuracy anchors, open-ended boot probes) and blocks an accuracy check that runs without CUDA graphs and

‎agent-flow/agent_flow/workflows/trtllm_modeling_v2/spec/INTAKE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ goal words cannot say.
6565
| disagg | `accuracy.disagg.test`: the node id of the target's disaggregated-serving accuracy test, written beside the tree's own (the tests that serve through `trtllm-serve disaggregated`, configured, set up and launched as they are), with the environment it reads in `accuracy.disagg.env` (`LLM_MODELS_ROOT` ...); it runs once, at the member the request validates fully. Derive sizes it from the checkpoint: **one node** when a context and a generation engine both fit (`accuracy.disagg.devices`, two engines of two on a 4-GPU node), else `accuracy.disagg.nodes` with one engine per node, as the tree's multi-node disaggregated tests place them | boot and accuracy run one aggregated engine and never cross the hop; a multi-node test runs one pytest process per node of one gates allocation (`MV2FLOW_JOB_NODE_RANK/HOSTS/NODES`), so the gates session must hold that many nodes |
6666
| any other feature (MTP, speculative, offload ...) | name it in `--goal`; `derive.report.md` and `task.example.yaml` say what its unit owes | the same one-variant-per-axis rule applies |
6767
| workload isl / osl / concurrency | `max_seq_len = isl + osl`; `max_batch_size` >= the concurrency; both are **global totals**: under attention DP each rank serves its share (`max_batch_size / ranks`, rounded up); `max_num_tokens` = isl (or 8192); `perf.workload` | |
68-
| "perf tune" | `perf.enabled: true`; `perf.workload.concurrency` 1/32/128 unless the goal names it; a `dep` member only the high point, a global total | it starts once the core's required checks hold, never holds the onboarding back (its jobs queue below the onboarding's, its verdict does not wait for it), and measures one baseline (no stock reference, no repeats); a goal is `ratio_to_baseline` or `pct_of_sol` |
68+
| "perf tune" | `perf.enabled: true`; `perf.workload.concurrency` 1/32/128 unless the goal names it; a `dep` member only the high point, a global total; a perf config's `cuda_graph_config` captures up to the live requests a rank holds (under attention DP the concurrency over the ranks, x1.5 as they finish unevenly) | it starts once the core's required checks hold, never holds the onboarding back (its jobs queue below the onboarding's, its verdict does not wait for it), and measures one baseline (no stock reference, no repeats); a goal is `ratio_to_baseline` or `pct_of_sol` |
6969

7070
**The smallest contract that covers the request.** Every check loads the model (minutes on a
7171
large checkpoint), and every change to the target runs the stale checks again, so the contract's

‎agent-flow/agent_flow/workflows/trtllm_modeling_v2/spec/lint.py‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -971,15 +971,25 @@ def tree_rules(ctx: LintContext) -> Iterator[Finding]:
971971

972972
#: Every rule, in report order. A new feature, scope or launch check adds its function here.
973973
def perf_rules(ctx: LintContext) -> Iterator[Finding]:
974-
"""A ``perf`` key the campaign no longer reads: it runs without it."""
974+
"""A ``perf`` key the campaign no longer reads, and a perf config whose decode runs eager.
975+
976+
A config with CUDA graphs off, or whose largest captured batch is below the live requests a
977+
rank holds (``tune.spec.capture_shortfalls``), measures eager steps for the whole campaign.
978+
"""
979+
from ..tune.spec import capture_shortfalls, serving_options
980+
975981
perf = ctx.task.get("perf")
976-
for key in sorted(set(perf) & set(REMOVED_PERF_KEYS)) if isinstance(perf, Mapping) else ():
982+
if not isinstance(perf, Mapping):
983+
return
984+
for key in sorted(set(perf) & set(REMOVED_PERF_KEYS)):
977985
yield Finding(
978986
"perf-removed-key",
979987
WARN,
980988
f"`perf.{key}` is ignored: {REMOVED_PERF_KEYS[key]}",
981989
f"drop `perf.{key}`",
982990
)
991+
for why, fix in capture_shortfalls(serving_options(ctx.task)):
992+
yield Finding("perf-cuda-graph-coverage", WARN, why, fix)
983993

984994

985995
RULES: tuple[Rule, ...] = (

‎agent-flow/agent_flow/workflows/trtllm_modeling_v2/tune/spec.py‎

Lines changed: 123 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,25 @@
44

55
from __future__ import annotations
66

7+
import math
78
from dataclasses import dataclass, field
89
from pathlib import Path
9-
from typing import Any, Mapping
10+
from typing import Any, Iterable, Mapping, Sequence
1011

11-
from ..checks.check_config import checkpoint_remote_code
12+
import yaml
13+
14+
from ..checks.check_config import checkpoint_remote_code, options_capture
1215
from ..spec.task_schema import DEFAULT_PERF_CONCURRENCY
13-
from .harness.bench import AGENTX_DATASET, AGENTX_DURATION_S
16+
from .harness.bench import AGENTX_DATASET, AGENTX_DURATION_S, resolve_config
1417
from .measure import BenchPart, BenchSpec
1518
from .schema import AGENTX_WORKLOAD_KEYS
1619
from .serving_config import derive_serving_config, write_serving_config
1720

1821
PACKAGE = Path(__file__).resolve().parent.parent
1922
TARGET_SELECTION = {"modeling_v2": "require"}
23+
#: How far above its average share of the concurrency one attention-DP rank's live requests
24+
#: run: requests finish unevenly, so a rank holds more than its share for whole stretches.
25+
CAPTURE_HEADROOM = 1.5
2026

2127

2228
@dataclass
@@ -131,6 +137,15 @@ def bench(self) -> BenchSpec:
131137
parts=tuple(self.parts),
132138
) # fmt: skip
133139

140+
def serving_options(self) -> list[tuple[str, list[int], dict]]:
141+
"""Each perf config's name, concurrencies and the LLM-API options its server reads."""
142+
return [
143+
(name, list(concurrencies), resolve_config(list(paths), []))
144+
for name, (_, _, concurrencies, paths) in self.bench()
145+
.workloads(self.identity_configs)
146+
.items()
147+
]
148+
134149

135150
def _draft_len(task: Mapping[str, Any]) -> int:
136151
"""The draft length a speculative target verifies, or 0 without one."""
@@ -143,6 +158,23 @@ def _draft_len(task: Mapping[str, Any]) -> int:
143158
return resolve_max_draft_len(task.get("accuracy") or {}, speculators[-1])
144159

145160

161+
def _derived_options(task: Mapping[str, Any], entry: Mapping[str, Any]) -> dict:
162+
"""The serving config a ``perf.configs`` entry that names no configs runs with."""
163+
workload = entry.get("workload") or {}
164+
isl, osl = int(workload.get("isl", 1024)), int(workload.get("osl", 1024))
165+
concurrency = [int(c) for c in workload.get("concurrency", [1])]
166+
config = {
167+
**TARGET_SELECTION,
168+
**derive_serving_config(
169+
isl=isl, osl=osl, concurrency=concurrency, draft_len=_draft_len(task)
170+
),
171+
}
172+
if checkpoint_remote_code(task.get("checkpoint_path")):
173+
config["trust_remote_code"] = True
174+
config.update(entry.get("llm_api_options") or {})
175+
return config
176+
177+
146178
def _part(task: Mapping[str, Any], workdir: Path, entry: Mapping[str, Any]) -> BenchPart:
147179
"""One ``perf.configs`` entry: its workload, and its configs (derived when it names none)."""
148180
name = str(entry["name"])
@@ -151,15 +183,7 @@ def _part(task: Mapping[str, Any], workdir: Path, entry: Mapping[str, Any]) -> B
151183
concurrency = [int(c) for c in workload.get("concurrency", [1])]
152184
configs = [Path(p).resolve() for p in entry.get("identity_configs") or []]
153185
if not configs:
154-
config = {
155-
**TARGET_SELECTION,
156-
**derive_serving_config(
157-
isl=isl, osl=osl, concurrency=concurrency, draft_len=_draft_len(task)
158-
),
159-
}
160-
if checkpoint_remote_code(task.get("checkpoint_path")):
161-
config["trust_remote_code"] = True
162-
config.update(entry.get("llm_api_options") or {})
186+
config = _derived_options(task, entry)
163187
configs = [write_serving_config(workdir / "configs" / f"serving-{name}.yaml", config)]
164188
client = str(workload.get("client", "random"))
165189
agentx = {}
@@ -181,3 +205,90 @@ def _part(task: Mapping[str, Any], workdir: Path, entry: Mapping[str, Any]) -> B
181205
client=client,
182206
agentx=agentx,
183207
)
208+
209+
210+
def serving_options(task: Mapping[str, Any]) -> list[tuple[str, list[int], dict]]:
211+
""":meth:`TuneSpec.serving_options` read from ``task`` alone, writing nothing.
212+
213+
A config whose files do not read is left out: the campaign's own start says why.
214+
"""
215+
perf = task.get("perf") or {}
216+
entries = perf.get("configs")
217+
if not entries:
218+
workload = perf.get("workload") or {}
219+
concurrency = workload.get("concurrency", list(DEFAULT_PERF_CONCURRENCY))
220+
entries = [
221+
{
222+
"name": "",
223+
"workload": {**workload, "concurrency": concurrency},
224+
"identity_configs": perf.get("identity_configs"),
225+
}
226+
]
227+
found = []
228+
for entry in entries:
229+
concurrency = [int(c) for c in (entry.get("workload") or {}).get("concurrency", [1])]
230+
files = [Path(p).resolve() for p in entry.get("identity_configs") or []]
231+
try:
232+
options = resolve_config(files, []) if files else _derived_options(task, entry)
233+
except (OSError, yaml.YAMLError):
234+
continue
235+
found.append((str(entry.get("name") or ""), concurrency, options))
236+
return found
237+
238+
239+
def capture_shortfalls(
240+
configs: Iterable[tuple[str, Sequence[int], Mapping[str, Any]]],
241+
) -> list[tuple[str, str]]:
242+
"""Each perf config whose decode runs eager for part of its load: ``(why, fix)``.
243+
244+
CUDA graphs off, or a largest captured batch below the live requests one rank holds: the
245+
config's concurrency over its attention-DP ranks, times :data:`CAPTURE_HEADROOM` (never
246+
above the concurrency or the engine's ``max_batch_size``). A step past the largest batch
247+
runs eager, and the campaign measures that instead of the captured path.
248+
"""
249+
found = []
250+
for name, concurrency, options in configs:
251+
where = f"perf config `{name}`" if name else "the perf config"
252+
try:
253+
capture = options_capture(options)
254+
except ValueError:
255+
continue # the LLM API refuses it; the server's boot says so
256+
if capture is None:
257+
found.append(
258+
(
259+
f"{where} turns CUDA graphs off (`cuda_graph_config: null`): every decode "
260+
"step runs eager, a path no deployment serves",
261+
"drop `cuda_graph_config: null` and capture up to the concurrency",
262+
)
263+
)
264+
continue
265+
top = max(int(c) for c in concurrency)
266+
ranks = (
267+
max(1, int(options.get("tensor_parallel_size") or 1))
268+
if options.get("enable_attention_dp")
269+
else 1
270+
)
271+
share = -(-top // ranks)
272+
live = min(top, math.ceil(share * CAPTURE_HEADROOM))
273+
if options.get("max_batch_size"):
274+
live = min(live, int(options["max_batch_size"]))
275+
largest = capture.batch_sizes[-1]
276+
if largest >= live:
277+
continue
278+
load = (
279+
f"concurrency {top} over {ranks} attention-DP ranks is {share} live requests per "
280+
f"rank on average, and a rank holds up to {live} as requests finish unevenly"
281+
if ranks > 1
282+
else f"concurrency {top} keeps up to {live} requests live"
283+
)
284+
default = "" if "cuda_graph_config" in options else " (the LLM API default: it sets none)"
285+
found.append(
286+
(
287+
f"{where} captures CUDA graphs up to batch {largest}{default}, but {load}: "
288+
f"every decode step above {largest} runs eager",
289+
f"capture every batch up to at least {live}, e.g. `cuda_graph_config: "
290+
f"{{enable_padding: true, max_batch_size: {top}}}` (no rank holds more than the "
291+
"concurrency), with the engine's `max_batch_size` at least as large",
292+
)
293+
)
294+
return found

‎agent-flow/agent_flow/workflows/trtllm_modeling_v2/tune/stage.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
)
7474
from .schema import campaign_max_hours, validate_perf_block
7575
from .sol_consensus import METHODS, TOLERANCE, read_rulings, reconcile
76-
from .spec import TuneSpec
76+
from .spec import TuneSpec, capture_shortfalls
7777
from .worktree import measured_tree, open_candidate, tree_in_use
7878

7979
PACKAGE = Path(__file__).resolve().parent.parent
@@ -1417,13 +1417,19 @@ def _sync_source(self, camp: Campaign | None = None) -> bool:
14171417
def run(self) -> str | None:
14181418
"""The campaign to its verdict; ``None`` when it ends without one, to resume later.
14191419
1420+
A perf config whose decode runs eager for part of its load is journaled first
1421+
(:func:`capture_shortfalls`): a warning, the campaign measures it as it is.
1422+
14201423
A transient deferral (:attr:`MeasurementUnavailable.transient`: a job to finish, a
14211424
session to come back, a run or gate that ended without a verdict) is waited out here,
14221425
``perf.campaign.retry_wait_s`` at a time and at most ``max_retries`` times in one
14231426
process, each wait journaled with its reason; then the campaign resumes from its
14241427
checkpoint as a new process would. One that needs someone to act first, or one past
14251428
those waits, ends the process without a verdict, and the next invocation resumes.
14261429
"""
1430+
for why, fix in capture_shortfalls(self.spec.serving_options()):
1431+
self.log(f"[tune] warning: {why}. Fix: {fix}")
1432+
self.ledger.append("config_warning", warning=why)
14271433
wait_s = float(self.spec.campaign.get("retry_wait_s", RETRY_WAIT_S))
14281434
retries = int(self.spec.campaign.get("max_retries", MAX_RETRIES))
14291435
waited = 0

‎agent-flow/tests/workflows/trtllm_modeling_v2/test_tune_configs.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,53 @@ def test_the_perf_block_runs_without_a_stock_reference_or_repeats_and_says_so():
8484
]
8585

8686

87+
def test_a_perf_config_whose_cuda_graphs_stop_short_of_its_load_is_a_warning(tmp_path):
88+
"""128 requests over 4 attention-DP ranks: 32 per rank on average, up to 48 as they finish."""
89+
from agent_flow.workflows.trtllm_modeling_v2.spec.lint import WARN, perf_rules
90+
91+
from .test_tune_stage import FakeRunner, _effect, _repo
92+
93+
adp = {"modeling_v2": "require", "tensor_parallel_size": 4, "enable_attention_dp": True}
94+
configs = {
95+
"short": {**adp, "cuda_graph_config": {"enable_padding": True, "max_batch_size": 32}},
96+
"covered": {**adp, "cuda_graph_config": {"enable_padding": True, "max_batch_size": 48}},
97+
"eager": {**adp, "cuda_graph_config": None},
98+
"bounded": {**adp, "max_batch_size": 16, "cuda_graph_config": {"max_batch_size": 16}},
99+
}
100+
entries = []
101+
for name, options in configs.items():
102+
(tmp_path / f"{name}.yaml").write_text(yaml.safe_dump(options))
103+
entries.append(
104+
{
105+
"name": name,
106+
"workload": {"isl": 1024, "osl": 128, "concurrency": [1, 128]},
107+
"identity_configs": [str(tmp_path / f"{name}.yaml")],
108+
}
109+
)
110+
perf = {"configs": entries, "spools": ["s1", "s2", "s3", "s4"], "env_script": "/env.sh"}
111+
task = {"trtllm_repo_path": str(_repo(tmp_path)), "checkpoint_path": "/ckpt", "perf": perf}
112+
found = list(perf_rules(SimpleNamespace(task=task)))
113+
assert [(f.rule, f.severity) for f in found] == [("perf-cuda-graph-coverage", WARN)] * 2
114+
short, eager = (f.message for f in found)
115+
assert short.startswith("perf config `short` captures CUDA graphs up to batch 32")
116+
assert "32 live requests per rank on average, and a rank holds up to 48" in short
117+
assert "max_batch_size: 128}` (no rank holds more than the concurrency)" in found[0].fix
118+
assert eager.startswith("perf config `eager` turns CUDA graphs off")
119+
# The campaign journals it when it starts, and measures as the spec says.
120+
perf["campaign"] = {"enabled": False}
121+
spec = TuneSpec.from_task(task, tmp_path / "ws", target="t/")
122+
logs = []
123+
stage = TuneStage(spec, {}, dispatch=lambda *a: "", checkpoint=lambda: None,
124+
runner_factory=lambda s, p: FakeRunner(s, p, _effect), poll_s=0,
125+
log=logs.append) # fmt: skip
126+
assert stage.run() == "tuned"
127+
warned = [m for m in logs if m.startswith("[tune] warning: ")]
128+
assert [m.removeprefix("[tune] warning: ").split(". Fix: ")[0] for m in warned] == [
129+
short,
130+
eager,
131+
]
132+
133+
87134
AGENTX = {"client": "agentx", "isl": 8192, "osl": 1024, "concurrency": [1], "duration_s": 600}
88135

89136

0 commit comments

Comments
 (0)