Skip to content

fix: attention_unfused alpha missing norm_factor squaring - #8666

Closed
delock wants to merge 2 commits into
masterfrom
fix/pt-binding-alpha-squaring
Closed

delock wants to merge 2 commits into
masterfrom
fix/pt-binding-alpha-squaring

Conversation

@delock

@delock delock commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Summary

attention_unfused in pt_binding.cpp uses norm_factor directly as the QK^T scale, but ds_attention.py passes 1/sqrt(sqrt(head_dim)) which is head_dim^(-1/4). The correct softmax scale is head_dim^(-1/2), requiring the value to be squared.

The bug

// attention_unfused (line ~197):
float alpha = norm_factor;  // head_dim^(-1/4) — WRONG

// Fallback binding in the same file (line ~378):
float alpha = norm_factor * norm_factor;  // head_dim^(-1/2) — CORRECT

Same file, two bindings — one squares, one doesn't. The one that doesn't is a bug.

How norm_factor is computed (ds_attention.py)

self.norm_factor = math.sqrt(head_dim)        # sqrt(64) = 8
self.norm_factor = math.sqrt(self.norm_factor) # sqrt(8) = 2.83 = head_dim^(1/4)
# Passed to binding as: 1 / norm_factor = head_dim^(-1/4)

The binding is expected to square it back to head_dim^(-1/2).

Impact

For head_dim=64: correct scale is 1/8, buggy scale is 1/2.83 — a 2.8× difference in QK^T score magnitude, causing significantly different softmax distributions.

Test plan

  • Verify attention output matches F.scaled_dot_product_attention reference
  • Test with multiple head_dim values (64, 128, 256)

ds_attention passes 1/sqrt(sqrt(head_dim)); attention_unfused used it
directly as QK^T scale (head_dim^(-1/4)). The correct softmax scale is
head_dim^(-1/2), requiring alpha = norm_factor * norm_factor. The
fallback binding in the same file (line 378) already does this —
this fix aligns attention_unfused with it.

Signed-off-by: Guokai Ma <[email protected]>
@delock
delock requested a review from tjruwase as a code owner September 25, 2026 14:59

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ceef30ff39

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

float alpha = norm_factor;
// ds_attention passes 1/sqrt(sqrt(head_dim)); square it back to the
// 1/sqrt(head_dim) softmax scale, matching the fallback binding below.
float alpha = norm_factor * norm_factor;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add an integration test for the changed attention scale

This changes an inference-level attention result but adds no test coverage (the commit's stated test plan is still unchecked). Add and execute a real-device integration test that compares this path's output against an independent attention reference, including the relevant head dimensions, before merging.

AGENTS.md reference: AGENTS.md:L36-L37

Useful? React with 👍 / 👎.

float alpha = norm_factor;
// ds_attention passes 1/sqrt(sqrt(head_dim)); square it back to the
// 1/sqrt(head_dim) softmax scale, matching the fallback binding below.
float alpha = norm_factor * norm_factor;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the required Signed-off-by trailer

Commit 10ac5597212375b3a0c04a9bad296eb378c65b98 is a non-merge commit, and git log -1 --format='%b' confirms that its message contains no Signed-off-by: trailer. Add the required DCO sign-off before merging.

AGENTS.md reference: AGENTS.md:L8-L9

Useful? React with 👍 / 👎.

@delock delock added merge-train PRs on merge-train (without additional commits) would be cherrypicked in an aggregate commit and removed merge-train PRs on merge-train (without additional commits) would be cherrypicked in an aggregate commit labels Sep 29, 2026
@hwchen2017
hwchen2017 requested a balanced review from Copilot September 29, 2026 04:14

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

The corrected C++ path lacks regression coverage, and its new comment inaccurately describes non-default configurations.

Review effort: Balanced
Findings: 1 Medium severity · 1 Low severity

Open (2)
What changed in this PR

Corrects attention scaling by squaring norm_factor before the unfused QKᵀ operation.

Changes:

  • Applies the expected softmax scaling.
  • Documents alignment with the other attention binding.
File Description
csrc/​transformer/​inference/​csrc/​pt_binding.cpp Corrects unfused attention scaling.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

float alpha = norm_factor;
// ds_attention passes 1/sqrt(sqrt(head_dim)); square it back to the
// 1/sqrt(head_dim) softmax scale, matching the fallback binding below.
float alpha = norm_factor * norm_factor;
Comment on lines +197 to +198
// ds_attention passes 1/sqrt(sqrt(head_dim)); square it back to the
// 1/sqrt(head_dim) softmax scale, matching the fallback binding below.
@delock
delock requested review from loadams and tohtana as code owners October 3, 2026 16:22
Add test_softmax_context_int8 comparing the legacy int8 attention binding
against an independently scaled reference softmax(q@k^T * norm_factor^2) @ v
for head_dim 64/128/256 and seq_len 16/128, and clarify that norm_factor is
the caller-provided pre-square scale so the comment stays accurate under
non-default configurations (use_mup, inverse-layer scaling).

Verified on RTX 4080 with torch 2.12.1+cu130: the test fails on the pre-fix
binding and passes after the alpha squaring fix.

Signed-off-by: Guokai Ma <[email protected]>
@delock
delock force-pushed the fix/pt-binding-alpha-squaring branch from d0dc79f to 82ecffe Compare October 4, 2026 03:24
@delock

delock commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

close as this does not block #8381 works

@delock delock closed this Oct 6, 2026
@tohtana tohtana added needs-gpu-test GPU testing is recommended to validate the changes in this PR. and removed needs-gpu-test GPU testing is recommended to validate the changes in this PR. labels Nov 10, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 19, 2026
…y decode (deepspeedai#8602)

## Summary

Adds a **segment-KI framework** that accelerates greedy decode in the
hybrid-engine rollout by injecting native CUDA kernels into comm-free
segments of the model, plus a **C++ decode loop** that runs the full
autoregressive generation with near-zero per-step Python overhead.

### Segment detection: structural, not per-model

Detection is attribute-name based: any HF family whose gated MLP uses
`gate_proj/up_proj/down_proj` (LLaMA, Qwen, Mistral, DeepSeek, Gemma...)
or whose GatedDeltaNet block uses the `in_proj_{qkv,z,b,a}` set is
picked up without per-model code. Projections carrying TP collectives
are never fused (a defensive `isinstance` check against the Allreduce
layer hierarchy).

### Co-location by construction

Both GLU (dual-weight GEMV) and GDN (quad-weight GEMV) replacements read
the original weight Parameters directly through `autograd.Function`s
with exact backward, so training and generation share one forward path:
**zero weight copies, no inject/eject switching between rollout and
training**. Verified end-to-end by an integration test (below): generate
→ train one step → generate, output changes, no sync calls.

## Components

| File | Role |
|---|---|
| `csrc/module_inject/fused_glu.cu` | dual/quad-weight GEMV (MLP / GDN
input projections), GDN gates, decode attention (warp-per-head, KV
split-K, online softmax), fused residual+RMSNorm, triple QKV GEMV,
graph-capturable decode step |
| `csrc/module_inject/decode_loop.cu` | C++ generation loop taking a
backend-agnostic `std::function` replay callable (CUDA graph, eager
forward, or future SYCL); argmax and buffer updates run as a private
kernel; EOS checked via amortized D2H sync every 16 steps |
| `deepspeed/module_inject/segment_ki.py` | segment detection + forward
replacement (`apply_segment_ki`) |
| `deepspeed/module_inject/kernel_reference.py` | pure-PyTorch
executable specifications for every kernel — test oracle, runtime
fallback, porting reference |
| `deepspeed/ops/module_inject/{fused_glu,decode_loop}.py` | op builders
(JIT compile, lazy load) |
| `deepspeed/utils/static_cache.py` | hybrid-slot static cache: real
static KV layers for full attention, pass-through slot reusing HF's
cudagraph-safe GDN state buffers by reference |
| `deepspeed/runtime/rollout/hybrid_engine_rollout.py` | prefill → cache
setup → graph capture → C++ decode loop, with layered fallback
(full-step graph for b=1, graph+argmax for b>1, C++ loop, Python loop) |

## Performance

Qwen3.5-4B, RTX 4080 SUPER, greedy, b=1:

| | tok/s | relative |
|---|---|---|
| HF eager | 22.5 | 1.0× |
| **DeepSpeed (this PR)** | **69.4** | **3.1×** |
| vLLM | 74.9 | — |

## Tests

`tests/unit/module_inject/test_segment_ki_kernels.py` — 11 tests, all
passing (executed on RTX 4080 SUPER):

- [x] **Kernel vs reference consistency** (GPU, 6 tests): every kernel
compared against its `kernel_reference.py` oracle on identical inputs
(dual_gemv, quad_gemv, gdn_gates, triple_gemv, fused_add_norm,
decode_attn)
- [x] **Injection invariants** (CPU-runnable, 4 tests): injected forward
matches un-injected output, no weight copies installed, composite
autograd path, backward scatters gradients to the original Parameters
- [x] **Rollout → train → rollout integration** (GPU,
Qwen3.5-0.8B-Base): generate with graph capture + segKI, one SGD step
through the same injected model, generate again with changed output — no
inject/eject/sync calls anywhere in between
- [ ] Multi-GPU (AutoTP) validation (planned follow-up)

## Notes

- SYCL/XPU porting: `kernel_reference.py` serves as the executable spec;
`decode_loop`'s `std::function` interface is backend-agnostic (graph
replay or eager forward); SYCL kernels would follow the same op-builder
pattern.
- Related upstream fix split into a standalone PR: deepspeedai#8666
(attention_unfused alpha squaring).

---------

Signed-off-by: Guokai Ma <[email protected]>
Signed-off-by: Ma, Guokai <[email protected]>
Signed-off-by: Ma, Guokai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants