Skip to content

Instantly share code, notes, and snippets.

@sglang-bot
Created October 24, 2026 10:24
Show Gist options
  • Select an option

  • Save sglang-bot/f03d7d0dd268b0386177eb2ef09f8b3b to your computer and use it in GitHub Desktop.

Select an option

Save sglang-bot/f03d7d0dd268b0386177eb2ef09f8b3b to your computer and use it in GitHub Desktop.
DeepSeek-V4.1-Flash on SGLang at DeepInfer's benchmark settings: prefill (DEP4) and decode (DEP64)

DeepSeek-V4.1-Flash on SGLang at DeepInfer's benchmark settings: prefill (DEP4) and decode (DEP64)

Files:

  • Prefill: launch_prefill_server.sh starts the server on 4 GPUs, make_placement.py builds its expert placement, bench_engine_steps.py measures it.
  • Decode: launch_decode_server.sh starts the server (once per node), decode_fixed_batch.py measures it.
  • DeepInfer: sitecustomize.py sets DeepEP's Engram QP count for DeepInfer's tuned runs.

Build

  • sglang main, one commit per phase:
    • prefill 7d996300b9
    • decode 3b95120f00, 9 commits earlier on the same main; the commits in between do not touch the decode path.
git clone https://github.com/sgl-project/sglang && cd sglang
git checkout <commit>
pip install -e python
  • Kernel and runtime packages: sgl-flash-mla 1.0.0, sgl-deep-gemm 0.2.3.post2, sglang-kernel 0.4.10, torch 2.14.1 (CUDA 13.0), flashinfer-python 0.7.2, nvidia-cutlass-dsl 4.8.0, tilelang 0.1.12, transformers 5.19.0, deepseek-recipe 0.2.0. The GB300 runs used the lmsysorg/sglang nightly-dev image of 2026-10-21 (c1c287a4) with these packages; the B300 runs used the same packages in a virtualenv.
  • Model deepseek-ai/DeepSeek-V4.1-Flash, revision 5254448103b6254fc646dacbca1cbbf20e9216c1 (the prefill runs used 314113f8a7dadb388215396ba5fbee2c610a04d6, whose safetensors and config.json are identical).
  • DeepInfer 774ce24.
  • bench_engine_steps.py is sglang's benchmark/engine_steps/bench_engine_steps.py (md5 68521f14b72701a59869ad5796fd8f31); it is not in the 7d996300b9 tree, so run it from here.

Prefill

Setting

DeepInfer's prefill benchmark (examples/sweep/run_sweep.sh prefill), on 4 GPUs of one GB300 node or one B300 machine, attention DP 4 and expert parallel 4:

  • 131,072-token context per request: a cached prefix plus 4,096 uncached tokens, one output token.
  • B new tokens per GPU per step, B in 4K, 8K, 16K, 32K, 64K.
  • MoE routing forced balanced (SGLANG_SIMULATE_UNIFORM_EXPERTS=1; DeepInfer's benchmark sets DEEPINFER_FORCE_LOAD_BALANCE=1), EPLB off.
  • 32 redundant experts, 416 physical, 104 per GPU (DeepInfer's benchmark default DEEPINFER_OVERRIDE_NUM_EXTRA_EXPERTS=32). SGLang places them with make_placement.py: each GPU holds its own block of 96 experts plus copies of 8 experts of the next GPU's block, so every GPU carries the same expected load under balanced routing. The default --init-expert-location trivial would leave two GPUs with 104/96 of the average load.

SGLang

python3 make_placement.py --num-layers 40 --out placement_r32_ep4.json   # 40 = num_hidden_layers of the checkpoint

# one server per B, GPUs 0-3
MODEL=/path/DeepSeek-V4.1-Flash B=8192 PLACEMENT=$PWD/placement_r32_ep4.json bash launch_prefill_server.sh > server.log 2>&1

# on the same host, once /health answers; N = 16 x ceil(31 x 8192 / 4096) = 992 requests per rank at 8K
python3 bench_engine_steps.py prefill --base-url http://127.0.0.1:30000 --dp 4 --context 131072 --new-tokens 4096 \
  --tokens-per-step 8192 --warmup-steps 8 --requests 992 --server-log server.log --out result.json
  • Requests per rank: SCALE x min(ceil(31 x B / 4096), 512), SCALE 16 at 4K and 8K, 2 at 16K and 32K, 1 at 64K. The scale and the 8 warm-up steps are our choices; they give the window enough whole steps.
  • Metric: tokens of whole steps over their wall time, per GPU, for every step that ends between 20% and 90% of the requests finishing, on every rank; cross-checked against the engine's own per-step log lines (SGLANG_LOG_MS=1, --server-log).
  • The tool flushes the server's cache before each run. Per B: one discarded warm-up run, then the mean of 3 runs.
  • SGLANG_OPT_DSV41_ENGRAM_PEER_SHARDS=1 (off by default) splits the Engram tables across the GPUs and reads each row from the GPU that owns it. The launcher uses the breakable prefill CUDA graph at 4K and 8K and memory fraction 0.85 at 64K (0.9 elsewhere).

DeepInfer

# 4 GPUs, one process per run; at each B, the fastest of four configurations
python -u examples/benchmark.py --prefill_batch_size B --context_length 131072 --yoco_clip --model_name /path/DeepSeek-V4.1-Flash
config Engram table environment
D host memory (default) none
G GPU memory DEEPINFER_ENGRAM_FORCE_GPU_STORAGE=1
T host memory DI_ENGRAM_QPS=25 NCCL_GIN_GDAKI_MAX_QP_RD_ATOMIC=8, sitecustomize.py on PYTHONPATH
TG GPU memory G and T together
  • T and TG apply DeepEP's own 64K Engram setting (25 QPs, RD atomic 8; vendor/DeepEP/csrc/buffers/engram.hpp) at every B. At 64K it is already the default, so T equals D and TG equals G there.
  • GB300: NCCL_IB_HCA=mlx5_0,mlx5_1,mlx5_2,mlx5_3, one NIC per GPU.
  • Metric: DeepInfer's printed per-step prefill metric (about 9 steps on rank 0).

Results

DeepInfer ms/step divided by SGLang ms/step at each point (above 1: SGLang faster), both engines on the same machine (B300) or node (GB300):

B per GPU B300 SGLang (ms/step) B300 DeepInfer best (ms/step) B300 (x) GB300 SGLang (ms/step) GB300 DeepInfer best (ms/step) GB300 (x)
4K 60.34 62.69 (TG) 1.039 57.93 60.18 (T) 1.039
8K 102.68 105.23 (T) 1.025 89.22 88.68 (TG) 0.994
16K 190.17 189.62 (TG) 0.997 160.55 160.79 (TG) 1.001
32K 368.12 373.61 (T) 1.015 308.85 319.61 (TG) 1.035
64K 723.70 724.51 (G) 1.001 602.33 614.74 (G) 1.021

GSM8K on the SGLang prefill config without the routing simulation (sgl-eval, 200 examples): 97.50% on B300 and GB300.

Decode

Setting

DeepInfer's decode benchmark (examples/sweep/run_sweep.sh decode 131072 3 0.75) on 16 GB300 nodes in one NVLink domain, 4 GPUs each: attention DP 64 and expert parallel 64.

  • 131,072-token context per request: a shared 126,976-token prefix (cached) plus 4,096 own tokens, random ids.
  • Exactly N requests decoding on every rank, N in 8, 16, 32, 64, 128, 256.
  • MoE routing forced balanced on every layer (SGLANG_SIMULATE_ROUND_ROBIN_EXPERTS=1; DeepInfer DEEPINFER_FORCE_LOAD_BALANCE=1).
  • 3 draft tokens, all verified every step on both engines (SGLang SGLANG_RAGGED_VERIFY_MODE=static), so a step does the same work however many are accepted. SGLang simulates acceptance at 3.25 tokens per step; DeepInfer uses its real acceptance. Throughput per GPU = N x 3.25 / step and per-user speed = 3.25 / step, the axes of DeepInfer's published figure.
  • DeepInfer's expert layout on both engines: 384 routed + 64 redundant experts, 7 per GPU (--ep-num-redundant-experts 64 --init-expert-location trivial --ep-dispatch-algorithm dynamic, the launcher's default).

Run

# on every node i of NNODES, same MASTER_ADDR (node 0 serves HTTP on PORT 30000)
MODEL=/path/DeepSeek-V4.1-Flash GPUS=64 NNODES=16 NODE_RANK=<i> MASTER_ADDR=<node 0> bash launch_decode_server.sh

# from any machine that reaches node 0 (standard library only)
python3 decode_fixed_batch.py --url http://<node 0>:30000 --ranks 64 --levels 8,16,32,64,128,256 --out steps.jsonl

Per level the client flushes the cache, caches the prefix on every DP rank (one request per rank pinned with routed_dp_rank), sends N prompts to every rank (pinned, 131,072 output tokens, EOS ignored, so nothing finishes inside the window), waits until the server holds ranks x N running, holds 45 s, and reports the mean over ranks of the engine's own wall time per decode step recorded at exactly N (SGLANG_RECORD_STEP_TIME=1, read from /server_info).

Results

requests per GPU DeepInfer (ms/step) SGLang (ms/step) SGLang step vs DeepInfer
8 9.37 9.41 0.4% longer
16 9.82 9.71 1.1% shorter
32 10.69 10.33 3.4% shorter
64 13.27 12.64 4.7% shorter
128 18.61 18.27 1.8% shorter
256 31.19 28.88 7.4% shorter

Differences left: SGLang keeps the Engram tables in GPU memory (peer shards) and DeepInfer in host memory, its default; DeepInfer's draft model carries 64 redundant experts, which SGLang's draft has no option for.

"""What one prefill or decode step costs at a fixed, steady batch.
Each DP rank warms a long shared prefix; every request adds a random, uncached
--new-tokens suffix and is pinned to its rank. Prefill sends one-token requests,
--tokens-per-step new tokens per rank per step; decode streams --batch-per-rank
requests per rank and times --measure-steps steps.
Throughput counts whole steps only: the window starts and ends at step boundaries
(the scheduler's stamps under --enable-metrics, else response arrival gaps).
--server-log cross-checks the engine's per-step log lines over the same window; it
needs the server on this host's clock, with SGLANG_LOG_MS=1. In HTTP mode the
package, GPU and environment fields describe the benchmark client; server_info
records the server.
python bench_engine_steps.py prefill --base-url URL --dp 4 --tokens-per-step 8192
python bench_engine_steps.py decode --base-url URL --dp 8 --batch-per-rank 64
python bench_engine_steps.py prefill --engine --dp 4 --model-path M --dp-size 4 ...
"""
import argparse
import asyncio
import json
import math
import os
import re
import statistics
import subprocess
import sys
import tempfile
import time
from datetime import datetime
from importlib.metadata import PackageNotFoundError, version
from importlib.util import find_spec
from urllib.error import HTTPError
from urllib.request import Request, urlopen
_TS = r"\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(\.\d+)?\S*(?: DP(\d+))?[^\]]*\] "
_RATE = r"throughput \(token/s\): ([\d.]+)"
_PREFILL = r"Prefill batch.*?#new-token: (\d+)().*?input "
_DECODE = r"Decode batch, #running-req: (\d+).*?(?:accept len: ([\d.]+).*?)?gen "
LINES = {
"prefill": re.compile(_TS + _PREFILL + _RATE),
"decode": re.compile(_TS + _DECODE + _RATE),
}
def step_groups(times, size):
"""(end, count) groups of times, about `size` to a step: any gap over half the
median of the len / size largest gaps splits, so a stall cannot hide a boundary."""
t = sorted(times)
gaps = [b - a for a, b in zip(t, t[1:])]
if not gaps:
return [(t[-1], len(t))] if t else []
top = sorted(gaps)[-max(1, len(t) // size - 1) :]
split, groups, start = 0.5 * top[len(top) // 2], [], 0
for i, gap in enumerate(gaps):
if gap > split:
groups.append((t[i], i + 1 - start))
start = i + 1
return groups + [(t[-1], len(t) - start)]
def group_window(groups, lo, hi):
"""(t0, t1): the ends of the first and last groups that end between the lo and
hi fractions of all items."""
if not groups:
raise SystemExit("no completions to window")
total, cum, ends = sum(c for _, c in groups), 0, []
for end, c in groups:
cum += c
ends.append((end, cum))
i = next(k for k, (_, c) in enumerate(ends) if c >= lo * total)
j = max((k for k, (_, c) in enumerate(ends) if c <= hi * total), default=-1)
if j <= i:
raise SystemExit(f"no whole step between the {lo} and {hi} fractions")
return ends[i][0], ends[j][0]
def log_steps(lines, mode, t0, t1, size, tol=None):
"""Per rank, the engine's ms per step over [t0, t1] (epoch seconds). With `tol`, t0
and t1 are scheduler step ends: each rank logs a line within `tol` of every step end,
so the lines from the one at t0 to the one at t1 are the window's steps. Otherwise
the lines whose interval since the rank's previous line lies inside the window, at
batch `size`."""
per_rank, spans, prev, accept, seen = {}, {}, {}, [], set()
edges, inside = {}, []
for m in filter(None, map(LINES[mode].search, lines)):
ts = datetime.strptime(m.group(1), "%Y-%m-%d %H:%M:%S").timestamp()
ts, step = ts + float(m.group(2) or 0), 0.001 if m.group(2) else 1.0
rank = int(m.group(3) or 0)
start, prev[rank] = prev.get(rank, 0.0), ts
if tol is not None:
if m.group(2) and t0 - tol < ts <= t1 + tol:
edges.setdefault(rank, []).append(ts)
if ts < t1 - tol: # the batches launched inside the window
seen.add(int(m.group(4)))
continue
if start < t0 or ts + step > t1: # stamps are truncated to `step`
continue
seen.add(int(m.group(4)))
inside.append((m, ts, step, rank, start))
if size is None and inside:
size = statistics.mode(int(m.group(4)) for m, *_ in inside)
for m, ts, step, rank, start in inside:
if int(m.group(4)) == size:
accept_len = float(m.group(5) or 1.0)
# The engine's input throughput counts replayed tokens with the new ones
replay = re.search(r"#replay-token: (\d+)", m.string)
tokens = size * accept_len + (int(replay.group(1)) if replay else 0)
ms = tokens / float(m.group(6)) * 1000
per_rank.setdefault(rank, []).append(ms)
lo, hi = spans.get(rank, (start, ts + step))
spans[rank] = min(lo, start), max(hi, ts + step)
accept += [accept_len] if m.group(5) else []
if tol is not None:
whole = {
r: ts
for r, ts in edges.items()
if len(ts) > 1 and ts[0] - t0 <= tol and t1 - ts[-1] <= tol
}
return {
"ms_per_step_per_rank": {
r: (ts[-1] - ts[0]) / (len(ts) - 1) * 1000 for r, ts in whole.items()
},
"complete": bool(prev) and whole.keys() == prev.keys(),
"sizes_seen": sorted(seen),
}
check = {
"ms_per_step_per_rank": {r: statistics.mean(v) for r, v in per_rank.items()}
}
check["coverage"] = min(((b - a) / (t1 - t0) for a, b in spans.values()), default=0)
check["complete"] = check["coverage"] >= 0.8
check["sizes_seen"] = sorted(seen)
if accept:
check["accept_len"] = statistics.mean(accept)
return check
def steps_blurred(group_ms):
median = statistics.median(group_ms)
return any(not 0.6 * median <= ms <= 1.6 * median for ms in group_ms)
def gpu_count(info, dp, explicit=None):
"""Attention DP partitions TP; ordinary DP replicates the TP/PP group."""
replicas = info.get("dp_size", 1)
ranks = replicas * info.get("attn_dp_size", 1)
if "dp_size" in info and dp != ranks:
raise SystemExit(f"--dp {dp} does not match the server's {ranks} ranks")
if explicit is not None:
return explicit
if "tp_size" not in info or "dp_size" not in info:
raise SystemExit("server topology is unavailable; pass --num-gpus explicitly")
return info["tp_size"] * info.get("pp_size", 1) * replicas
def check_cache(meta, new_tokens):
new = meta["prompt_tokens"] - meta["cached_tokens"]
if new != new_tokens:
raise RuntimeError(
f"expected {new_tokens} uncached suffix tokens, got {new}: "
"the shared prefix was evicted/missed or part of a suffix was cached"
)
return new
def check_logs(check, result, size, dp):
"""Every error voids the cross-check and fails the run."""
per_rank = check["ms_per_step_per_rank"]
errors = []
if set(per_rank) != set(range(dp)):
errors.append(f"expected ranks {list(range(dp))}, got {sorted(per_rank)}")
seen = check["sizes_seen"]
if size is None: # prefill: one step size, near the measured new tokens per step
target = result["new_tokens_per_step"]
if len(seen) != 1 or abs(seen[0] - target) > 0.01 * target:
errors.append(f"expected one batch size near {target}, got {seen}")
elif set(seen) != {size}:
errors.append(f"expected batch size {size}, got {seen}")
if not check["complete"]:
errors.append(
"engine lines miss part of the window on some rank; set SGLANG_LOG_MS=1 "
"(and --enable-metrics for prefill) on the server"
)
if per_rank:
check["ms_per_step"] = statistics.mean(per_rank.values())
check["diff_pct"] = (result["ms_per_step"] / check["ms_per_step"] - 1) * 100
if abs(check["diff_pct"]) > 0.5:
errors.append("engine log disagrees by more than 0.5%")
check.update(agree=not errors, errors=errors)
return check
class EngineTransport:
def __init__(self, server_args):
import sglang as sgl
self.engine = sgl.Engine(server_args=server_args)
self.run = self.engine.loop.run_until_complete
async def generate(self, ids, params, rank, stream):
out = await self.engine.async_generate(
input_ids=ids, sampling_params=params, routed_dp_rank=rank, stream=stream
)
if not stream:
yield time.time(), out["meta_info"]
return
async for chunk in out:
yield time.time(), chunk["meta_info"]
async def start_profile(self, body):
from sglang.srt.managers.io_struct import ProfileReq
await self.engine.tokenizer_manager.start_profile(ProfileReq(**body))
async def stop_profile(self):
await self.engine.tokenizer_manager.stop_profile()
def server_info(self):
return self.engine.get_server_info()
def flush_cache(self):
ret = self.engine.flush_cache()
return None if ret.success else ret.message or "flush failed"
def finish(self):
try: # abort decode leftovers
self.engine.tokenizer_manager.abort_request(abort_all=True)
finally:
self.engine.shutdown()
class HttpTransport:
def __init__(self, url, timeout):
import aiohttp
import orjson # a 128K-id body: json.dumps would starve the server
self.url, self.session, self.dumps = url.rstrip("/"), None, orjson.dumps
self.timeout = timeout
self.new_session = lambda: aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=None, sock_read=timeout),
connector=aiohttp.TCPConnector(limit=0),
)
self.loop = asyncio.new_event_loop()
self.run = self.loop.run_until_complete
def post(self, path, body):
self.session = self.session or self.new_session()
headers = {"Content-Type": "application/json"}
return self.session.post(
self.url + path, data=self.dumps(body), headers=headers
)
async def generate(self, ids, params, rank, stream):
body = dict(input_ids=ids, sampling_params=params, routed_dp_rank=rank)
async with self.post("/generate", {**body, "stream": stream}) as resp:
resp.raise_for_status()
if not stream:
yield time.time(), (await resp.json())["meta_info"]
return
async for raw in resp.content:
line = raw.decode().strip()
if line.startswith("data:") and line != "data: [DONE]":
yield time.time(), json.loads(line[5:])["meta_info"]
async def start_profile(self, body):
async with self.post("/start_profile", body) as resp:
resp.raise_for_status()
async def stop_profile(self):
async with self.post("/stop_profile", {}) as resp:
resp.raise_for_status()
def server_info(self):
with urlopen(self.url + "/server_info", timeout=self.timeout) as response:
return json.load(response)
def flush_cache(self):
try:
with urlopen(
Request(self.url + "/flush_cache", method="POST"), timeout=self.timeout
):
pass
except HTTPError as e:
return e.read().decode()
def finish(self):
try:
if self.session is not None:
self.run(self.session.close())
finally:
self.loop.close()
def nvidia_smi(*args):
try:
return subprocess.check_output(["nvidia-smi", *args], text=True).splitlines()
except (OSError, subprocess.CalledProcessError):
return []
def package_version(name):
try:
return version(name) # the first one on sys.path, the one import resolves
except PackageNotFoundError:
spec = find_spec(name.replace("-", "_"))
return spec and spec.origin # a source tree without metadata: its path
def environment():
pkgs = {"sglang", "sglang-kernel", "sgl-deep-gemm", "sgl-flash-mla", "torch"}
gpus = nvidia_smi("--query-gpu=index,name,uuid,driver_version", "--format=csv")
env = {k: v for k, v in os.environ.items() if k.startswith("SGLANG_")}
devices = os.environ.get("CUDA_VISIBLE_DEVICES")
return dict(
versions={p: package_version(p) for p in sorted(pkgs)},
gpus=gpus[1:],
visible_devices=devices,
sglang_env=env,
)
async def batch(
args,
tp,
prompt,
n_each,
params,
done,
what,
*,
check_prefix=False,
on_complete=None,
):
"""n_each requests per rank, submitted round-robin over the ranks so none starts
ahead, about eight steps' worth in flight on each."""
in_flight = max(1, args.tokens_per_step // args.new_tokens) * 8 + 1
limits = [asyncio.Semaphore(in_flight) for _ in range(args.dp)]
async def collect(r):
async for t, meta in tp.generate(prompt(r), params, r, False):
new = meta["prompt_tokens"] - meta["cached_tokens"]
if check_prefix:
check_cache(meta, args.new_tokens)
done.append((t, meta.get("prefill_finished_time"), new, r))
if on_complete is not None:
await on_complete(r)
async def one(r):
async with limits[r]:
await asyncio.wait_for(collect(r), timeout=args.timeout)
tasks = [
asyncio.ensure_future(one(r)) for _ in range(n_each) for r in range(args.dp)
]
finished, last, shown = 0, time.time(), time.time()
try:
while finished < len(tasks):
await asyncio.wait([t for t in tasks if not t.done()], timeout=1)
for task in tasks:
if task.done() and task.exception():
raise task.exception()
now, n = time.time(), sum(t.done() for t in tasks)
if n > finished:
finished, last = n, now
if now - last > args.timeout:
raise SystemExit(
f"{what}: no request finished for {args.timeout:.0f} s"
)
if now - shown >= 5 or finished == len(tasks):
print(f"{what}: {finished}/{len(tasks)} requests", flush=True)
shown = now
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
async def profile_prefill(args, tp, prompt, params):
"""Profile a separate, continuously fed burst once every rank has warmed up;
the captured steps come from the trace."""
per_step = max(1, args.tokens_per_step // args.new_tokens)
warmup = max(
per_step, math.ceil(args.requests * args.lo), args.warmup_steps * per_step
)
reserve = (args.profile_steps + 4) * per_step
if warmup + reserve > args.requests:
raise SystemExit(
f"profile needs {warmup} warmup + {reserve} remaining requests per rank; "
"raise --requests or lower --lo/--profile-steps"
)
completed, trigger = [0] * args.dp, []
def check_remaining():
# A drained burst would put queue-drain steps into the trace.
remaining = [args.requests - n for n in completed]
if min(remaining) < reserve:
raise RuntimeError(
f"profile burst is draining: remaining per rank {remaining}, "
f"need at least {reserve}; raise --requests"
)
async def on_complete(rank):
completed[rank] += 1
if trigger or min(completed) < warmup:
return
check_remaining()
trigger.append(completed.copy())
# Only this request awaits the ACK; its peers keep the batch supplied.
await tp.start_profile(args.profile)
check_remaining()
try:
await batch(
args,
tp,
prompt,
args.requests,
params,
[],
"profile",
check_prefix=True,
on_complete=on_complete,
)
if not trigger:
raise RuntimeError("profile did not start after all ranks warmed up")
except BaseException:
# A failed or cancelled start may still have reached the engine.
if trigger:
try:
await asyncio.wait_for(tp.stop_profile(), timeout=args.timeout)
except Exception as exc:
print(f"profile cleanup failed: {exc!r}", file=sys.stderr)
raise
return {"trigger_completions_per_rank": trigger[0]}
async def prefill(args, tp, prompt):
nc, B = args.new_tokens, args.tokens_per_step
per_step = max(1, B // nc)
params = {"max_new_tokens": 1, "temperature": 0.0, "ignore_eos": True}
n_warmup = args.warmup_steps * per_step
await batch(args, tp, prompt, n_warmup, params, [], "warmup", check_prefix=True)
done = []
await batch(
args, tp, prompt, args.requests, params, done, "measured", check_prefix=True
)
stamp = "scheduler" if all(s for _, s, _, _ in done) else "arrival"
times = [s if stamp == "scheduler" else t for t, s, _, _ in done]
# The window comes from all completions; steps from each rank's own ends, since
# one rank's ends can trail another's and split a step shared across ranks.
T0, T1 = group_window(step_groups(times, per_step * args.dp), args.lo, args.hi)
spans, rank_steps, per_rank, group_ms = [], [], [], []
for r in range(args.dp):
mine = [(t, n) for t, (_, _, n, rr) in zip(times, done) if rr == r]
groups = step_groups([t for t, _ in mine], per_step)
all_ends = [end for end, _ in groups]
if r == 0: # rank 0's ends inside the window anchor every rank's window
inside = [end for end in all_ends if T0 <= end <= T1]
if len(inside) < 4:
raise SystemExit("the window holds under three steps; raise --requests")
anchors = inside[0], inside[-1]
a, b = (min(all_ends, key=lambda end: abs(end - x)) for x in anchors)
ends = [end for end in all_ends if a <= end <= b]
counts = [c for end, c in groups if a < end <= b]
if min(counts) < 0.8 * statistics.median(counts): # a short step
raise SystemExit(
f"rank {r} steps finished {min(counts)} to {max(counts)} requests: "
"the queue ran dry"
)
spans.append((a, b))
rank_steps.append(len(ends) - 1)
per_rank.append(sum(n for t, n in mine if a < t <= b))
group_ms += [(y - x) * 1000 for x, y in zip(ends, ends[1:])]
if len(set(rank_steps)) > 1:
raise SystemExit(f"ranks ran unequal steps in the window: {rank_steps}")
# Requests count at completion, so window edges can shift a few between ranks;
# a rank short by a whole step's budget missed steps.
if max(per_rank) - min(per_rank) > B:
raise SystemExit(f"ranks served unequal tokens in the window: {per_rank}")
# Count steps, not tokens / B: replayed tokens (e.g. the encoder's SWA window)
# share the step budget, so a full step can carry fewer than B new tokens.
steps, tokens = rank_steps[0], sum(per_rank)
t0 = statistics.mean(a for a, _ in spans)
t1 = statistics.mean(b for _, b in spans)
profile = (
await profile_prefill(args, tp, prompt, params) if args.profile_steps else None
)
return dict(
**({"profile": profile} if profile is not None else {}),
steps=steps,
seconds=t1 - t0,
tokens=tokens,
wall=(t0, t1),
group_ms=group_ms,
size=round(tokens / (steps * args.dp)),
stamp=stamp,
)
async def decode(args, tp, prompt):
n, events, first = args.batch_per_rank, [], set()
params = {"max_new_tokens": args.output_len, "temperature": 0.0, "ignore_eos": True}
async def one(r, k):
seen = 0
async for t, meta in tp.generate(prompt(r), params, r, True):
if (r, k) not in first:
check_cache(meta, args.new_tokens)
count = meta["completion_tokens"]
if count < seen:
raise RuntimeError("stream completion_tokens decreased")
if count > seen:
events.append((t, count - seen))
seen = count
first.add((r, k))
async def wait(cond, why):
deadline, shown = time.time() + args.timeout, time.time()
while not cond():
if time.time() - shown >= 5:
print(why(), flush=True)
shown = time.time()
if ended := next((task for task in tasks if task.done()), None):
exc = ended.exception() # None: it finished
raise SystemExit(f"a request ended early ({exc!r}); see --output-len")
if time.time() > deadline:
raise SystemExit(f"timed out after {args.timeout:.0f} s: " + why())
await asyncio.sleep(0.1)
def started():
per_rank = [sum(1 for rank, _ in first if rank == r) for r in range(args.dp)]
return (
f"requests started per rank {per_rank} of {n}; the server may admit "
"fewer (see --max-running-requests over the DP size)"
)
def steps_after(t_all):
return len(step_groups([e[0] for e in events if e[0] > t_all], n * args.dp))
tasks = [asyncio.ensure_future(one(r, k)) for r in range(args.dp) for k in range(n)]
try:
await wait(lambda: len(first) == n * args.dp, started) # the full batch runs
t_all, need = time.time(), args.warmup_steps + args.measure_steps + 2
await wait(
lambda: steps_after(t_all) >= need,
lambda: f"{steps_after(t_all)} of {need} steps",
)
if args.profile_steps:
await tp.start_profile(args.profile)
await asyncio.sleep(2 + args.profile_steps * 0.1)
finally: # also on failure, so no stream outlives the event loop
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
groups = step_groups([e[0] for e in events if e[0] > t_all], n * args.dp)
window = [end for end, _ in groups[args.warmup_steps :][: args.measure_steps + 1]]
t0, t1 = window[0], window[-1]
tokens = sum(k for t, k in events if t0 < t <= t1)
return dict(
steps=args.measure_steps,
seconds=t1 - t0,
tokens=tokens,
wall=(t0, t1),
group_ms=[(b - a) * 1000 for a, b in zip(window, window[1:])],
size=n,
stamp="arrival",
)
def positive(cast):
def parse(text):
value = cast(text)
if not math.isfinite(value) or value <= 0:
raise argparse.ArgumentTypeError(f"{text} is not positive and finite")
return value
return parse
pos_int, pos_float = positive(int), positive(float)
OPTIONS = [ # flag, type, default, help
("--base-url", str, None, "a running server (or pass --engine)"),
("--dp", pos_int, None, "attention DP ranks to pin requests to"),
("--num-gpus", pos_int, None, "GPUs to divide by (default: server topology)"),
("--context", int, 131072, "prompt tokens: shared prefix plus suffix"),
("--new-tokens", pos_int, 4096, "random, uncached suffix tokens per request"),
("--tokens-per-step", pos_int, 65536, "prefill: new tokens per rank per step"),
("--requests", pos_int, None, "prefill: requests per rank (31B/new, max 512)"),
("--batch-per-rank", pos_int, 64, "decode: running requests per rank"),
("--output-len", pos_int, 2048, "decode: max new tokens; must outlast the run"),
("--warmup-steps", int, None, "steps before the window (prefill 5, decode 50)"),
("--measure-steps", pos_int, 60, "decode: steps in the window"),
("--lo", float, 0.2, "prefill: window start, as a fraction of completions"),
("--hi", float, 0.9, "prefill: window end, as a fraction of completions"),
("--profile-steps", int, 0, "profile this many steps after the window"),
("--profile-dir", str, "/tmp/engine_steps_profile", "profile output directory"),
("--profile-activities", str, None, "e.g. GPU (default: the server's)"),
("--timeout", pos_float, 600, "seconds a stalled server gets before failing"),
("--seed", int, 0, "seed of the random ids"),
("--out", str, None, "write the JSON record here"),
]
WORKLOAD = [flag[2:].replace("-", "_") for flag, *_ in OPTIONS if flag != "--out"]
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("mode", choices=["prefill", "decode"])
for flag, typ, default, help_ in OPTIONS:
ap.add_argument(flag, type=typ, default=default, help=help_)
ap.add_argument("--engine", action="store_true", help="in-process engine")
ap.add_argument("--server-log", nargs="+", default=[], help="logs to cross-check")
ap.add_argument("--sample-gpu", action="store_true", help="local SM clock, power")
ap.add_argument("--no-flush", action="store_true", help="keep the server's cache")
ap.add_argument("--profile-no-stack", action="store_true", help="skip stacks")
if "--engine" in sys.argv:
from sglang.srt.server_args import ServerArgs
ServerArgs.add_cli_args(ap)
args = ap.parse_args()
if args.engine == bool(args.base_url) or not args.dp:
ap.error("pass --dp and exactly one of --engine and --base-url")
if args.context < args.new_tokens or not 0 <= args.lo < args.hi <= 1:
ap.error("need --context >= --new-tokens and 0 <= --lo < --hi <= 1")
if args.mode == "prefill" and args.tokens_per_step % args.new_tokens:
ap.error("--tokens-per-step must be a multiple of --new-tokens")
if args.warmup_steps is None:
args.warmup_steps = 5 if args.mode == "prefill" else 50
if args.warmup_steps < 0 or args.profile_steps < 0:
ap.error("warmup and profile step counts must be nonnegative")
nc, B = args.new_tokens, args.tokens_per_step
args.requests = args.requests or min(math.ceil(31 * B / nc), 512)
args.profile = dict(output_dir=args.profile_dir, num_steps=args.profile_steps)
if args.profile_activities:
args.profile["activities"] = args.profile_activities.split(",")
if args.profile_no_stack:
args.profile["with_stack"] = False
if args.engine:
from sglang.srt.server_args import ServerArgs
tp = EngineTransport(ServerArgs.from_cli_args(args))
else:
tp = HttpTransport(args.base_url, args.timeout)
try:
run_benchmark(args, tp)
finally:
tp.finish()
def run_benchmark(args, tp):
import numpy as np
nc = args.new_tokens
rng = np.random.default_rng(args.seed)
def ids(n): # plain vocabulary ids, clear of special tokens
return rng.integers(1000, 100000, size=n).tolist()
prefixes = [ids(args.context - nc) for _ in range(args.dp)]
def prompt(r):
return prefixes[r] + ids(nc)
info = tp.server_info()
args.num_gpus = gpu_count(info, args.dp, args.num_gpus)
if info.get("enable_eplb"):
raise SystemExit("EPLB is on: rebalance steps would land in the window")
if args.mode == "decode" and info.get("stream_interval", 1) != 1:
raise SystemExit("decode needs --stream-interval 1: one streamed chunk a step")
# A warm cache (an earlier run with the same seed) would serve the suffixes
if not args.no_flush and (err := tp.flush_cache()):
raise SystemExit(f"flushing the server's cache failed: {err}")
async def run():
warm = {"max_new_tokens": 1, "temperature": 0.0}
for _ in range(2): # the second pass hits: later requests reuse the prefix
await batch(args, tp, prompt, 1, warm, [], "prefix warmup")
return await (prefill if args.mode == "prefill" else decode)(args, tp, prompt)
query = [
"--query-gpu=timestamp,clocks.sm,power.draw",
"--format=csv,noheader,nounits",
]
if devices := os.environ.get("CUDA_VISIBLE_DEVICES"):
query += ["-i", devices] # nvidia-smi itself ignores the variable
sample_output = tempfile.TemporaryFile(mode="w+t") if args.sample_gpu else None
sampler, sample_text = None, ""
try:
if sample_output is not None:
sampler = subprocess.Popen(
["nvidia-smi", *query, "-lms", "250"], stdout=sample_output, text=True
)
res = tp.run(run())
finally:
if sampler:
sampler.terminate()
try:
sampler.wait(timeout=5)
except subprocess.TimeoutExpired:
sampler.kill()
sampler.wait()
if sample_output is not None:
sample_output.seek(0)
sample_text = sample_output.read()
sample_output.close()
size = res.pop("size")
if args.mode == "prefill":
res["new_tokens_per_step"] = size
steps, span, tokens = res["steps"], res["seconds"], res["tokens"]
res.update(
ms_per_step=span / steps * 1000, tok_s_per_gpu=tokens / span / args.num_gpus
)
if args.mode == "decode":
res["accept_len"] = tokens / (steps * size * args.dp)
if sampler:
rows = [r.split(", ") for r in sample_text.splitlines() if ", " in r]
t0, t1 = res["wall"]
in_window = [
r[1:]
for r in rows
if t0 <= datetime.strptime(r[0], "%Y/%m/%d %H:%M:%S.%f").timestamp() <= t1
]
for key, col in zip(("sm_clock_mhz", "power_w"), zip(*in_window)):
res[key + "_median"] = statistics.median(float(x) for x in col)
lines = [line for path in args.server_log for line in open(path, errors="replace")]
tol = min(res["group_ms"]) / 4000 if res["stamp"] == "scheduler" else None
check = {}
if args.server_log:
# Prefill steps carry the engine's batch, not --tokens-per-step: match any size
fixed = None if args.mode == "prefill" else size
check = log_steps(lines, args.mode, *res["wall"], fixed, tol)
check = check_logs(check, res, fixed, args.dp)
errors = check.get("errors", [])
if args.mode == "decode" and steps_blurred(res["group_ms"]):
errors = errors + [
"decode steps stray past 0.6-1.6x their median: streamed chunks blur the "
"step boundaries at this step length, so ms/step is unreliable"
]
record = dict(
mode=args.mode,
transport="engine" if args.engine else "http",
environment_scope="engine_host" if args.engine else "benchmark_client",
argv=sys.argv,
workload={k: getattr(args, k) for k in WORKLOAD},
result=res,
cross_check=check,
errors=errors,
server_info=info,
**environment(),
)
print(
f"{args.mode}: {res['ms_per_step']:.2f} ms/step, "
f"{res['tok_s_per_gpu']:.0f} tok/s/GPU over {steps:.2f} whole steps "
f"({res['stamp']} times)"
)
if "ms_per_step" in check:
print(
f"engine log: {check['ms_per_step']:.2f} ms/step, {check['diff_pct']:+.2f}%"
)
for error in errors:
print(f"ERROR: {error}")
if args.out:
with open(args.out, "w") as f:
json.dump(record, f, indent=1, default=str)
if errors:
raise SystemExit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""Decode step time per rank at a fixed batch, against a running sglang server. One file, standard library only.
The server must run with SGLANG_RECORD_STEP_TIME=1 (its own wall time per decode step, per DP rank, keyed by the
running count, returned by /server_info). For each N in --levels:
1. flush the cache and cache the shared prefix on every DP rank (one request per rank, pinned with routed_dp_rank);
2. send N prompts to every rank (pinned), each = the shared prefix + its own --new-tokens random ids, decoding until killed;
3. wait until the server holds ranks x N running and none waiting, read /server_info, hold --dwell seconds, read again;
4. step at N = mean over ranks of the samples recorded at exactly N in between (first sample per rank dropped);
5. stop the prompts and wait for the server to drain.
Prints one line per level and writes them as JSON lines to --out.
python3 decode_fixed_batch.py --url http://HOST:PORT --ranks 64 --levels 8,16,32,64,128,256 --out steps.jsonl
python3 decode_fixed_batch.py --url ... --ranks 64 --levels 128 --profile-steps 20 --profile-dir /logs/prof # plus a GPU trace
Defaults are DeepInfer's published decode setting (131,072-token context: 126,976 cached + 4,096 own tokens). Ids are
drawn from [1000, 100000) so no special token appears.
Server side, for DeepInfer's setting (what the sglang server must run with; the client needs nothing else):
env SGLANG_RECORD_STEP_TIME=1 the per-rank step record this script reads
SGLANG_SIMULATE_ROUND_ROBIN_EXPERTS=1 forced balanced MoE routing (DeepInfer: DEEPINFER_FORCE_LOAD_BALANCE=1)
SGLANG_SIMULATE_ACC_LEN=3.25 SGLANG_SIMULATE_ACC_METHOD=match-expected SGLANG_SIMULATE_ACC_TOKEN_MODE=real-draft-token
SGLANG_RAGGED_VERIFY_MODE=static fixed-length verification: every step commits 1 + 3 slots per request
args --enable-dp-attention --speculative-algorithm DSPARK --speculative-dspark-block-size 3 --speculative-num-steps 3
--max-running-requests >= ranks x (max N + 8) (the engine admits a few below the cap per rank)
--cuda-graph-max-bs-decode 256, and a KV pool that holds ranks x N x 131K tokens at the largest N
The DEP64 GB300 configuration behind the published curve (MegaGate, v41_new KV layout, Engram peer shards, fp32 lm-head,
0.8 memory fraction, 8K per-rank prefill chunk, and DeepInfer's expert layout --ep-num-redundant-experts 64
--init-expert-location trivial --ep-dispatch-algorithm dynamic) is launch_decode_server.sh in this gist.
"""
import argparse, http.client, json, random, statistics, subprocess, sys, time, urllib.parse, urllib.request
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--url", required=True)
ap.add_argument("--ranks", type=int, required=True, help="attention DP ranks")
ap.add_argument("--levels", default="8,16,32,64,128,256", help="requests per rank")
ap.add_argument("--prefix-len", type=int, default=126976)
ap.add_argument("--new-tokens", type=int, default=4096)
ap.add_argument("--output-len", type=int, default=131072, help="max new tokens; must outlast the level")
ap.add_argument("--dwell", type=float, default=45, help="seconds held at the full batch")
ap.add_argument("--per-call", type=int, default=64, help="prompts per /generate call")
ap.add_argument("--timeout", type=float, default=1800, help="seconds to reach the full batch")
ap.add_argument("--out", default="steps.jsonl")
ap.add_argument("--profile-steps", type=int, default=0, help="after a level's dwell, trace this many scheduler steps on every rank")
ap.add_argument("--profile-levels", default="", help="levels to trace (default: all when --profile-steps is set)")
ap.add_argument("--profile-dir", default="/tmp/decode_fixed_batch_profile", help="server-side directory for the traces")
ap.add_argument("--profile-activities", default="GPU", help="comma list, e.g. GPU or CPU,GPU; GPU alone keeps host timing undisturbed")
ap.add_argument("--_send", nargs=3, type=int, metavar=("RANK", "COUNT", "SEED"), help=argparse.SUPPRESS)
args = ap.parse_args()
U = urllib.parse.urlparse(args.url)
def ids(seed, n):
r = random.Random(seed)
return [r.randrange(1000, 100000) for _ in range(n)]
def post(path, body, timeout=None):
conn = http.client.HTTPConnection(U.hostname, U.port, timeout=timeout)
conn.request("POST", path, body=body if isinstance(body, bytes) else json.dumps(body).encode(),
headers={"Content-Type": "application/json"})
resp = conn.getresponse()
return resp.status, resp.read()
def get_json(path):
with urllib.request.urlopen(args.url + path, timeout=120) as r:
return json.load(r)
def running_waiting():
with urllib.request.urlopen(args.url + "/v1/loads?format=prometheus&include=core", timeout=30) as r:
text = r.read().decode()
run = sum(float(l.split()[-1]) for l in text.splitlines() if l.startswith("sglang_num_running_reqs"))
wait = sum(float(l.split()[-1]) for l in text.splitlines() if l.startswith("sglang_num_waiting_reqs"))
return int(run), int(wait)
def records():
return [{int(k): v for k, v in (s.get("step_time_dict") or {}).items()} for s in get_json("/server_info")["internal_states"]]
PREFIX = ids(12345, args.prefix_len)
if args._send: # child: one pinned /generate call carrying COUNT prompts, held open until the parent kills it
rank, count, seed = args._send
rows = ",".join(json.dumps(PREFIX + ids(seed * 100003 + k, args.new_tokens)) for k in range(count))
body = ('{"input_ids":[' + rows + '],"routed_dp_rank":%d,"sampling_params":{"max_new_tokens":%d,'
'"ignore_eos":true,"temperature":0.0},"stream":false}' % (rank, args.output_len)).encode()
status, text = post("/generate", body)
sys.exit(f"HTTP {status}: {text[:300]!r}" if status != 200 else 0)
def warm(): # the shared prefix in every rank's cache, checked by the cached-token count
def one(rank):
_, out = post("/generate", {"input_ids": PREFIX + ids(7, 8), "routed_dp_rank": rank,
"sampling_params": {"max_new_tokens": 1, "temperature": 0.0}}, timeout=1800)
return json.loads(out)["meta_info"].get("cached_tokens", 0)
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(args.ranks) as ex:
list(ex.map(one, range(args.ranks)))
cached = list(ex.map(one, range(args.ranks)))
return min(cached)
def drain():
for _ in range(600):
if running_waiting() == (0, 0):
return
time.sleep(2)
out = open(args.out, "a")
profile_levels = {int(x) for x in args.profile_levels.split(",") if x} or {int(x) for x in args.levels.split(",")}
for n in [int(x) for x in args.levels.split(",")]:
drain()
post("/flush_cache", b"")
t0 = time.time(); cached = warm()
calls = [(r, min(args.per_call, n - k), r * 1000 + k) for r in range(args.ranks) for k in range(0, n, args.per_call)]
kids = [subprocess.Popen([sys.executable, __file__, "--url", args.url, "--ranks", str(args.ranks),
"--prefix-len", str(args.prefix_len), "--new-tokens", str(args.new_tokens),
"--output-len", str(args.output_len), "--_send", str(r), str(c), str(s)],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
for r, c, s in calls]
deadline, settled = time.time() + args.timeout, 0
while settled < 3 and time.time() < deadline:
dead = [k for k in kids if k.poll() is not None]
if dead: # a sender exited before the level: the server refused its prompts
sys.exit(f"level {n}: a sender exited: {dead[0].stderr.read().decode()[-400:]}")
run, wait = running_waiting()
settled = settled + 1 if (run == args.ranks * n and wait == 0) else 0
time.sleep(2)
t_fill = time.time() - t0
row = dict(requests_per_rank=n, ranks=args.ranks, prefix_cached_min=cached, fill_s=round(t_fill, 1))
if settled >= 3:
before = records(); time.sleep(args.dwell); after = records()
per_rank = []
for b, a in zip(before, after):
new = a.get(n, [])[len(b.get(n, [])):][1:]
if new:
per_rank.append(statistics.mean(new) * 1000)
row.update(step_ms=round(statistics.mean(per_rank), 3) if per_rank else None, ranks_at_n=len(per_rank),
step_ms_min=round(min(per_rank), 3) if per_rank else None,
step_ms_max=round(max(per_rank), 3) if per_rank else None)
if args.profile_steps and n in profile_levels: # trace after the measured window, same batch
pdir = f"{args.profile_dir}/bs{n}"
status, text = post("/start_profile", {"output_dir": pdir, "num_steps": args.profile_steps,
"activities": args.profile_activities.split(",")}, timeout=120)
row.update(profile_dir=pdir, profile_status=status)
time.sleep(min(600, 30 + args.profile_steps * (row["step_ms"] or 50) / 1000 * 4)) # export takes a few x the steps
else:
row.update(step_ms=None, error="the batch never settled at ranks x N")
for k in kids:
k.kill()
print(json.dumps(row), flush=True)
out.write(json.dumps(row) + "\n"); out.flush()
drain()
#!/usr/bin/env bash
# Launch the sglang server for decode_fixed_batch.py: DeepSeek-V4.1-Flash, DP attention x EP over GPUS GPUs
# (DEP64 = 16 nodes x 4 GB300 in one NVLink domain), at DeepInfer's decode setting: forced balanced routing, 3 drafts with
# fixed-length verification at simulated acceptance 3.25, the per-rank step record, and DeepInfer's expert layout
# (384 routed + 64 redundant experts).
# Run once per node with the same MASTER_ADDR; node 0 serves HTTP on PORT:
# MODEL=/path/DeepSeek-V4.1-Flash GPUS=64 NNODES=16 NODE_RANK=<i> MASTER_ADDR=<node 0> bash launch_decode_server.sh
# Then, from any machine that reaches node 0:
# python3 decode_fixed_batch.py --url http://MASTER_ADDR:PORT --ranks GPUS --levels 8,16,32,64,128,256
# REDUNDANT_EXPERTS=64 is the default; REDUNDANT_EXPERTS= (empty) runs SGLang's own 384-expert layout.
set -euo pipefail
: "${MODEL:?}" "${GPUS:?}" "${NNODES:?}" "${NODE_RANK:?}" "${MASTER_ADDR:?}"
PORT=${PORT:-30000}
REDUNDANT_EXPERTS=${REDUNDANT_EXPERTS-64}
env \
SGLANG_RECORD_STEP_TIME=1 \
SGLANG_OPT_DSV41_ENGRAM_PEER_SHARDS=1 \
SGLANG_OPT_DEEPGEMM_MEGA_GATE=1 \
SGLANG_DSV4_KV_LAYOUT=v41_new \
SGLANG_OPT_DSV41_BF16_INDEX_LOGITS=1 \
SGLANG_RAGGED_VERIFY_MODE=static \
SGLANG_SIMULATE_ACC_LEN=3.25 \
SGLANG_SIMULATE_ROUND_ROBIN_EXPERTS=1 \
SGLANG_SIMULATE_ACC_METHOD=match-expected \
SGLANG_SIMULATE_ACC_TOKEN_MODE=real-draft-token \
SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=16384 \
SGLANG_OPT_DSV41_MEGA_MHC_PREFILL=1 \
SGLANG_TIMEOUT_KEEP_ALIVE=900 \
NCCL_MNNVL_ENABLE=1 \
NCCL_CUMEM_ENABLE=1 \
python3 -m sglang.launch_server --model-path "$MODEL" --served-model-name deepseek-ai/DeepSeek-V4.1-Flash \
--nnodes "$NNODES" --node-rank "$NODE_RANK" --dist-init-addr "$MASTER_ADDR:5000" --host 0.0.0.0 --port "$PORT" \
--trust-remote-code --random-seed 733427905 \
--tensor-parallel-size $GPUS \
--data-parallel-size $GPUS \
--expert-parallel-size $GPUS \
--enable-dp-attention \
--enable-dp-lm-head \
--enable-fp32-lm-head \
--enable-dp-attention-local-control-broadcast \
--moe-a2a-backend megamoe \
--dsv4-attn-backend flashmla_mega \
--speculative-algorithm DSPARK \
--speculative-dspark-block-size 3 \
--speculative-num-steps 3 \
--stream-interval 32 \
--swa-prefix-tails 2048 \
--enable-decoder-swa-bounded-replay \
--mem-fraction-static 0.8 \
--max-running-requests $(( GPUS * 264 )) \
--cuda-graph-max-bs-decode 256 \
--tokenizer-worker-num 8 \
--watchdog-timeout 3600 \
--skip-server-warmup \
--enable-metrics \
--chunked-prefill-size $(( GPUS * 8192 )) \
--max-prefill-tokens 8192 \
${REDUNDANT_EXPERTS:+--ep-num-redundant-experts $REDUNDANT_EXPERTS --init-expert-location trivial --ep-dispatch-algorithm dynamic}
#!/usr/bin/env bash
# Launch the sglang server for the prefill benchmark on 4 GPUs (DP4 / EP4) at DeepInfer's prefill setting:
# 131,072-token contexts, 4,096 uncached tokens per request, B new tokens per GPU per step, 32 redundant experts.
# Build the expert placement once:
# python3 make_placement.py --num-layers 40 --out placement_r32_ep4.json
# Then start one server per B and, on the same host, once /health answers:
# python3 bench_engine_steps.py prefill --base-url http://127.0.0.1:30000 --dp 4 --context 131072 --new-tokens 4096 \
# --tokens-per-step B --warmup-steps 8 --requests N --server-log server.log --out result.json
# with N = SCALE x min(ceil(31 x B / 4096), 512) requests per rank, SCALE 16 at 4K and 8K, 2 at 16K and 32K, 1 at 64K.
# MODEL=/path/DeepSeek-V4.1-Flash B=8192 PLACEMENT=$PWD/placement_r32_ep4.json bash launch_prefill_server.sh > server.log 2>&1
set -euo pipefail
: "${MODEL:?}" "${B:?}" "${PLACEMENT:?}"
PORT=${PORT:-30000}
MEM=${MEM:-$([ "$B" -ge 65536 ] && echo 0.85 || echo 0.9)} # 0.9 OOMs intermittently at 64K
GRAPH=""; [ "$B" -le 8192 ] && GRAPH="--cuda-graph-backend-prefill breakable --cuda-graph-prefill-max-context 262144 --cuda-graph-max-seq-len-prefill 262144 --cuda-graph-bs-prefill 4096 8192"
env \
SGLANG_LOG_MS=1 \
SGLANG_OPT_DSV41_ENGRAM_PEER_SHARDS=1 \
SGLANG_OPT_DSV41_MEGA_MHC_PREFILL=1 \
SGLANG_OPT_DSV41_BF16_INDEX_LOGITS=1 \
SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=65536 \
SGLANG_DSV4_KV_LAYOUT=v41_new \
SGLANG_DP_USE_GATHERV=1 \
SGLANG_RAGGED_VERIFY_MODE=static \
SGLANG_ENABLE_DP_SPEC_PREFILL_COORDINATION=0 \
SGLANG_NUMA_BIND_V2=0 \
SGLANG_DEFAULT_THINKING=1 \
SGLANG_DSV41_REASONING_EFFORT=high \
SGLANG_TIMEOUT_KEEP_ALIVE=900 \
SGLANG_SIMULATE_UNIFORM_EXPERTS=1 \
SGLANG_SIMULATE_ACC_LEN=3.51 \
SGLANG_SIMULATE_ACC_METHOD=match-expected \
SGLANG_SIMULATE_ACC_TOKEN_MODE=real-draft-token \
CUDA_VISIBLE_DEVICES=0,1,2,3 \
python3 -m sglang.launch_server \
--model-path "$MODEL" --served-model-name deepseek-ai/DeepSeek-V4.1-Flash --trust-remote-code \
--tensor-parallel-size 4 --data-parallel-size 4 --expert-parallel-size 4 \
--enable-dp-attention --enable-dp-lm-head \
--moe-a2a-backend megamoe --dsv4-attn-backend flashmla_mega \
--ep-num-redundant-experts 32 --ep-dispatch-algorithm dynamic --init-expert-location "$PLACEMENT" \
--speculative-algorithm DSPARK --speculative-dspark-block-size 5 \
--enable-decoder-swa-bounded-replay --swa-full-tokens-ratio 0.12 \
--chunked-prefill-size $((4 * B)) --max-prefill-tokens "$B" \
--max-running-requests 256 --mem-fraction-static "$MEM" \
--cuda-graph-max-bs-decode 1 --disable-decode-cuda-graph \
--enable-metrics --random-seed 733427905 --watchdog-timeout 3600 \
--skip-server-warmup --tokenizer-worker-num 4 \
$GRAPH \
--host 127.0.0.1 --port "$PORT"
"""Balanced placement with 32 redundant experts for DSv4.1-Flash prefill at EP4.
python make_placement.py --num-layers <config.num_hidden_layers> --out placement_r32_ep4.json
GPU r holds its own logical block [96r, 96r+96) plus copies of the first 8 experts of block r+1, so every
GPU holds 104 physical experts, as DeepInfer does with its default 32 extra experts. With SGLang's replica
choice under an a2a backend (a local copy wins; otherwise every copy stays a candidate and dynamic dispatch
splits evenly; expert_location.py _find_nearest_expert) and uniform routing over logical experts, every
GPU's expected load is 96 expert-units. The self-check below computes that load and fails otherwise.
"""
import argparse
import json
from fractions import Fraction
N_LOGICAL, EP, EXTRA = 384, 4, 32
PER_RANK, EXTRA_PER_RANK = N_LOGICAL // EP, EXTRA // EP
def layer_map():
phys = []
for r in range(EP):
nxt = (r + 1) % EP
phys += list(range(r * PER_RANK, (r + 1) * PER_RANK))
phys += [nxt * PER_RANK + j for j in range(EXTRA_PER_RANK)]
return phys
def expected_load(phys):
slots_per_gpu = len(phys) // EP
gpu_of = lambda p: p // slots_per_gpu
copies = {}
for p, e in enumerate(phys):
copies.setdefault(e, []).append(p)
load = [Fraction(0)] * EP
for src in range(EP): # each DP rank sends 1/EP of the tokens, uniform over logical experts
for e, ps in copies.items():
local = [p for p in ps if gpu_of(p) == src]
chosen = local[:1] if local else ps
for p in chosen:
load[gpu_of(p)] += Fraction(1, EP * len(chosen))
return load
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--num-layers", type=int, required=True)
ap.add_argument("--out", required=True)
args = ap.parse_args()
phys = layer_map()
assert len(phys) == N_LOGICAL + EXTRA and sorted(set(phys)) == list(range(N_LOGICAL))
load = expected_load(phys)
print("expected load per GPU (expert-units):", [float(x) for x in load])
assert all(x == PER_RANK for x in load), load
with open(args.out, "w") as f:
json.dump({"physical_to_logical_map": [phys] * args.num_layers}, f)
print(f"wrote {args.out}: {args.num_layers} layers x {len(phys)} physical experts")
if __name__ == "__main__":
main()
# Put this file's directory on PYTHONPATH for DeepInfer runs. It logs DeepEP's Engram QP config on every run and, when
# DI_ENGRAM_QPS is set, overrides the QP count (qp_depth and restrict_rd_atomic are kept). DeepInfer has no flag for it.
import builtins
import os
import sys
_qps = os.environ.get("DI_ENGRAM_QPS")
_orig_import = builtins.__import__
def _import(name, *args, **kwargs):
module = _orig_import(name, *args, **kwargs)
de = sys.modules.get("deep_ep")
if de is not None and hasattr(de, "EngramBuffer") and not getattr(de, "_di_qps_patched", False):
de._di_qps_patched = True
orig = de.EngramBuffer.get_theoretical_config
def patched(*a, **k):
q, d, r = orig(*a, **k)
new_q = int(_qps) if _qps else q
print(f"[qpcap] engram num_qps {q} -> {new_q}, qp_depth {d}, restrict_rd_atomic {r}", flush=True)
return new_q, d, r
de.EngramBuffer.get_theoretical_config = staticmethod(patched)
return module
builtins.__import__ = _import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment