Skip to content

Commit 187088d

Browse files
hbarclayclaude
andcommitted
operatorx: cases run under InferenceX's srt-slurm recipes
operatorx/recipes.py finds the recipe InferenceX serves a case's source checkpoint with on the runner's hardware (expanded by infx.srt_slurm's own selected_recipes); the planner gives that shard the recipe's image, launch env and server arguments (OPERATORX_ENGINE_ARGS). The attention engine takes the arguments through vLLM's EngineArgs parser (the op's own KV and indexer dtypes on top) and the recipe's CUDA-graph mode and sizes, replacing per-model settings. Replaces the configs/*-master.yaml recipe lookup that the top-level layout broke. The plan job initializes srt-slurm and srtctl's dependencies. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 5fa43cf commit 187088d

4 files changed

Lines changed: 171 additions & 68 deletions

File tree

‎.github/workflows/operatorx-sweep.yml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,11 @@ jobs:
9090
set -eo pipefail
9191
source inferencex-e2e/benchmarks/benchmark_lib.sh --validation-only
9292
check_env_vars OPERATORX_RUNNER OPERATORX_BACKENDS OPERATORX_TESTLISTS OPERATORX_WORLD_SIZES OPERATORX_MODE OPERATORX_CHUNK_SIZE GITHUB_RUN_ID GITHUB_RUN_ATTEMPT GITHUB_SHA GITHUB_OUTPUT
93-
python3 -m operatorx.ci plan \
93+
# Cases take InferenceX's srt-slurm recipes, expanded by InferenceX's own code (srtctl).
94+
git submodule update --init inferencex-e2e/utils/srt-slurm
95+
uv run --no-project --exclude-newer PT12H --python 3.12 --with pyyaml --with ruamel.yaml \
96+
--with marshmallow --with marshmallow-dataclass --with pydantic --with jinja2 --with requests --with rich \
97+
python -m operatorx.ci plan \
9498
--platform-config operatorx/platforms.json \
9599
--runner "$OPERATORX_RUNNER" --backends "$OPERATORX_BACKENDS" \
96100
--testlists "$OPERATORX_TESTLISTS" --world-sizes "$OPERATORX_WORLD_SIZES" \

‎operatorx/ci.py‎

Lines changed: 25 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,6 @@ def load_platforms(path: Path) -> dict:
112112
return platforms
113113

114114

115-
REPO = ROOT.parents[1]
116-
# launch-script exports that are serving/benchmark plumbing, not kernel selection
117-
_RECIPE_ENV_SKIP = re.compile(r"^(AIPERF_|HF_|MODEL|PORT|RESULT|SERVER|LMCACHE|PYTHONHASHSEED|VLLM_ENGINE_READY)")
118-
119-
120115
def family(name: str) -> str:
121116
"""Hardware family of a runner label: 'cluster:mi355x-amds' -> 'mi355x'."""
122117
return name.removeprefix("cluster:").split("-")[0]
@@ -126,41 +121,6 @@ def is_amd(runner: str) -> bool:
126121
return family(runner).startswith("mi")
127122

128123

129-
def recipe_env(script: Path) -> dict[str, str]:
130-
"""The launch script's unconditional top-level `export NAME=value` lines (no expansion)."""
131-
env = {}
132-
for line in script.read_text().splitlines():
133-
m = re.fullmatch(r"export ([A-Z_][A-Z0-9_]*)=(['\"]?)([^$`'\"\s]*)\2", line)
134-
if m and not _RECIPE_ENV_SKIP.match(m.group(1)):
135-
env[m.group(1)] = m.group(3)
136-
return env
137-
138-
139-
def load_recipes(keys: set[str]) -> dict[str, dict]:
140-
"""InferenceX recipes (configs/*-master.yaml) by key: image, framework, hardware family,
141-
and the env its single-node launch script exports."""
142-
import yaml
143-
144-
out = {}
145-
for vendor in ("amd", "nvidia"):
146-
configs = yaml.safe_load((REPO / f"configs/{vendor}-master.yaml").read_text())
147-
for key in keys & configs.keys():
148-
r = configs[key]
149-
hw = family(r["runner"])
150-
spec = any(s.get("spec-decoding") == "mtp" for sc in (r.get("scenarios") or {}).values()
151-
for s in (sc[0].get("search-space", []) if isinstance(sc, list) and sc else []))
152-
name = f"{r['model-prefix']}_{r['precision']}_{hw}{'_mtp' if spec else ''}.sh"
153-
scripts = [REPO / "benchmarks/single_node" / sub / name for sub in ("agentic", "")]
154-
script = next((x for x in scripts if x.is_file()), None)
155-
out[key] = {"image": r["image"], "framework": r["framework"], "hardware": hw,
156-
"script": str(script.relative_to(REPO)) if script else None,
157-
"env": recipe_env(script) if script else {}}
158-
missing = keys - out.keys()
159-
if missing:
160-
raise ValueError(f"unknown InferenceX recipes: {sorted(missing)}")
161-
return out
162-
163-
164124
def write_json(path: Path, value: object) -> None:
165125
path.parent.mkdir(parents=True, exist_ok=True)
166126
temporary = path.with_suffix(path.suffix + ".tmp")
@@ -177,8 +137,12 @@ def plan(
177137
chunk_size: int,
178138
platforms: dict[str, dict],
179139
mode: str = "timing",
180-
recipes: dict[str, dict] | None = None,
140+
find_recipe=None,
181141
) -> dict:
142+
"""Shards for a selection. A case whose source checkpoint InferenceX serves on this
143+
hardware runs under that recipe (find_recipe(framework, hardware, checkpoints),
144+
operatorx.recipes.find): its image, launch env and server arguments."""
145+
from operatorx.recipes import FRAMEWORKS, checkpoints
182146
if runner not in RUNNERS:
183147
raise ValueError(f"unsupported runner: {runner}")
184148
if mode not in MODES:
@@ -211,6 +175,7 @@ def plan(
211175
if not 1 <= chunk_size <= 500:
212176
raise ValueError("chunk size must be between 1 and 500")
213177
groups = defaultdict(list)
178+
recipes_seen: dict[str, dict] = {}
214179
excluded = 0
215180
for name, shapes in sorted(testlists.items()):
216181
for shape in shapes:
@@ -221,24 +186,28 @@ def plan(
221186
if ws not in world_sizes:
222187
excluded += 1
223188
continue
224-
# an entry naming an InferenceX recipe for this hardware runs with that recipe's
225-
# image and launch env, in its own shard
226-
recipe = next((k for k in shape.get("recipes", ()) if recipes and k in recipes
227-
and recipes[k]["hardware"] == family(runner)
228-
and recipes[k]["framework"] in backends), None)
229-
groups[(ws, recipe or "")].append({"testlist": name, "shape": shape})
189+
recipe = next((r for b in backends if b in FRAMEWORKS and find_recipe
190+
for r in [find_recipe(b, family(runner), checkpoints(shape.get("sources")))] if r),
191+
None)
192+
if recipe:
193+
recipes_seen[recipe["recipe"]] = recipe
194+
groups[(ws, recipe["recipe"] if recipe else "")].append({"testlist": name, "shape": shape})
230195
image_groups = defaultdict(list)
231196
for backend in sorted(set(backends)):
232197
image_groups[images[backend]["image"]].append(backend)
233198
cells = []
234199
shards = []
235200
for (ws, recipe), cases in sorted(groups.items()):
201+
rest = image_groups
236202
if recipe:
237-
r = recipes[recipe]
238-
shards.append((r["image"], [r["framework"]], ws, cases,
239-
{"recipe": recipe, "recipe_script": r["script"], "env": r["env"]}))
240-
else:
241-
shards += [(image, selected, ws, cases, {}) for image, selected in sorted(image_groups.items())]
203+
r = recipes_seen[recipe]
204+
framework = next(b for b in backends if b in FRAMEWORKS)
205+
shards.append((r["image"], [framework], ws, cases,
206+
{"recipe": recipe, "checkpoint": r["checkpoint"], "env": r["env"],
207+
"engine_args": r["engine_args"]}))
208+
# the other backends run the same cases on their own images
209+
rest = {i: [b for b in bs if b != framework] for i, bs in image_groups.items()}
210+
shards += [(image, selected, ws, cases, {}) for image, selected in sorted(rest.items()) if selected]
242211
for image, selected, ws, cases, extra in shards:
243212
for offset in range(0, len(cases), chunk_size):
244213
cell = {
@@ -607,6 +576,7 @@ def interrupted(signum, frame):
607576
OPERATORX_BACKENDS=",".join(cell["backends"]),
608577
OPERATORX_MODE=cell.get("mode", "timing"),
609578
OPERATORX_RECIPE=cell.get("recipe", ""),
579+
OPERATORX_ENGINE_ARGS=json.dumps(cell.get("engine_args") or {}),
610580
OPERATORX_TESTLISTS=",".join(
611581
sorted({c["testlist"] for c in cell["cases"]})
612582
),
@@ -831,6 +801,8 @@ def main() -> None:
831801
if args.command == "plan":
832802
import tomllib
833803

804+
from operatorx import recipes
805+
834806
names = args.testlists.split(",")
835807
if any(not re.fullmatch(r"[A-Za-z0-9_-]+", n) for n in names):
836808
raise ValueError("invalid testlist name")
@@ -855,8 +827,7 @@ def main() -> None:
855827
args.chunk_size,
856828
load_platforms(args.platform_config),
857829
args.mode,
858-
recipes=load_recipes({k for shapes in lists.values() for s in shapes for k in s.get("recipes", ())})
859-
if any(s.get("recipes") for shapes in lists.values() for s in shapes) else None,
830+
find_recipe=recipes.find,
860831
)
861832
digests = {c["image"]: "" for c in result["include"]}
862833
for image in digests:

‎operatorx/recipes.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""The InferenceX recipe a case runs under.
2+
3+
InferenceX serves every single-node configuration from a native srt-slurm recipe
4+
(inferencex-e2e/benchmarks/single_node/srt-slurm-recipes/<model>/<framework>/<hardware>-<precision>*/*.yaml).
5+
A case takes the recipe InferenceX runs for its source checkpoint on the runner's
6+
hardware: the recipe's image, launch env and server arguments. InferenceX's own code
7+
expands a recipe into its variants (infx.srt_slurm.synthetic_acceptance.selected_recipes).
8+
Without a recipe the case runs on the backend's default image.
9+
"""
10+
from __future__ import annotations
11+
12+
import functools
13+
import json
14+
import sys
15+
from pathlib import Path
16+
from typing import Any
17+
18+
REPO = Path(__file__).resolve().parents[1] / "inferencex-e2e" # infx, its recipes and srt-slurm
19+
RECIPES = REPO / "benchmarks/single_node/srt-slurm-recipes"
20+
FRAMEWORKS = ("vllm",)
21+
22+
# Server arguments a layer benchmark does not apply: artifacts it never loads (weights,
23+
# tokenizer and the parsers built on it, draft model), the parallel layout (a case's own),
24+
# the KV tiers and prefix cache of a long-running server, and the frontend.
25+
_NOT_APPLIED = {"model", "tokenizer", "tokenizer-mode", "reasoning-parser", "tool-call-parser",
26+
"enable-auto-tool-choice", "speculative-config", "served-model-name", "load-format",
27+
"safetensors-load-strategy", "skip-tokenizer-init", "tensor-parallel-size",
28+
"data-parallel-size", "pipeline-parallel-size", "enable-expert-parallel",
29+
"expert-parallel-size", "decode-context-parallel-size", "dcp-comm-backend",
30+
"distributed-executor-backend", "kv-transfer-config", "kv-events-config",
31+
"enable-prefix-caching", "prefix-match-unit", "enable-cumem-allocator",
32+
"gpu-memory-utilization", "kv-cache-memory-bytes", "max-num-seqs", "max-model-len",
33+
"enforce-eager"}
34+
35+
36+
@functools.cache
37+
def _variants(framework: str, hardware: str) -> tuple[tuple[str, dict], ...]:
38+
"""Every expanded variant InferenceX runs for a framework on a hardware family."""
39+
import yaml
40+
41+
for path in (str(REPO), str(REPO / "utils/srt-slurm/src")):
42+
if path not in sys.path:
43+
sys.path.append(path)
44+
from infx.srt_slurm.synthetic_acceptance import selected_recipes
45+
46+
out = []
47+
for f in sorted(RECIPES.glob(f"*/{framework}/{hardware}-*/*.yaml")):
48+
for name, recipe in selected_recipes(yaml.safe_load(f.read_text()), None):
49+
out.append((str(f.relative_to(REPO)) + (f":{name}" if name else ""), recipe))
50+
return tuple(out)
51+
52+
53+
def find(framework: str, hardware: str, checkpoints: list[str]) -> dict | None:
54+
"""The recipe InferenceX runs for the first of the checkpoints served on this hardware."""
55+
if framework not in FRAMEWORKS or not RECIPES.is_dir():
56+
return None
57+
variants = _variants(framework, hardware)
58+
for ckpt in checkpoints:
59+
for key, r in variants:
60+
if r["model"]["path"] == f"hf:{ckpt}":
61+
role = r["roles"]["agg"]
62+
return {"recipe": key, "checkpoint": ckpt, "image": r["model"]["container"],
63+
"env": {k: str(v) for k, v in (role.get("env") or {}).items()},
64+
"engine_args": role.get("args") or {}}
65+
return None
66+
67+
68+
def checkpoints(sources) -> list[str]:
69+
"""The distinct checkpoints ("org/model") a case's "<org>/<model>/<role>" sources name."""
70+
return list(dict.fromkeys(s.rsplit("/", 1)[0] for s in sources or ()))
71+
72+
73+
def serve_argv(args: dict[str, Any]) -> list[str]:
74+
"""A recipe's server arguments as `vllm serve` command-line arguments, less the ones a
75+
layer benchmark does not apply."""
76+
out = []
77+
for k, v in args.items():
78+
if k in _NOT_APPLIED or v is None or v is False:
79+
continue
80+
out.append(f"--{k}")
81+
if v is not True:
82+
out.append(v if isinstance(v, str) else json.dumps(v))
83+
return out

‎operatorx/runners/common/vllm/attention.py‎

Lines changed: 58 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class _Build:
4242
config: dict
4343
module: str # module path suffix, e.g. "layers.0.self_attn"
4444
engine: dict = field(default_factory=dict)
45+
without: tuple = () # recipe arguments for model parts the cut-down model leaves out
4546

4647

4748
def _family(name: str) -> dict:
@@ -137,8 +138,7 @@ def _build_gqa(op: Op) -> _Build:
137138
rope_theta=a["rope_theta"], use_qk_norm=bool(a.get("qk_norm")), attention_output_gate=False,
138139
num_hidden_layers=1, moe_layer_freq=[0], dense_intermediate_size=_MLP, num_mtp_modules=0,
139140
sparse_attention_config=sparse, vocab_size=_VOCAB)
140-
# MiniMax-M3 serves with 128-token pages (its sparse layers need them), dense layers included
141-
return _Build("minimax_m3", c, "layers.0.self_attn", {"language_model_only": True, "block_size": 128})
141+
return _Build("minimax_m3", c, "layers.0.self_attn", {"language_model_only": True})
142142

143143

144144
def _build_gdn(op: Op) -> _Build:
@@ -227,7 +227,8 @@ def _build_dsv41(a: dict) -> _Build:
227227
t["rope_scaling"] = dict(_yarn(a["rope_scaling"]), rope_type="yarn")
228228
if a.get("indexer"):
229229
t.update(index_topk=a["topk"], index_n_heads=a["index_heads"], index_head_dim=a["index_dim"])
230-
return _Build("deepseek_v41", c, f"layers.{layer}.attn", {"language_model_only": True})
230+
return _Build("deepseek_v41", c, f"layers.{layer}.attn", {"language_model_only": True},
231+
without=("engram-config",))
231232

232233

233234
def _build_dsv4(op: Op) -> _Build:
@@ -281,14 +282,22 @@ def __init__(self, key: str, b: _Build):
281282
self.key = key
282283
self.dir = tempfile.mkdtemp(prefix="opx-attn-")
283284
Path(self.dir, "config.json").write_text(json.dumps(b.config))
284-
kwargs = dict(model=self.dir, load_format="dummy", skip_tokenizer_init=True, enforce_eager=True,
285-
enable_prefix_caching=False, max_num_seqs=_MAX_SEQS,
286-
max_num_batched_tokens=_MAX_BATCHED_TOKENS, kv_cache_memory_bytes=_kv_bytes(),
287-
gpu_memory_utilization=_GPU_UTIL,
288-
# compile kernels when first used (the untimed step) rather than every
289-
# shape up front; FlashInfer autotuning still runs
290-
kernel_config={"enable_jit_warmup": False})
285+
recipe, self.recipe = _recipe_kwargs(b.without)
286+
kwargs = {"max_num_batched_tokens": _MAX_BATCHED_TOKENS, **recipe}
287+
kwargs.update(model=self.dir, load_format="dummy", skip_tokenizer_init=True, enforce_eager=True,
288+
enable_prefix_caching=False, max_num_seqs=_MAX_SEQS, kv_cache_memory_bytes=_kv_bytes(),
289+
gpu_memory_utilization=_GPU_UTIL)
290+
# compile kernels when first used (the untimed step) rather than every shape up
291+
# front; FlashInfer autotuning still runs
292+
kernel = kwargs.get("kernel_config")
293+
if kernel is None or isinstance(kernel, dict):
294+
kwargs["kernel_config"] = {**(kernel or {}), "enable_jit_warmup": False}
295+
else:
296+
kernel.enable_jit_warmup = False
297+
attention = {**self.recipe["attention_config"], **b.engine.pop("attention_config", {})}
291298
kwargs.update(b.engine)
299+
if attention:
300+
kwargs["attention_config"] = attention
292301
self.reqs: list = []
293302
self.n = 0
294303
try:
@@ -347,6 +356,9 @@ def step(self, batch: dict, path: str) -> dict:
347356
from vllm.v1.core.sched.output import NewRequestData
348357
from vllm.v1.request import Request
349358
self.release()
359+
budget = self.runner.vllm_config.scheduler_config.max_num_batched_tokens
360+
if sum(g["count"] * g["q"] for g in batch["groups"]) > budget:
361+
raise UnsupportedOpError(f"the batch schedules more than max-num-batched-tokens={budget} new tokens")
350362
rng = random.Random(batch.get("seed", 0))
351363
for g in batch["groups"]:
352364
for _ in range(g["count"]):
@@ -385,6 +397,35 @@ def capture(*args, **kwargs):
385397
return seen
386398

387399

400+
def _recipe_kwargs(without: tuple = ()) -> tuple[dict, dict]:
401+
"""The InferenceX recipe's server arguments (OPERATORX_ENGINE_ARGS, set per shard by the
402+
planner from operatorx.recipes) as vLLM EngineArgs, parsed by vLLM's own parser; and
403+
what the engine itself does not apply: the attention config (merged with the op's) and
404+
the CUDA-graph mode and sizes serving would use (the engine here runs eagerly)."""
405+
import dataclasses
406+
407+
from vllm.engine.arg_utils import EngineArgs
408+
from vllm.utils.argparse_utils import FlexibleArgumentParser
409+
410+
from operatorx.recipes import serve_argv
411+
args = {k: v for k, v in json.loads(os.environ.get("OPERATORX_ENGINE_ARGS") or "{}").items() if k not in without}
412+
attention = json.loads(args.pop("attention-config", None) or "{}")
413+
compilation = json.loads(args.pop("compilation-config", None) or "{}")
414+
if args.get("max-cudagraph-capture-size"):
415+
compilation.setdefault("max_cudagraph_capture_size", int(args["max-cudagraph-capture-size"]))
416+
info = {"attention_config": attention, "compilation_config": compilation}
417+
if not args:
418+
return {}, info
419+
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
420+
base = vars(parser.parse_known_args(["--model", "m"])[0])
421+
ns = vars(parser.parse_known_args(["--model", "m", *serve_argv(args)])[0])
422+
fields = {f.name for f in dataclasses.fields(EngineArgs)} - {"model"}
423+
kwargs = {k: v for k, v in ns.items() if k in fields and v != base.get(k)}
424+
if compilation.get("custom_ops"): # custom-op selection holds without compilation
425+
kwargs["compilation_config"] = {"custom_ops": compilation["custom_ops"]}
426+
return kwargs, info
427+
428+
388429
def _kv_bytes() -> int:
389430
return int(torch.cuda.get_device_properties(torch.cuda.current_device()).total_memory * _KV_FRACTION)
390431

@@ -454,8 +495,6 @@ def _prepare(op: Op) -> dict:
454495
kv = a.get("kv_cache_dtype")
455496
if kv is not None:
456497
b.engine["kv_cache_dtype"] = _KV_DTYPES[kv]
457-
if b.family == "kimi_k3" and kv == "fp8": # vLLM requires it with K3's fp8 latent cache
458-
b.engine.setdefault("attention_config", {})["use_prefill_query_quantization"] = True
459498
try:
460499
eng = _engine(b)
461500
# vLLM's own startup (model build, profiling and warmup runs) failing on this config
@@ -514,7 +553,13 @@ def _full_graph(eng: _Engine) -> bool:
514553
if len(qs) != 1:
515554
return False
516555
q = qs.pop()
517-
if q * len(eng.reqs) > vllm_linear._capture_sizes()[-1]:
556+
compilation = eng.recipe["compilation_config"]
557+
mode = str(compilation.get("cudagraph_mode", "FULL_AND_PIECEWISE")).upper()
558+
if compilation.get("mode") in (0, "NONE") and "cudagraph_mode" not in compilation or mode in ("NONE", "PIECEWISE"):
559+
return False
560+
sizes = compilation.get("cudagraph_capture_sizes")
561+
top = max(sizes) if sizes else compilation.get("max_cudagraph_capture_size") or vllm_linear._capture_sizes()[-1]
562+
if q * len(eng.reqs) > top:
518563
return False
519564
need = AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE if q == 1 else AttentionCGSupport.UNIFORM_BATCH
520565
for gs in eng.runner.attn_groups:

0 commit comments

Comments
 (0)