Skip to content

CUDA: fuse the row L2 clip chain - #401

Open
danielhanchen wants to merge 4 commits into
base/upstream-418fe97b5from
inkperf-cuda-clip-rows
Open

danielhanchen wants to merge 4 commits into
base/upstream-418fe97b5from
inkperf-cuda-clip-rows

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Pin for the prebuilt: upstream b12602 (418fe97) plus this one commit. Base branch base/upstream-418fe97b5.

What it changes

c = x (* w), y = c * clamp(t / (sqrt(sum_rows(c*c)) + eps), lo, hi) is 7 to 9 graph nodes: [mul,] sqr, sum_rows, sqrt, scale, [fill,] div, clamp, mul. Inkling 2 runs it on q, k and the relative-position projection of every layer, about a seventh of its decode kernels. The matcher in ggml-cuda.cu runs the chain as one kernel (clip-rows.cu) with the rounding of the separate ops:

  • the row sum reproduces the sum_rows_f32 reduction for the same block size
  • products use __fmul_rn so nothing is contracted into an FMA
  • the scale node must have scale 1 (only the eps bias is folded)

GGML_CUDA_DISABLE_CLIP_ROWS_FUSION=1 turns it off. test-backend-ops gets CLIP_ROWS_FUSE (16 cases: with and without the weight, fill, clamp ranges, row widths across the sum_rows block-size rule).

Evidence (B200, one exclusive card)

  • Inkling-2-Mini decode: 6653 -> 5723 kernels per token (142 clip_rows_f32 per token); with the mmvf and graph changes, tg128 +21 to +24% over the pin set, pp512 +50%.
  • test-backend-ops CUDA0: CLIP_ROWS_FUSE 16/16, SCALE, MUL, SUM_ROWS, SQRT, DIV pass.
  • llama-perplexity KLD against the pin set on UD-IQ1_S, UD-Q4_K_XL and the Mainline_Support UD-IQ1_S: PPL string equal, mean KLD 0, top-1 100%, also on the decode path (-ub 1, -ub 4) and with -sm layer -ts 1,1 on two GPUs. A 1-ulp change of the clip output alone gives mean KLD 3.1e-3, so the gate sees bit-identity, not a tolerance.

Notes

  • The exactness argument depends on the sum_rows block-size rule (nrows/nsm < 2 ? 512 : (ncols < 1024 ? 32 : 128)). If upstream changes that rule, this kernel has to follow it.
  • CUDA, HIP and MUSA share the .cu. HIP has __fmul_rn / __fadd_rn; bit-identity there is against the same HIP build's separate ops (checked on gfx1151, below).

Other backends

CUDA, HIP and MUSA share the .cu. On gfx1151 (Linux ROCm and Windows) the fused CLIP_ROWS_FUSE cases go from 0 to 16 OK. Metal and Vulkan are untouched and never take the fused path.

Cross-platform base vs head (pin set with all four speed pins): HIP gfx1151 Linux ROCm and Windows, Vulkan lavapipe, Metal (macos-15), CPU and CUDA B200, no regression on any leg; test-llama-archs and the tiny Inkling 2 perplexity are identical. The GitHub macos-15 runner reports MUL_MAT unsupported, so Metal is untested for matmul (this change does not touch Metal code).

c = x (* w), y = c*clamp(t/(sqrt(sum_rows(c*c)) + eps), lo, hi) is 7 to 9 graph
nodes ([mul,] sqr, sum_rows, sqrt, scale, [fill,] div, clamp, mul); Inkling 2
runs it on q, k and the relative-position projection of every layer, about a
seventh of its decode kernels. Run the chain as one kernel with the same
rounding as the separate ops: the row sum reproduces the sum_rows reduction for
the same block size, products are not contracted, and the scale must be 1.
GGML_CUDA_DISABLE_CLIP_ROWS_FUSION=1 turns it off.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T07:39:48.634001Z 6c0e84d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen
danielhanchen changed the base branch from master to base/upstream-418fe97b5 November 21, 2026 21:48

@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: 95a0c50eac

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +4543 to +4547
if (fill) {
if (fill->src[0] != scl || div->src[0] != fill) {
return 0;
}
memcpy(&limit_value, fill->op_params, sizeof(float));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject an in-place fill that overwrites the denominator

If the matched chain uses ggml_fill_inplace(ctx, norm, threshold), the fill overwrites scl before DIV reads it, so the unfused graph divides the threshold by itself (yielding 1 for a finite positive threshold). This matcher accepts that chain, but the fused kernel instead divides the threshold by the original norm, changing the output. ggml_can_fuse_subgraph permits this internal view, and the memory-range check only checks overlaps with the final output, so neither guard rejects it. Reject fills that alias scl, and add an in-place-fill regression case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in e418bb2. The matcher now declines the fusion when the FILL is a view of the SCALE output (ggml_fill_inplace on the norm) or shares its data, and when a per-row limit is one of the chain's intermediates (sqr, sum_rows, sqrt, scale), which the fused kernel never writes. Added CLIP_ROWS_FUSE(..., inplace_fill=1) with and without the weight: on the previous head both fail on CUDA0 (ERR 11.3), with the fix CLIP_ROWS_FUSE is 18/18. The Inkling 2 graph fills its threshold once per device, so its chains still fuse.

… chain

ggml_fill_inplace on the norm overwrites the denominator before DIV reads it,
so the separate ops divide the threshold by itself while the fused kernel
divides it by the original norm. Decline the fusion when the FILL is a view of
the SCALE output, and when a per-row limit is one of the chain's
intermediates, which the fused kernel never writes. Adds an in-place fill case.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: e418bb288b

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +4514 to +4516
const ggml_tensor * x = sqr->src[0];
if (sum->src[0] != sqr || sqrtn->src[0] != sum || scl->src[0] != sqrtn || clamp->src[0] != div ||
div->src[1] != scl || out->src[0] != x || out->src[1] != clamp) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject an in-place SQR that overwrites the final MUL input

When the weighted chain uses ggml_sqr_inplace(ctx, c) with c = ggml_mul(ctx, x, w), SQR overwrites c, so the final unfused MUL reads squared values. This matcher accepts that graph: ggml_can_fuse_subgraph allows the SQR view because its source is the internal m0, and the memory-range guard only checks overlaps with the final output. The fused kernel instead recomputes the original x*w for the final multiplication, changing the result (for a one-element row with c=2, limit 1, bias 0 and clamp [0,1], unfused returns 2 while fused returns 1). Reject SQR nodes that alias their input and add an in-place-SQR regression case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed and fixed in a185601. The matcher now keeps the ops separate when any chain node before the output is in place, which covers ggml_sqr_inplace on c as well as the other ops of the chain. I added an in-place SQR case to CLIP_ROWS_FUSE: it fails on the old matcher (ERR 1.34) and passes now, with all 20 CLIP_ROWS_FUSE cases passing.

ggml_sqr_inplace(ctx, c) overwrites c, so the final unfused MUL reads the
squared values, while the fused kernel recomputes c from x and w. Reject
the fusion when any node before the output is a view of its input, and
add an in-place SQR CLIP_ROWS_FUSE test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: a185601f56

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ggml/src/ggml-cuda/ggml-cuda.cu Outdated
Comment on lines +4559 to +4560
for (const ggml_tensor * t : { sqr, sum, sqrtn, scl }) {
if (limit == t || limit->view_src == t) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject the initial weighted MUL as a limit tensor

For a weighted chain with ne[0] == 1, div->src[0] can legally be m0: its shape matches scl, but this exclusion list omits it. The subgraph-use check also accepts this extra internal dependency. Fusion then skips computing m0 while passing its data as limit to the kernel, so the numerator comes from stale or uninitialized storage rather than x*w, changing the result. Include m0 among the rejected limit sources and add a single-column weighted regression case.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed and fixed in 6c0e84d. The weighted input m0 is now in the list of chain intermediates the limit must not be, so a one-column chain whose limit is x*w itself keeps the separate ops. I added that case to CLIP_ROWS_FUSE (ne=[1,24,7,1], limit_is_c=1): it fails on the previous head (ERR 1.60) and passes now, 21/21.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 6c0e84ddf6

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

erokhins pushed a commit to JetBrains-Hardware/llama.cpp that referenced this pull request Nov 24, 2026
abeloin added a commit to abeloin/llama.cpp-mix that referenced this pull request Nov 24, 2026
Merge --no-ff du commit épinglé par unsloth (scripts/unsloth/pr-set.json).
Couche 2, liste A (banc/notes/couche2-unsloth-liste-2026-11-24.md côté
notes).

Conflit limité à tests/test-backend-ops.cpp (structures de test ajoutées au même endroit par deux pins) : côté mix conservé, les cas de test de ce pin ne sont PAS repris — à réintégrer à la main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QBjnvFeJ4P7Jp71oC6pzWf
abeloin added a commit to abeloin/llama.cpp-mix that referenced this pull request Nov 24, 2026
…rafasmour ggml-org#73/ggml-org#98 réintégrés

Les merges r3 de unslothai#401 (clip L2 des rangées), ggml-org#414
(depth mix) et la sélection rafasmour (ggml-org#73 état de conv dans le concat,
ggml-org#98 deux portes delta-net en un lancement) avaient conservé le côté mix
de tests/test-backend-ops.cpp (conflit d'ajouts au même endroit) : les
noyaux fusionnés correspondants n'avaient plus de cas de test.

Blocs repris verbatim des commits sources, sans adaptation :
- 95a0c50, e418bb2, a185601, 6c0e84d (ggml-org#401, test_clip_rows_fuse)
- 03af137, f766457 (ggml-org#414, test_depth_mix_fuse)
- 7a0f09e (rafasmour ggml-org#73, conv state), e3a7e9c (rafasmour ggml-org#98, portes delta-net)
Structures insérées après leur ancre d'origine (ou avant
make_test_cases_eval quand l'ancre est absente du mix), enregistrements
avant « return test_cases; » ; les correctifs suivants appliqués par
git apply -3 sans conflit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01QBjnvFeJ4P7Jp71oC6pzWf

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant