Skip to content

[Fix] DSv4.1: Size the encoder-replay SWA pool by the DSpark draft's stages, and keep more prefix tails - #43502

Merged
Oasis-Git merged 7 commits into
sgl-project:mainfrom
YAMY1234:dsv41-dspark-swa-pricing
Oct 15, 2026
Merged

Oasis-Git merged 7 commits into
sgl-project:mainfrom
YAMY1234:dsv41-dspark-swa-pricing

Conversation

@YAMY1234

@YAMY1234 YAMY1234 commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

python3 -m sglang.launch_server --model-path deepseek-ai/DeepSeek-V4.1-Flash --trust-remote-code \
  --tp 4 --ep-size 4 --mem-fraction-static 0.8 --max-running-requests 64 --chunked-prefill-size 8192 \
  --speculative-algorithm DSPARK --speculative-dspark-block-size 5 \
  --enable-encoder-swa-bounded-replay --enable-decoder-swa-bounded-replay
# startup, TP0: DSV4 SWA sizing: ... prefix_tails=256 / DSV4 memory calculation: ... swa_fixed=4.55 GB ... full_token=60815360

The pool is priced at the wrong layer count.

  • Under encoder SWA bounded replay the target keeps its window per request, so the paged SWA pool holds only the DSpark draft's KV.
  • DSV4PoolConfigurator prices that pool at paged_draft_layers = dflash_draft_num_layers, the draft config's num_hidden_layers. The DSpark head bundled with DeepSeek-V4.1 inherits the target's 40.
  • DeepseekV4ForCausalLMDSpark builds len(dspark_target_layer_ids) = 3 stages. The configurator therefore reserves about 13× the bytes the draft allocates and takes them out of the full KV pool: 3.8 GB per GPU at the default, 33.5 GB at --swa-prefix-tails 4096. That memory stays free after graph capture.

256 prefix tails are too few for multi-turn agentic traffic.

  • A cached prefix is reusable only while its last window still has paged SWA slots (the radix match stops at a tombstoned window).
  • On a one-hour agentic-coding replay at 16 concurrent sessions, conversations idle for 3–5 minutes lose their tail while their full KV is still on the GPU. They re-prefill 130K–755K tokens, which blocks everything queued behind them for 2–13 s.
  • 3.5% of requests wait more than 1 s. One request with a 104,704-token cached prefix and 311 new tokens waited 11.6 s.

Modifications

  • Record the DeepSeek-V4 DSpark draft's stage count (SpecAuxHiddenStateConfig.dspark_num_stages; the dense DSpark draft builds num_hidden_layers stages, so it is left unset there) and price the encoder-replay paged SWA by it, falling back to dflash_draft_num_layers.
  • Under encoder replay with DSpark, default --swa-prefix-tails to 4 × max_running_requests × (num_layers_total // paged_draft_layers).
    • This keeps the byte budget of the non-replay default, which prices all target layers, and spends it on cheaper tails: 3,328 tails, ≈2.3 GB per GPU, at 64 running requests.
    • An explicit flag still wins.
  • Tests:
    • test_spec_aux_hidden_state_resolver.py: a 40-layer draft config with three dspark_target_layer_ids resolves to 3 stages for the DeepSeek-V4 draft and leaves the field unset for a dense DSpark draft;
    • test_pool_configurator.py: the DSpark budget test now uses a 40-layer draft config with 3 stages; the default tails rule and its override.

Accuracy Tests

Only pool sizes change. GSM8K first 50 test questions, 5-shot, greedy, launch command above; each arm runs the 50 questions cold and then again as prefix hits:

GSM8K-50 main this PR
cold 49/50 50/50
hit 49/50 49/50
GSM8K requests (our client)
  • Data: test.jsonl (first 50) and train.jsonl from openai/grade-school-math.

  • Prompt: the first 5 train examples as Question: …\nAnswer: …\n\n, then Question: <question>\nSolve the problem. End your answer with #### followed by the numeric answer., sent as one user message rendered by encoding_dsv41.encode_messages(messages, thinking_mode="chat") and tokenized without special tokens.

  • One request per question, 50 in flight:

    POST /generate {"input_ids": <prompt ids>, "cache_salt": "L1-v1-gsm8k-<index>", "sampling_params": {"temperature": 0, "max_new_tokens": 1024}, "stream": false, "return_logprob": false}
    
  • POST /flush_cache, then the cold pass, then the same 50 requests again as the hit pass. Every cold response reported meta_info.cached_tokens == 0, and every hit response cached_tokens >= (len(input_ids) - 1) // 256 * 256 (50/50 in both arms).

  • Score: the last number in the output (commas removed) equals the last number in the reference answer.

Unit tests on CPU: test_pool_configurator.py 56 passed, test_spec_aux_hidden_state_resolver.py 4 passed. With these tests on main's source, the 4 DSpark tests fail. Results below were measured at c5130ca00ba; the later review commits only restrict the stage count to the DeepSeek-V4 draft, and this checkpoint still resolves to 3 stages.

Speed Tests and Profiling

Same node, 4×GB300; each arm uses its default prefix tails. The static benchmark below adds --enable-cache-report --enable-metrics --tokenizer-backend fastokens --served-model-name deepseek-ai/DeepSeek-V4.1-Flash --reasoning-parser auto --tool-call-parser auto to the launch command above; the startup values are the same with and without them.

startup (TP0) main 3831e7e0918 this PR c5130ca00ba
default prefix tails 256 3,328
swa_fixed 4.55 GB 2.66 GB
full KV pool tokens 60,815,360 62,058,752

Static prefix reuse: N distinct 16K-token prefixes at concurrency 16, one output token. Pass 1 caches them; pass 2 revisits them in reverse order with 256 new prompt tokens. All prefixes fit in the full KV pool in both arms.

python3 static_client.py --url http://127.0.0.1:<port> --out <dir>   # same command for main and this PR

It flushes the cache before each population, then runs N=100, N=200 and N=1000 (this PR's job reached its time limit in N=1000 pass 2, so N=1000 is not reported). Prefix hits are pass-2 requests with cached_tokens >= 16384; uncached prompt tokens are prompt minus cached tokens; TTFT is request start to the first streamed choice, p50 linearly interpolated.

static_client.py
import argparse, concurrent.futures, json, math, random, statistics, time, urllib.request
from pathlib import Path

p=argparse.ArgumentParser(); p.add_argument('--url',required=True); p.add_argument('--out',required=True); a=p.parse_args()
out=Path(a.out); out.mkdir(parents=True,exist_ok=True)

def api(path, body=None):
    req=urllib.request.Request(a.url+path,data=None if body is None else json.dumps(body).encode(),headers={'Content-Type':'application/json'})
    with urllib.request.urlopen(req,timeout=300) as r:
        raw=r.read()
        if path.startswith('/flush_cache'):
            assert raw.startswith(b'Cache flushed.'),raw
            return raw.decode()
        return json.loads(raw)

def request(i, n, stage):
    rng=random.Random(42+i)
    ids=[100+i]+[rng.randrange(2000,10000) for _ in range(16383)]
    if stage==2: ids += [rng.randrange(2000,10000) for _ in range(256)]
    body=json.dumps({'model':'deepseek-ai/DeepSeek-V4.1-Flash','prompt':ids,'max_tokens':1,'temperature':0,'ignore_eos':True,'stream':True,'stream_options':{'include_usage':True},'return_token_ids':True},separators=(',',':')).encode()
    req=urllib.request.Request(a.url+'/v1/completions',data=body,headers={'Content-Type':'application/json'})
    start=time.perf_counter(); first=None; usage=None; token_events=0
    with urllib.request.urlopen(req,timeout=300) as r:
        for raw in r:
            if not raw.startswith(b'data:'): continue
            payload=raw[5:].strip()
            if payload==b'[DONE]': break
            d=json.loads(payload)
            if d.get('error'): raise RuntimeError(d['error'])
            if d.get('choices'):
                if first is None: first=time.perf_counter()
                token_events+=1
            if d.get('usage'): usage=d['usage']
    assert first is not None and usage is not None,(i,usage)
    assert usage['prompt_tokens']==len(ids),(i,usage,len(ids))
    assert usage['completion_tokens']==1,(i,usage)
    # Upstream UsageProcessor deliberately omits prompt_tokens_details when cached_tokens==0.
    details=usage.get('prompt_tokens_details')
    cached=0 if details is None else details['cached_tokens']
    assert 0<=cached<=len(ids),(i,cached,len(ids))
    return {'population':n,'pass':stage,'prefix_id':i,'ttft_ms':1000*(first-start),'elapsed_ms':1000*(time.perf_counter()-start),'prompt_tokens':len(ids),'cached_tokens':cached,'uncached_tokens':len(ids)-cached,'usage':usage,'stream_events_with_choices':token_events}

def percentile(values, p):
    v=sorted(values); x=(len(v)-1)*p; i=int(x); return v[i]+(v[min(i+1,len(v)-1)]-v[i])*(x-i)

def run(n):
    api('/flush_cache?timeout=30',{})
    result={'N':n,'prefix_tokens':16384,'extension_tokens':256,'concurrency':16,'generation_tokens':1,'seed':42,'pass1_order':'ascending prefix ID','pass2_order':'descending prefix ID, newest first','timing':'HTTP request start after client prompt construction to first streamed choices event; server emits this on first generated token','passes':{}}
    for stage in (1,2):
        order=list(range(n)) if stage==1 else list(reversed(range(n)))
        started=time.time(); rows=[]
        with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
            futures=[pool.submit(request,i,n,stage) for i in order]
            with (out/f'n{n}-pass{stage}.jsonl').open('w') as f:
                for j,future in enumerate(concurrent.futures.as_completed(futures),1):
                    row=future.result(); rows.append(row); f.write(json.dumps(row)+'\n')
                    if j%100==0: print(f'STATIC_PROGRESS N={n} pass={stage} completed={j}/{n}',flush=True)
        elapsed=time.time()-started; t=[r['ttft_ms'] for r in rows]; prompt=sum(r['prompt_tokens'] for r in rows); cached=sum(r['cached_tokens'] for r in rows)
        result['passes'][str(stage)]={'requests':len(rows),'errors':0,'elapsed_seconds':elapsed,'prompt_tokens':prompt,'cached_tokens':cached,'uncached_tokens':prompt-cached,'usage_cache_hit_rate':cached/prompt,'requests_with_cached_prefix':sum(r['cached_tokens']>0 for r in rows),'requests_with_full_16384_prefix':sum(r['cached_tokens']>=16384 for r in rows),'ttft_ms':{'mean':statistics.mean(t),'p50':percentile(t,.5),'p90':percentile(t,.9),'max':max(t)}}
        print('STATIC_PASS_DONE '+json.dumps(result['passes'][str(stage)]),flush=True)
        (out/f'n{n}-summary.json').write_text(json.dumps(result,indent=2)+'\n')
    return result

summary={'protocol':'independent deterministic raw token-ID prefixes via OpenAI streaming completions, one output token, max_workers16; identical order per arm; flush between populations','populations':{}}
summary['populations']['100']=run(100)
summary['populations']['200']=run(200)
summary['populations']['1000']=run(1000)
(out/'static-summary.json').write_text(json.dumps(summary,indent=2)+'\n')
print('STATIC_DONE',flush=True)
pass 2 main this PR
N=100: prefix hits 21/100 100/100
N=100: uncached prompt tokens 1,319,936 25,600
N=100: TTFT p50 (ms) 7,728 3,982
N=200: prefix hits 21/200 153/200
N=200: uncached prompt tokens 2,983,936 821,248 (−72%)
N=200: TTFT p50 (ms) 7,944 4,028

At N=200, --swa-prefix-tails 8192 reaches 200/200 (same client, N=200 only). The remaining misses at the default come from finished requests keeping their whole last chunk of SWA (~8.7K slots per 16K prefix) instead of one window; that retention is a separate issue and is not changed here.

Checklist

  • Format your code according to the code style guidelines.
  • Add unit tests.
  • Update documentation as needed (the --swa-prefix-tails help text is updated; no other docs).
  • Provide accuracy and speed benchmark results.

CI States

Latest PR Test (Base): ⏳ Run #38682609361
Latest PR Test (Extra): ❌ Run #38682609286
Latest PR Test (AMD ROCm 10): ⏳ Run #38682609271

Under --enable-encoder-swa-bounded-replay with DSpark, the paged SWA pool only
holds the draft's KV. The DSpark head bundled in the DeepSeek-V4.1 checkpoint
inherits the target's num_hidden_layers (40), so paged_draft_layers priced each
paged SWA token at 40 layers while DeepseekV4DSpark builds
len(dspark_target_layer_ids) = 3 stages. The configurator reserved ~13x the
bytes the draft pool allocates and shrank the full KV pool by the difference:
about 3.8 GiB per GPU at the default 256 prefix tails and 30 GiB at 4096.

Record the DSpark stage count and price the paged SWA by it.
…r encoder replay

Under --enable-encoder-swa-bounded-replay with DSpark, the paged SWA pool only
stores the draft layers, so one cached prefix tail costs
num_layers_total / paged_draft_layers times less than without replay. Keep the
non-replay default's byte budget and give it proportionally more tails.

The 4 x max_running_requests default leaves room for 256 tails at
max_running_requests=64; on AgentX traces idle conversations lose their tail
within minutes, the radix match stops at the shared system prompt, and
100K-750K-token prefixes are re-prefilled while the full KV is still resident.
@YAMY1234
YAMY1234 marked this pull request as ready for review October 12, 2026 17:23

@nvpohanh nvpohanh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[by Claude Code] Severity: style | Confidence: High

Issue

The accuracy and speed sections give the server launch command, but not the commands that produced the results, so others cannot rerun them. The description does not include:

  • the GSM8K command: the eval script, the 5-shot and 50-question settings, and how the second run was sent so that it hit the prefix cache;
  • the script or command for the static prefix-reuse benchmark (N 16K-token prefixes at concurrency 16, pass 1, then pass 2 in reverse order with 256 new tokens) that reports prefix hits, uncached prompt tokens, and TTFT p50.

Fix

Add both commands, or link the scripts, for the main and PR runs.

The dense DSpark draft builds num_hidden_layers stages, so len(target_layer_ids)
is the stage count only for DeepseekV4ForCausalLMDSpark. Fix the class name in
the field comment and cover both cases in the resolver test.
test_dsv4_paged_dspark_budget_reserves_window_and_draft_layers already checks
the 3-stage price; the stage count itself is now tested in the resolver test.
@YAMY1234

Copy link
Copy Markdown
Collaborator Author

Added both to the description. GSM8K: the exact requests our client sends (5-shot prompt, /generate body, flush → cold pass → same requests as the hit pass, with the cached-token checks) and the scorer. Static prefix reuse: the client command, metric definitions, the extra server flags it used, and the full client script in a collapsed block; the same command was run against main and this PR.

@YAMY1234

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Oct 13, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] I've started babysitting the NVIDIA CI of this PR. I'll check it every 30 minutes until all NV pipelines pass. If a relevant job fails, I may rerun it, merge the latest main into this branch, push a small test-only fix, or post a note here.

Anyone can stop me at any time: just post a comment asking me to stop (for example, stop babysitting). I'll stop at my next check, within 30 minutes, and take no further action on this PR.

@YAMY1234 YAMY1234 changed the title [DSv4.1] Size the encoder-replay SWA pool by the DSpark draft's stages, and keep more prefix tails [Fix] DSv4.1: Size the encoder-replay SWA pool by the DSpark draft's stages, and keep more prefix tails Oct 14, 2026
@nvpohanh

Copy link
Copy Markdown
Collaborator

[by Claude Code] The relevant CI failure (https://github.com/sgl-project/sglang/actions/runs/38518506289/job/115709633895) is not caused by this PR. It is a known breakage on main that #44235 will fix. CI for this PR is blocked until that PR merges.

@Oasis-Git

Copy link
Copy Markdown
Collaborator

[Codex]: Running the requested targeted CI at c763dae: the pool configurator and auxiliary hidden-state resolver unit tests, plus DeepSeek-V4.1-Flash DSPARK TP4+EP4 end-to-end GSM8K and MMLU accuracy tests on 4 GB300 GPUs. The existing E2E class does not enable encoder SWA bounded replay, so it provides DSPARK runtime/accuracy regression coverage; replay pool sizing is covered by the selected unit tests.

@Oasis-Git

Copy link
Copy Markdown
Collaborator

/rerun-test test/registered/unit/model_executor/test_pool_configurator.py test/registered/unit/model_executor/test_spec_aux_hidden_state_resolver.py test/registered/e2e/models/test_deepseek_v41_flash_gb300.py::TestDSV41FlashTP4EP4DSpark

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Rebase Required Before Re-run

A major update has landed on main. Your PR is diverged relative to required base commit b67785153a55.

Re-run was not dispatched. What to do:

  • Rebase your branch onto the latest main and push again
  • Follow issue #21065 for context
  • CI-fix PRs may request the bypass-maintenance label to skip this check

@Oasis-Git

Copy link
Copy Markdown
Collaborator

[Codex]: Retrying the requested targeted CI after the branch update to 0de0506, which includes required baseline b677851. Scope remains the pool configurator and auxiliary hidden-state resolver unit tests, plus TestDSV41FlashTP4EP4DSpark (GSM8K and MMLU on 4 GB300 GPUs). This existing E2E class does not enable encoder SWA bounded replay.

@Oasis-Git

Copy link
Copy Markdown
Collaborator

/rerun-test test/registered/unit/model_executor/test_pool_configurator.py test/registered/unit/model_executor/test_spec_aux_hidden_state_resolver.py test/registered/e2e/models/test_deepseek_v41_flash_gb300.py::TestDSV41FlashTP4EP4DSpark

@github-actions

github-actions Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🚀 ubuntu-latest (2 tests): ✅ View workflow run

cd test/ && python3 registered/unit/model_executor/test_pool_configurator.py
cd test/ && python3 registered/unit/model_executor/test_spec_aux_hidden_state_resolver.py

🚀 4-gpu-gb300 (1 test): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_deepseek_v41_flash_gb300.py TestDSV41FlashTP4EP4DSpark

@Oasis-Git

Copy link
Copy Markdown
Collaborator

[Codex]: Targeted CI passed at current head 0de0506.

  • Pool configurator and auxiliary hidden-state resolver unit tests: passed.
  • DeepSeek-V4.1-Flash DSPARK TP4+EP4 E2E (GSM8K and MMLU, 4 GB300 GPUs): passed.

This is targeted coverage, not full CI. The selected E2E class does not enable encoder SWA bounded replay.

@Oasis-Git
Oasis-Git merged commit 1d809bb into sgl-project:main Oct 15, 2026
98 of 139 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants