Skip to content

perf(models): fuse the qkv and gate/up projections into single GEMVs - #206

Open
kunkunblueberry wants to merge 5 commits into
InferMatrixLab:mainfrom
kunkunblueberry:pr/fused-projections
Open

kunkunblueberry wants to merge 5 commits into
InferMatrixLab:mainfrom
kunkunblueberry:pr/fused-projections

Conversation

@kunkunblueberry

@kunkunblueberry kunkunblueberry commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Required human contributor answers

Recorded from the contributor''s instruction: the goal of this work is to bring vllm-rlt''s
operator performance to vLLM parity, for the developers who build and run on this engine,
because these operators are the performance-critical components. Figures cited below are the
measurements in this PR.

1. What outcome are you trying to achieve?

Match vLLM''s operator performance in vllm-rlt. Projections are the largest single item in the
decode step (measured at 6.33 ms/step of 13.86 ms on Ouro-1.4B), and at the batch sizes this
engine runs they stream weights without doing much arithmetic, so they are the place where
operator-level parity is decided.

2. What is the highest-leverage variable for that outcome?

Achieved DRAM bandwidth on the weight stream. The reference measurement is that a single
2048x2048 GEMV with distinct weights reaches 597 GB/s of a measured 1770 GB/s peak, and that
this is a property of how few bytes are in flight per launch, not of kernel quality: on the
same call torch.compile measured 3.4x slower.

3. How will this work move that variable rather than create busywork?

q/k/v read the same hidden row and gate/up likewise, so fusing them stacks the weight
matrices into one GEMV each and raises the bytes in flight per launch. Measured cold-L2, per
call: qkv 370 -> 1174 GB/s (3.17x) and gate_up 934 -> 1327 GB/s (1.42x), which is 15.286 ->
14.567 ms/step end to end. No new kernel, no build step, no numerical contract change:
gate_up is bitwise identical and qkv differs by at most 0.003%, inside one BF16 ULP.

4. Who is the customer or user, and what do they actually need?

Developers who deploy looped-transformer models on vllm-rlt and need per-step latency parity
with vLLM, and contributors benchmarking operator work who need the projection cost not to
dominate their measurements. They need it without changing model code, checkpoints, or the
shipped configuration.

PR necessity and bugfix evidence

A PR is needed: the projections are the largest measured item in the decode step, the change
is confined to one layer module plus the model wiring, and it needs no configuration or
checkpoint migration. This is a performance change, not a bugfix; the evidence is the
cold-L2 operator sweep and the end-to-end step timing in Test Result, reproducible with the
commands in Test Plan.

Purpose

Summary. Fuse the projections that share an input row - q/k/v into [6144, 2048] and
gate/up into [11264, 2048] - so each becomes one GEMV. Measured 3.17x (qkv) and 1.42x
(gate_up) at the operator level, 1.049x end to end, with gate_up bitwise identical.

Each projection in this engine is a GEMV that streams a weight matrix and computes almost
nothing, so it is bandwidth-bound, and every extra launch or pass over the same input row is
paid in full:

  • OuroAttention: q/k/v -> one [6144, 2048] matrix, then split the output.
  • OuroMLP: gate/up -> one [11264, 2048] matrix, then split.
  • o_proj and down_proj are deliberately not fused: they consume different inputs.

FusedWeight (vllm_rlt/layers/fused_projections.py) keeps the parameters where they are and
resolves the source tensors per call, caching the stacked matrix by (id, data_ptr, dtype, shape). That resolution order is the whole difficulty and cost three attempts, each of which
broke a real contract:

  • holding a strong reference to the owning module makes a cycle, and state_dict / _apply
    then recurse until they fail;
  • a weakref cannot be pickled, and the engine ships the model to the worker;
  • registering the cache as an nn.Parameter adds a state_dict key and breaks checkpoint
    round-trip.

As a plain object holding a plain tensor, none of those apply.

Test Plan

vllm-rlt Version / Commit: b29ffb5, branch pr/fused-projections, based on main at
ce200f0.

python -m ruff check vllm_rlt tests            # All checks passed
python -m ruff format --check vllm_rlt tests   # 148 files already formatted
OMP_NUM_THREADS=1 python -m pytest -q          # 1305 passed, 913 skipped (clean checkout, lyx)

GPU validation on 8x A100-SXM4-80GB (lyx):

pytest tests/test_fused_projections.py -q -p no:randomly   # 9 passed

The tests cover the three contracts above directly rather than only the arithmetic: checkpoint
round-trip (the cache must not appear in state_dict), pickling the model, and re-resolving
after a parameter''s storage changes.

Test Result

Operator-level, cold-L2, distinct weights per call (a single reused matrix is served from the
A100''s 40 MB L2 and overstates the bottleneck), device ms per call:

case M separate fused gain GB/s separate -> fused max rel diff
qkv [6144,2048] 1 0.0680 0.0215 3.17x 370 -> 1174 0.0019%
qkv 8 0.0787 0.0221 3.56x 321 -> 1144 0.0015%
qkv 32 0.0772 0.0215 3.60x 333 -> 1198 0.0015%
qkv 128 0.0681 0.0230 2.96x 401 -> 1185 0.0029%
gate_up [11264,2048] 1 0.0494 0.0348 1.42x 934 -> 1327 0.0000%
gate_up 8 0.0507 0.0362 1.40x 913 -> 1279 0.0030%
gate_up 32 0.0497 0.0353 1.41x 945 -> 1332 0.0028%
gate_up 128 0.0623 0.0465 1.34x 795 -> 1065 0.0000%

gate_up is bitwise identical to the two separate matmuls. qkv has a maximum relative
difference of 0.003%, well inside one BF16 ULP (0.78%): the stacked GEMM reassociates the
reduction. The tests assert the measured bound rather than bitwise parity for that reason.

Numerics were re-measured for this PR and are better than the first record. The experiment
note quotes 1.411x for both cases and a 0.41% qkv deviation; that was measured with a single
reused weight matrix (cache-resident) and a different reduction shape. The figures above are
the cold-L2, per-call numbers the bandwidth claim actually depends on.

End to end on the real checkpoint, CUDA graphs on, 128-token prompt / 64 decode tokens:
15.286 -> 14.567 ms/step (1.049x), consistent with 1.092x on the graphs-only operator A/B (the
difference is the non-graph host work around the replay, which does not shrink).

Where it stops, measured. The fused path now runs at 1174-1332 GB/s against a measured HBM
peak of 1770 GB/s, so roughly 1.3-1.5x remains and it is the small-matrix regime, not kernel
quality: the same sweep at o_proj width (8.4 MB) reaches only 597 GB/s. q/k/v must stay
fused for that reason, and per-call torch.compile on the same call measured 3.4x slower
(59 us vs 17.6 us), so a hand-written GEMV is not the answer.

Related work

Full experiment record: docs/experiments/V002-projection-fusion.md.

At the sizes this engine runs, each projection is a GEMV that streams a weight matrix
and computes almost nothing, so it is bandwidth-bound and each extra launch or pass over
the same input row is paid in full. q/k/v read the same hidden row, and gate/up likewise,
so three and two separate GEMVs became one each.

FusedWeight keeps the parameters where they are and resolves the source tensors per call,
building the stacked matrix once per (id, data_ptr, dtype, shape). That resolution order
matters and cost three attempts:
- holding a strong reference to the owner module makes a cycle, and state_dict/_apply then
  recurse forever;
- a weakref cannot be pickled, and the engine ships the model to the worker;
- registering the cache as an nn.Parameter adds a state_dict key and breaks checkpoint
  round-trip. As a plain object holding a plain tensor, none of those apply.

Measured operator-level at M=1..8 (Ouro-1.4B shapes): qkv [6144, 2048] and gate_up
[11264, 2048] each 1.411x faster than the separate GEMVs. gate_up is bitwise identical to
the separate matmuls; qkv has a maximum relative difference of 0.41% against one BF16 ULP
of 0.78%, i.e. the stacked GEMM reassociates the reduction but stays inside a single ulp.

End to end on the real checkpoint with CUDA graphs on, 15.286 ms/step -> 14.567 ms/step
(1.049x), and 1.092x for the operator-level graphs-only A/B.

Related work: InferMatrixLab#167 (draft) and InferMatrixLab#146 (closed) both cover elementwise kernels, not
projections, so nothing in flight overlaps this change.
@kunkunblueberry
kunkunblueberry marked this pull request as ready for review November 22, 2026 16:36
Signed-off-by: kunkunblueberry <kunkunblueberry@gmail.com>
@LyxWxj

LyxWxj commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The PR stacks the projection weights vertically. For Ouro-1.4B, it builds qkv as [6144, 2048] and gate/up as [11264, 2048]. The main design question is how those fused weights are created and owned.

  1. Passing tensors directly to FusedWeight

FusedWeight could accept the source tensors directly. The current implementation stores the owning module and resolves its parameters on each call so it can notice when parameter objects have been replaced.
That matters for the current loader: it first constructs the model on the meta device and then replaces its parameters with checkpoint tensors. If FusedWeight retained the original tensor references during construction, those references could become stale.
Passing the current tensors on each call would avoid the reference back to the owning module. However, it would still retain both the original parameters and the concatenated cache.
Calling torch.cat on every forward pass would avoid a persistent cache but would repeatedly copy the weights during inference.
A better approach would be to create the fused weight as the model’s only physical copy and load each checkpoint tensor directly into its corresponding slice.

  1. Computing W_fused @ X.T

This is mathematically equivalent to the current linear operation:

  • Current approach
    Y = X @ W_fused.T # [N, 3H]

  • Proposed approach
    Z = W_fused @ X.T # [3H, N]

Splitting Z along its first dimension can produce contiguous [H, N] blocks. If downstream operators require the usual [N, H] layout, however, transposing those blocks produces non-contiguous views again.

For example, with two token rows and a projection width of three:

Result Shape Stride Contiguous?
Slice from X @ W.T [2, 3] (6, 1) No; each row is contiguous
Slice from W @ X.T [3, 2] (2, 1) Yes
Transpose of that slice [2, 3] (1, 2) No

The feature-major layout is a valid option, but RoPE, KV writes, attention and the MLP’s down projection would need to consume it correctly. Its performance should be measured across the full execution path. Different GEMM choices can also produce small BF16 numerical differences.

At the reviewed PR head, aabd446, the native silu_and_mul kernel has been updated to accept the original row-strided [N, D] slices. My earlier finding that it would reject those slices applied to the older head; I have not run the updated kernel on a GPU.

  1. How vLLM implements this

vLLM's implementation uses:

• QKVParallelLinear for one fused QKV weight.
• MergedColumnParallelLinear for one fused gate/up weight.
• A checkpoint mapping that sends q_proj, k_proj and v_proj into the corresponding slices of the fused parameter, and does the same for gate_proj and up_proj.

For the unquantized, single-GPU case, the loader allocates the fused parameter and copies each checkpoint weight into its target slice. It therefore does not need a second persistent copy of the original projection weights.

For the MLP, vLLM passes the complete [N, 2D] output to SiluAndMul. The CUDA kernel reads the gate and up halves using offsets within each row and writes a [N, D] output.
I would suggest following that model here: load directly into fused parameters, retain the existing token-major execution layout, and use the updated stride-aware activation kernel.
The loader would need to map the original checkpoint keys to fused slices; if the original state_dict export format must remain unchanged, that would also need an explicit mapping or hook. This would remove the approximately 1.59 GiB of persistent duplicate BF16 weights for Ouro-1.4B, along with the cache ownership and invalidation issues.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants