Skip to content

perf(dsv4): replace the skinny fp32 GEMMs in hc_pre with a split-K GEMV - #967

Open
zhangnju wants to merge 2 commits into
FlashML-org:mainfrom
zhangnju:perf/dsv4-skinny-gemv
Open

zhangnju wants to merge 2 commits into
FlashML-org:mainfrom
zhangnju:perf/dsv4-skinny-gemv

Conversation

@zhangnju

@zhangnju zhangnju commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

During decode, DeepSeek-V4 runs two skinny fp32 GEMMs per layer (hc_pre, plus hc_head once): [rows, 16384] x [24, 16384], 86 calls per step. Here rows is the number of tokens in the step, i.e. 1-16 concurrent requests. The weight is only 1.5 MB, but BLAS has no good kernel for this shape:

rows cuBLAS (RTX 5090) hipBLAS (R9700) hc_mix (5090 / R9700)
1 8.5 us 377 us 3.4 / 5.9 us
8 71.7 us 387 us 5.5 / 8.6 us
16 71.9 us 397 us 8.5 / 13.7 us

(per call, CUDA-graph steady state; full 1-64 row sweep is easy to reproduce with the tests' shapes)

Change

  • hc.py: new split-K GEMV hc_mix (a partial kernel over K chunks, then a fixed-order reduce, so it is deterministic). model.py: hc_pre and hc_head call it through _mix when rows <= HC_MIX_MAX_ROWS (32 on CUDA, 64 on ROCm, where BLAS stays slow longer). Larger row counts (prefill) keep the original F.linear path.
  • bf16_linear.py: bf16_linear_fp32 had a GEMV only for M=1 and fell back to F.linear for M>1. It now handles M <= 16 in the same kernel (each program loops over the rows, so the weight tile comes from cache). Callers: compressor wkv/wgate and the V4 / V4.1 MoE gate scores.

No fp8, attention or comm code is touched; no new env vars.

Results

Aggregate decode tok/s, AIME 2024 prompts, greedy, <= 600 tokens/request, 2 launches each, 0 CPU-thread warnings.

setup C=1 C=8
RTX 5090, TP1, main -> PR 22.3 -> 22.3 46.4 -> 50.7 (+9%)
4x R9700, TP4, #952 -> PR (--disable-pynccl) 7.2 -> 15.0 (2.1x) 32.0 -> 56.7 (1.8x)

Setup: deepseek-ai/DeepSeek-V4-Flash, --moe-strategy hybrid --moe-hybrid-max-fetch 1, Triton 3.8.0; 5090: CUDA 13.2, --moe-cache-mem 12GiB, main 81c162b; R9700 (gfx1201): torch 2.14.0+rocm10.1.0, --moe-cache-mem 16GiB. main has no DSV4 TP, so the R9700 run is on top of #952; with #952's default PyNCCL not buildable on ROCm, it uses --disable-pynccl. The R9700 runs used a local --distributed-timeout flag (TP4 ranks finish loading >60 s apart); it is not part of this PR.

Correctness

The fp32 accumulation order of two small GEMMs changes, so greedy outputs are not bit-identical to main (gate top-k can flip on near-ties). On 40 addition prompts the answers differ from main on 11/40 (sequential) and 3-9/40 (8 concurrent) on the 5090. That is the same size as the difference main has against itself between batch sizes (11-16/40). Accuracy 24 vs 27 sequential (sign test p ~ 0.26), no garbled output. Max abs error vs an fp32 reference is 1e-6 to 2e-5.

Unit tests (new test_dsv4_hc_mix.py, test_dsv4_bf16_linear.py, plus the unchanged fp8 / sparse-attn / e4m3 test files): 71 passed, 1 skipped on the 5090. On the R9700, 69 passed and 3 @pytest.mark.slow tests in test_e4m3_compat.py fail, identically on unmodified main.

Limitations

  • No formal quality eval; the probe above is small and noisy.
  • HC_MIX_MAX_ROWS = 32 on CUDA comes from the microbenchmark only (no end-to-end test above CUDA graph batch size 8).
  • The V4.1 MoE gate uses bf16_linear_fp32 too but was not tested on a V4.1 checkpoint; only Triton 3.8.0 was tested (pyproject.toml allows >=3.6,<3.9).

Reproduce

python -m freetoken.server.launch --model-path /models/DeepSeek-V4-Flash --cuda-graph-max-bs 8 \
  --max-running-requests 8 --expert-load parallel --text-model-only --tensor-parallel-size 1 --gpu 0 \
  --moe-cache-mem 12GiB --moe-strategy hybrid --moe-hybrid-max-fetch 1

For R9700 use --tensor-parallel-size 4 --gpu 0,1,2,3 --moe-cache-mem 16GiB --disable-pynccl. Client (same on both platforms; reads the 30 AIME 2024 problem strings from /tmp/aime.json; usage aime_client.py PORT C NPROB MAXTOK):

aime_client.py
# Paper-style AIME load: C workers take AIME problems in a fixed order (same set and order for every config), thinking on,
# streaming, at most MAXTOK output tokens each. Prints one JSON line: per-request mean decode tok/s (paper's metric),
# aggregate decode tok/s (all output tokens / wall time from the first token to the last), mean TTFT.
# usage: aime_client.py PORT C NPROB MAXTOK [OFFSET]
import json, sys, threading, time, urllib.request

port, conc, nprob, maxtok = (int(a) for a in sys.argv[1:5])
offset = int(sys.argv[5]) if len(sys.argv) > 5 else 0
probs = json.load(open("/tmp/aime.json"))
todo = [probs[(offset + i) % len(probs)] for i in range(nprob)]
lock = threading.Lock()
res = []


def one(problem):
    body = json.dumps({"model": "x", "messages": [{"role": "user", "content": problem + "\nPut the final answer in \\boxed{}."}],
                       "max_tokens": maxtok, "temperature": 0, "stream": True,
                       "stream_options": {"include_usage": True}}).encode()
    req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", body, {"Content-Type": "application/json"})
    t0 = time.time(); tf = None; n = 0; last = t0
    with urllib.request.urlopen(req, timeout=3600) as r:
        for line in r:
            line = line.decode().strip()
            if not line.startswith("data:") or line.endswith("[DONE]"):
                continue
            j = json.loads(line[5:])
            ch = j.get("choices") or []
            if ch and (ch[0]["delta"].get("content") or ch[0]["delta"].get("reasoning_content")):
                now = time.time()
                if tf is None:
                    tf = now
                n += 1; last = now
            if j.get("usage"):
                n = j["usage"]["completion_tokens"]
    return {"t0": t0, "ttft": (tf or last) - t0, "tokens": n, "first": tf or last, "last": last}


def worker():
    while True:
        with lock:
            if not todo:
                return
            p = todo.pop(0)
        r = one(p)
        with lock:
            res.append(r)


ts = [threading.Thread(target=worker) for _ in range(conc)]
[t.start() for t in ts]; [t.join() for t in ts]
per_req = [r["tokens"] / (r["last"] - r["first"]) for r in res if r["last"] > r["first"]]
span = max(r["last"] for r in res) - min(r["first"] for r in res)
print(json.dumps({"c": conc, "n": len(res), "per_req_decode": round(sum(per_req) / len(per_req), 2),
                  "aggregate_decode": round(sum(r["tokens"] for r in res) / span, 2),
                  "mean_ttft": round(sum(r["ttft"] for r in res) / len(res), 2),
                  "mean_tokens": round(sum(r["tokens"] for r in res) / len(res))}), flush=True)

@github-actions github-actions Bot added the perf label Nov 30, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant