Skip to content

[FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward - #8739

Draft
huizzhan wants to merge 116 commits into
mainfrom
cursor/kda-fused-layer-bwd-8350
Draft

huizzhan wants to merge 116 commits into
mainfrom
cursor/kda-fused-layer-bwd-8350

Conversation

@huizzhan

@huizzhan huizzhan commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Goal

Add a training backward for the whole Kimi-K3 KDA (Kimi Delta Attention) layer, and run the whole block end to end: 96 heads × 128, short conv width 4, hidden 7168. This covers two rows of ZhangDanyang-AMD/Lumen#35:

  • "KDA fused layer (prefill / decode)"
  • "Low-rank F-decay / output-gate projections": f_a [128, 7168], f_b [12288, 128], g_proj [12288, 7168]

The existing fused KDA paths (#6550, #4741, #4577, #7225) are inference-only and have no backward.

What this PR has now

  • aiter/ops/kda_fused_layer.py
    • kda_layer_fwd and kda_layer_bwd(dy, x, w, num_heads, backend=..., cu_seqlens=..., lower_bound=...) are the training entry points.
    • The weights follow the Kimi-K3 checkpoint (Tiny-L13 and K3.1-Pro):
      • The output gate is a full-rank g_proj [H*V, D].
      • conv, A_log, dt_bias and o_norm are fp32; the projections are bf16.
    • A_log is per head, padded. The checkpoint stores fp32 [128] for 96 heads: entries 0–95 are the per-head decay rates and 96–127 are zeros.
      • In HF modeling_kimi_linear.py it is nn.Parameter(log(uniform(1, 16)), shape [num_heads]).
      • FLA's kda_gate uses A_log.view(H, 1), and its Triton kernels load A_log[i_h] with i_h < H.
      • So it is one rate per head, broadcast over head_dim. It is not a per-channel decay shared across heads.
      • The layer reads A_log[:H], and dA_log keeps the padded shape with zeros in the padding.
    • Epsilons: eps is the RMSNorm epsilon. The q/k L2 norm always uses L2NORM_EPS = 1e-6, on both backends, because the chunk kernels that fuse it (FLA / [Triton/Gluon] KDA: add the chunk_delta_attn backward pass #6498 / [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740) hard-code that value.
    • Safe gate: lower_bound (K3 gate_lower_bound=-5) switches the decay gate to lower_bound * sigmoid(exp(A_log[h]) * (f_b(f_a(x)) + dt_bias)), which lies in [lower_bound, 0), as in FLA chunk_kda(safe_gate=True, lower_bound=...). Without it the gate is -exp(A_log[h]) * softplus(·).
    • backend="torch" is the reference. It is a chunked WY implementation of the gated delta rule, with gradients from autograd.
    • backend="fused" is a hand-written backward that recomputes the forward. kda_layer_fwd(backend="fused") is an autograd.Function whose backward is this path.
    • Every optional piece is picked up by try-import and falls back to torch when it is missing or rejects the call.
    • kda_fused_layer.LAST_PIECES records which implementation served each stage in the latest fused call.
    • varlen: kda_layer_fwd and kda_layer_bwd take cu_seqlens, with x packed as [1, total, D]. The conv and the recurrence restart at every boundary.
    • The torch chunk path computes one chunk at a time and checkpoints each chunk under autograd. Memory grows with one [H, K, V] state per chunk, instead of the [C, C, K] decay of every chunk, which is ~51 GB at T=16384 and H=96. This keeps the long shapes feasible.
Stage Implementation (first available wins)
Chunk delta-rule forward Selectable, default triton: the in-tree Triton chunk_kimi_delta_attn (#4568/#4683). flydsl selects #8744 chunk_kda_fwd_flydsl. Both get contiguous token-major q/k/v/g/beta (_token_major). Triton gets fp32 q/k/v for fp32 layers and bf16 for 16-bit layers (compute_dtype). With a lower bound it gets safe_gate=True, lower_bound, the same gate mode as the backward. A kernel that rejects the call (ValueError) falls through to the next choice. The kernel is only used when a chunk backward kernel is active; otherwise the torch forward is kept so autograd can reuse its graph
Chunk delta-rule backward Selectable, default triton: Triton chunk_delta_attn_bwd (#6498 / #8740), which fuses the L2 norm, gate and beta sigmoid. With a lower bound it gets safe_gate=True, lower_bound. A kernel whose signature has no lower_bound (#8740 chunk_kda_bwd_flydsl today) gets the finished decay instead of a fused gate. Triton gets fp32 q/k/v/do for fp32 layers and bf16 for 16-bit layers. Every chunk kernel gets contiguous token-major inputs on every dtype. flydsl selects #8740 chunk_kda_bwd_flydsl. Without either, torch autograd over the recompute's graph. register_chunk_bwd still overrides the selection
f_b projection + decay gate, forward / backward FlyDSL GEMM epilogues (gfx950, bf16/fp16): GEMM_EPI_KDA_GATE / _GATE_BWD for softplus, and GEMM_EPI_KDA_SAFE_GATE / _SAFE_GATE_BWD for the safe gate. They read an fp32 parameter vector [A_log[:H] | lower_bound | dt_bias], so dt_bias is added in fp32 inside the epilogue instead of through the bf16 GEMM bias. The fp32 lr is split into bf16 hi + lo halves, [hi|lo] @ [f_b|f_b]ᵀ with K=256, so the gate pre-activation keeps ~fp32 accuracy. This matters because the safe gate's derivative amplifies an input rounding by exp(A_log)
g_proj projection + sigmoid × normalized o, forward FlyDSL GEMM epilogue GEMM_EPI_SIGMOID_MUL
g_proj backward: dx += dgp·g_proj and dg_proj = dgpᵀ·x FlyDSL bf16 GEMMs (nn / tn), always on the full-tile kernel. Every KDA GEMM pins use_half_tile_interleaved=False, enforced by an assert, so the HTI tn path (#8754) is never used. A shape the GEMM rejects, such as a K tail when tokens % 64 ≠ 0, falls back to torch on the same bf16-rounded inputs
Gated RMSNorm backward (do, dgp, d norm_w) #8741 aiter.ops.flydsl.gated_rmsnorm_bwd; otherwise torch
Short conv + SiLU backward Selectable, default triton: #8726 Triton causal_conv1d_split_qkv_bwd_triton_fn. flydsl selects #8726 aiter.ops.flydsl.causal_conv1d_bwd_flydsl.causal_conv1d_split_qkv_bwd_flydsl_fn, which has the same signature. Both are fed fp32 x/dq/dk/dv, with x as a [dim, tokens] view with unit channel stride and int32 query_start_loc. Without either, torch autograd over the recompute's graph
q/k L2 norm backward fused into the chunk backward when it fuses qk_l2norm; otherwise FlyDSL l2norm_bwd, or torch on CPU
Beta sigmoid backward fused into the chunk backward when it fuses beta_sigmoid; otherwise torch element-wise
Other GEMMs (q/k/v, f_a, w_beta, w_o; forward and backward) torch GEMMs in the layer dtype: bf16 inputs with fp32 accumulation and fp32 output (torch.mm(out_dtype=float32)), so nothing is rounded to bf16 before the L2 norm and the gates. fp32 layers stay fp32. LAST_PIECES['gemm'] reports torch.bfloat16->fp32. Where this torch build lacks out_dtype, it reports torch.bfloat16 inputs, fp32 GEMM: same numbers, slower, and the output is still never rounded to bf16
  • Backend selection (functional first, optimize later): the chunk forward, chunk backward and conv backward stages default to Triton. FlyDSL is used only when selected:

    • per process, with set_kda_pieces(chunk_fwd="flydsl", chunk_bwd="flydsl", conv_bwd="flydsl");
    • or by environment, with AITER_KDA_PIECES=chunk_bwd=flydsl,conv_bwd=torch.

    Fallback order is flydsl → triton → torch and triton → torch. A FlyDSL piece is also skipped, and recorded as <stage>_flydsl_skipped, when the layer dtype is not one it is built for (FLYDSL_PIECE_DTYPES):

    • the chunk forward and backward are bf16-only;
    • the conv backward takes bf16, fp16 or fp32.

    kda_piece_choices() shows the active selection. LAST_PIECES records the backend each stage actually used (chunk_fwd, chunk_bwd, chunk_bwd_fuses, conv_bwd, l2norm_bwd, rmsnorm_bwd, proj_gemms, gemm). It also records:

    • chunk_fwd_<backend>_skipped when a kernel rejected the call;
    • <stage>_<backend>_missing, with the ImportError, when a selected kernel is not in the tree (e.g. the Triton chunk backward on this branch alone).
  • Fusion switches, to A/B combinations by whole-network step time: AITER_KDA_FUSIONS="save_fwd=1,concat_proj=1,chunk_fuse=qk_l2norm+gate,proj_epilogue=0" or set_kda_fusions(...). LAST_PIECES records fusions and recompute.

    • save_fwd=1: the training forward keeps its activations and the backward skips the whole recompute. This trades memory for time.
    • concat_proj=1: one GEMM for x @ [w_q; w_k; w_v; f_a; w_beta (; g_proj)]ᵀ.
    • proj_epilogue=0: torch GEMMs instead of the FlyDSL epilogues.
    • chunk_fuse=auto|none|<subset>: which prologue stages the chunk backward absorbs.
  • Precision modes (AITER_KDA_PRECISION / set_kda_precision; LAST_PIECES['precision']):

    • default: fp32 element-wise activations.
    • megatron: matches the verified Megatron-LM [Triton/Gluon] [Config] Tune gfx1250 Gluon MXFP4 GEMMs for Llama3 70B TP4 #6872 KDA precision map:
      • projection outputs bf16;
      • conv: fp32 accumulation rounded to bf16 before the SiLU, bf16 output;
      • L2 norm in fp32 with bf16 q/k output;
      • beta sigmoid in fp32, fp32 beta;
      • gate computed in fp32 from a bf16 raw_g (no GEMM epilogue);
      • chunk output bf16;
      • gated RMSNorm: rstd fp32, the normed value rounded to bf16 before × sigmoid(gate), bf16 output;
      • backward: grad·σ(g) rounded to bf16 before the norm gradient;
      • conv and norm weights bf16 at runtime; only A_log and dt_bias fp32.

    Both backends honor the mode. MXFP8 GEMMs come in through the _proj_gemm hook, and the cuDNN FROST recurrence numerics are not reproduced.

  • FlyDSL pieces never raise on unsupported shapes. The FlyDSL L2 norm, [FlyDSL] [gfx950] Kimi-K3 KDA gated RMSNorm backward #8741 RMSNorm and the GEMM epilogues / proj_gemm check their constraints at call time and fall back to torch, recording <op>_skipped: <reason> in LAST_PIECES. A kernel that still rejects a call at runtime falls back the same way. The constraints are: row kernels need head dim % 64; GEMMs need K/N/D % 8 and 16-bit weights.

  • One projection-GEMM entry point for the MXFP8 work stacked on this PR: every projection GEMM goes through _proj_gemm(a, w, kind, cd, epilogue=..., name=...). That covers forward, dgrad and wgrad, concat_proj, the three epilogues and the fp32 low-rank f_b GEMMs.

    • kind is fwd (a @ wᵀ), dgrad (a @ w) or wgrad (aᵀ @ w).
    • register_proj_gemm(fn) installs a replacement for all of them. Returning NotImplemented hands a call back to the default path.
  • Why the g_proj backward is not a prologue fusion: the gfx950 GEMM moves A from global memory to LDS by async DMA, which never passes through registers, so an element-wise transform cannot be applied on load. In dg_proj = dgpᵀ·x, dgp is also the transposed operand. Instead, [FlyDSL] [gfx950] Kimi-K3 KDA gated RMSNorm backward #8741 produces dgp and the two products run on the FlyDSL bf16 GEMM rather than torch fp32. A true prologue fusion would need a register-staged A path in the GEMM.

  • Shared GEMM change in aiter/ops/flydsl/kernels/gemm_a16w16_gfx950.py:

    • Constexpr epilogue / epi_group, plus epi0..2 tensors. These are added to the full-tile kernel only, at the end of its arguments.
    • Epilogues require split_k == 1 and the full-tile kernel.
    • Offline gfx950 ISA with epilogue=0 is unchanged: the default HTI kernel is byte-identical, and the full-tile kernel has an identical instruction stream.
    • The base GEMM does not compile for gfx942 with or without this change, so the GEMM pieces are gated on gfx950.
  • The chunk contract uses fla chunk_kda layout and flag names:

    fn(do, q, k, v, g, beta, scale, chunk_size, *, use_qk_l2norm_in_kernel, use_gate_in_kernel, A_log, dt_bias, use_beta_sigmoid_in_kernel, [lower_bound], [cu_seqlens]) -> (dq, dk, dv, dg, dbeta, dA_log, ddt_bias)
    
  • op_tests/test_kda_fused_layer_bwd.py emits eight tables:

    • Layer backward: torch_chunk and fused vs an independent recurrent fp32 reference, with all 15 gradients asserted.

    • KDA block forward + backward (end to end): kda_layer_fwd + autograd backward for torch and fused. y and all 15 gradients are asserted, both are timed, and a fused pieces column lists which implementation served each stage.

      • Rows come from -l b,tokens,num_seqs. The defaults add the Lumen#35 long sequences at full K3 width: T=8192, B=2×4096, and varlen 8×2048 (packed, cu_seqlens through the layer). The short rows are 1×100, 1×256 and a varlen 2×128.
      • -f sweeps fusion combos (-f default save_fwd=1 save_fwd=1,concat_proj=1), and each row is labeled fusion combo.
      • Rows of ≤ 512 tokens are graded against the token-by-token fp32 oracle, run per sequence for varlen. Longer rows are graded against the torch_chunk path, because the oracle is too slow there. A ref column says which reference each row used.
    • Per-piece FlyDSL (-p): the fused backward with one stage on FlyDSL and the others on Triton, one row per stage. Columns:

      • used: the backend that actually served the stage.
      • skipped: why FlyDSL was skipped, if it was.
      • failed grads: which gradients are out of tolerance.

      The run asserts after printing the table, so a wrong FlyDSL piece is localized. A bare -p means all stages (argparse turns it into an empty list); an unknown stage is rejected. Every summary table that comes out empty is a hard error that names the empty sweep axes.

    • Chunk forward backends, layer layout (bf16): the Triton and FlyDSL chunk forwards get the exact q/k/v views the layer builds (channel-major, out of the short conv), plus the gate and beta. Both are compared with chunk_kda_torch, so a chunk-forward integration bug is isolated from the rest of the layer.

    • Chunk backward backends, channel-major inputs (fp32 and bf16): the Triton and FlyDSL chunk backward adapters get channel-major q/k/v views with the fused prologue and lower_bound, and are compared with chunk_kda_bwd_torch. This is the case that crashed in fp32.

    • GPU-only stage diff, fp32 and bf16, with the -g lower bounds: each GPU-only stage of the fused path against its torch math on identical inputs. Each row says ran or skip: <reason>; failures are asserted after the table. The stages are:

      • the FlyDSL GEMM epilogues: gate_proj, gate_proj_bwd (dz and per-head dA_log) and sigmoid_gate_proj, fed fp32 lr as the layer does;
      • the FlyDSL l2norm_bwd;
      • [FlyDSL] [gfx950] Kimi-K3 KDA gated RMSNorm backward #8741 rmsnorm_bwd;
      • the Triton and FlyDSL chunk backward with the layer's fused prologue: raw q/k, raw gate with A_log/dt_bias/lower_bound, and the beta logit.
    • g_proj bwd GEMM bit-exact (gfx950, bf16/fp16): dx (nn) and dW_g (tn) on small-integer inputs, so the fp32 result is exact, written into NaN-filled outputs. Any wrong, racy or unwritten element fails.

    • Projection fusion (gfx950, bf16/fp16): gate, gate_bwd, sigmoid_mul and gproj_bwd vs a torch reference. gproj_bwd is graded on the bf16-rounded dgp it actually receives.

    • Weights are laid out like the checkpoint (fp32 conv / A_log[128] / dt_bias / o_norm). -g sweeps the gate lower bound: the default is -5 (K3), and -g -5 none adds the softplus gate.

Block perf (Triton defaults)

Estimate for bf16, 1×8192, measured 222 ms before this change. One D×HK projection GEMM is 2·8192·7168·12288 ≈ 1.44 TFLOP.

Stage Work before Time before (est.) After 301ff1c
q/k/v + w_o GEMMs in the forward, fp32 5.8 TF ~48 ms bf16
Backward recompute: q/k/v + g_proj + an unused y, fp32 7.2 TF ~60 ms bf16, y dropped (−1.44 TF)
Backward GEMMs q/k/v dW+dx and w_o dW+dx, fp32 11.5 TF ~95 ms bf16
fp32 copies (x.float(), fp32 cat of the 36864×7168 q/k/v weights, twice) ~2.5 GB moved ~2–3 ms gone (16-bit cat only)
FlyDSL g_proj / f_b GEMMs, Triton chunk fwd+bwd, Triton conv, norms, element-wise — ~15–20 ms unchanged
  • fp32 GEMMs were ~90% of the block: 24.5 TF at ~120 TF/s.
  • As bf16 they are ~23 TF at ~0.8–1 PF/s, about 25–30 ms.
  • Expected bf16 1×8192 fused: ~45–50 ms, versus 222 ms (~4.5×).
  • Expected bf16 1×256: ~5 ms, versus 10.7 ms.
  • varlen 8×2048 also loses the 8 per-sequence layer calls (M=2048 GEMMs plus 8× launch overhead); its GEMMs now run once with M=16384.
  • The next bottleneck after this is the chunk and conv kernels; the remaining TODOs are FlyDSL-vs-Triton selection by measurement and saving forward intermediates instead of recomputing.

Validation

  • MI350X, commit 3986185: all 128 cases pass. The fused slowdown was fixed in 61ae989.
  • Commit a902351 (CPU / offline):
    • Fused vs reference: fp32 ≤ 1e-5, bf16 ≈ 3.6e-3, for every chunk-fusion combination.
    • The end-to-end block test passes on CPU for fp32 and bf16. All pieces report torch there, as expected.
    • With stub loaders, the selection logic gives the expected results: the defaults are honored, AITER_KDA_PIECES and set_kda_pieces override them, a missing flydsl kernel falls back to triton, and invalid values are rejected. Gradients stay at ~1.6e-6 in every configuration.
    • The GEMM epilogue modes and the nn / tn backward GEMMs compile offline for gfx950.
  • Commit 6ed52d4 (CPU):
    • varlen: the packed result equals the sequences computed separately, for both backends (dx exact, dW ≈ 4e-6). It differs from the unsegmented run, so the boundaries do reset.
    • The block test grades correctly with both references.
    • The checkpointed chunk path matches the previous results.
  • Commit bbed79a (CPU / offline):
    • Both gate forms (softplus and safe gate at -5) match the recurrent reference: fp32 ≤ 2e-6, bf16 ≈ 3e-3.
      • This holds with no chunk fusion, with all fusions, and with a chunk kernel that lacks lower_bound (gate fusion is dropped there).
      • The padded A_log gradient is exactly zero.
    • The fused forward equals the torch forward.
    • The projection fallbacks match the test reference for both forms.
    • All 6 GEMM epilogue modes compile for gfx950; the default HTI kernel's ISA is still byte-identical.
  • MI350X, 5-way merge at a902351:
    • With the default Triton pieces, the block table passes (y plus 15 gradients). fused is 3.5–5.3× faster than torch (bf16 t=256: 53.2 ms → 10.7 ms).
    • Two failures, fixed in 1509585:
      • gproj_bwd[1]: 1.70% of elements over tolerance, max 0.174. The reference used fp32 aux while the GEMM gets it rounded to bf16, which the layer does on purpose. A CPU simulation of only that rounding gives 1.69% and max 0.154, so the FlyDSL tn GEMM is fine. The reference now uses the same bf16 input.
      • fp32 with all FlyDSL pieces: dx wrong. The bf16-only FlyDSL chunk pieces are now skipped for non-bf16 layers. If the conv piece is the cause, the per-piece table will show it on its fp32 row.
  • Commit 1509585 (CPU, stub loaders): the per-piece table reports used / skipped as expected. FlyDSL chunk pieces are skipped for fp32 and used for bf16. An injected wrong chunk_bwd is caught and its gradients are named.
  • Commit 301ff1c (CPU):
    • bf16 fused vs reference: ≤ 3.4e-3. This holds only because the GEMMs output fp32; with bf16-rounded GEMM outputs, some seeds reached 7% through the L2 norm of small-norm q rows.
    • fp32: ≤ 2e-6 for every fusion and gate combination.
    • Native varlen equals the per-sequence result (dW ≈ 1e-4 from summation order), both with a chunk backward that takes cu_seqlens and with one that does not.
  • MI350X, merge 5fa502bc0 with 1509585: all fp32 cases pass (252). -p died with KeyError: 'failed grads': a bare -p gave an empty piece list, so the sweep produced no rows. Fixed in 07402b2, which was checked on CPU with stubbed tests:
    • a bare -p runs all three pieces;
    • -p chunk_bwd runs only that piece;
    • an empty -t raises with the empty axis named;
    • an unknown piece is rejected.
  • Commit 3bb1fd3 (CPU, stubbed [Triton/Gluon] [HIP] [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 #8744 / [Triton/Gluon] [HIP] [FlyDSL] [gfx950] Kimi-K3 KDA chunk backward (96 heads) #8740 / [FlyDSL] [MI350X] causal conv1d backward support for Kimi-K3 #8726 FlyDSL entry points with their current signatures):
    • The FlyDSL chunk forward and backward each get cu_seqlens in one call over all packed tokens.
    • The FlyDSL conv backward gets fp32 inputs, int32 query_start_loc = cu_seqlens and a unit-channel-stride x.
    • Both match the per-sequence torch reference within bf16 tolerance.
  • MI350X merge 5fa502bc0 with [Triton/Gluon] [HIP] [FlyDSL] [gfx950] KDA chunk forward for Kimi-K3 #8744 36970b8: in the -p table, chunk_fwd=flydsl failed all 15 gradients (err 0.84–0.88), while chunk_bwd and conv_bwd on FlyDSL passed. Root cause, fixed in 9b943be:
  • Lumen 9-layer stack (fp32 loss off by 5.4e-4; bf16 gradients 6–10% off), fixed in 63497ee:
    • fp32: the Triton chunk adapters cast q/k/v(/do) to bf16 even for fp32 layers. They now keep fp32.
    • eps: the L2-norm epsilon followed the RMSNorm eps on the torch side but not inside the fused-L2 chunk kernels. It is now fixed at 1e-6 on both.
    • GEMM fallback: when torch.mm(out_dtype) is missing, the GEMM output is no longer rounded to bf16.
    • CPU checks: fp32 layers now hand fp32 q/k/v to both Triton chunk stages (err 1.8e-6), and eps=1e-5 matches between backends (3.4e-7).
    • bf16 at small width: the torch backend computes internally in fp32, while the chunk kernels take bf16 inputs. On CPU that alone gives a gradient deviation of 6–15% at K=16 and ~2% at K=64/128. So "eager vs fused" in bf16 at small width compares fp32 against bf16; grade both against an fp32 reference instead.
  • Commit 6d41f21 (CPU, stubs):
    • The Triton chunk forward and backward both receive lower_bound=-5.
    • A missing Triton chunk backward shows up as chunk_bwd_triton_missing: ImportError: ... next to chunk_bwd=torch.
    • The stage-diff table runs or skips each stage with a reason, and flags an injected wrong l2norm_bwd.
  • Commit 9d16051 (CPU): every combination of save_fwd × concat_proj × chunk_fuse (auto, none, qk_l2norm+gate) matches the reference: fp32 ≤ 1e-6, bf16 7e-3, and varlen fp32 ≤ 1e-6. With save_fwd=1, LAST_PIECES shows recompute: no (save_fwd).
  • MI350X merge12 at 6d41f21: every fp32 fused backward crashed with view size is not compatible in Triton l2norm.py:94, called from chunk_delta_attn_bwd. Fixed in 873ada5:
    • Cause: _token_major used .to(dtype, memory_format=contiguous_format), which returns a same-dtype tensor unchanged. In fp32, the channel-major q/k views reached the kernel; bf16 only worked because the cast copied.
    • Fix: it now forces .contiguous() on every dtype, and the layer makes all chunk-kernel inputs (do, q, k, v, g, beta) contiguous before any chunk backward.
    • New table: a channel-major chunk-bwd test, fp32 and bf16.
    • CPU check: a stub that .view()s like Triton reproduces the GPU crash with the old helper and passes with the new one.
  • MI350X bf16 K3-width single-layer diag (Lumen): y 5.0e-3, gradients 0.5–0.7% vs eager (all-torch 2.5e-3); gemm was torch.bfloat16->fp32 and the padded A_log gradient was 0.
    • With lower_bound=-5 and chunk_bwd=torch, f_a/f_b/dt_bias got worse (1.0–1.2e-2, vs 0.7e-2 with Triton). Without a lower bound, chunk_bwd=torch improved the gradients.
    • Cause: with chunk_bwd=torch nothing fuses the gate, so the gate backward runs in the FlyDSL safe-gate epilogue. That epilogue rounded the fp32 lr to bf16, while Triton receives fp32 lr @ f_bᵀ.
    • On CPU, single-bf16 lr gives 2.1–2.5e-3 on d f_b / d dt_bias / d A_log at the gate alone; the hi+lo split gives 3.5e-6. Fixed in ded3d7a.
    • The stage-diff table now feeds the gate stages fp32 lr, as the layer does.
  • Commit ded3d7a (CPU):
    • The register_proj_gemm hook sees every projection GEMM (forward, recompute, dgrad, wgrad, epilogues, concat).
    • With the hook returning NotImplemented, results are unchanged (2e-6).
    • All earlier CPU checks still pass.
  • MI350X at ded3d7a: the fp32 view crash is fixed (forward y 2.9e-6). The backward at small width then raised l2norm row length must be a multiple of 64, got 16. Fixed in 8baabdc with the guarded fallback above; CPU stubs enforcing the real constraints fall back at K=16 (reason recorded, err 5.4e-6) and use FlyDSL at K=64. The stage-diff table skips stages whose constraints a shape cannot meet.
  • Commit 95a82cd (CPU), megatron precision mode:
    • The torch and fused backends give bit-identical y in fp32 and bf16, with and without lower_bound.
    • Gradients differ by 4e-3–1e-2: the fused backward carries Megatron's B2 rounding, while the reference backend's roundings are straight-through.
    • default is unchanged.
    • The op-by-op comparison with the Megatron map is in the project store (internal/kda-megatron-precision-diff.md).
  • MI350X at 95a82cd (without [WIP] KDA projection GEMM epilogues: split-K/HTI epilogues, K tails, in-kernel gate-bwd sums, Kimi-K3/K3.1 tuned configs #8754): test_kda_proj gproj_bwd[1] (dW_g, tn), m=100, bf16, had 0.70–0.71% of elements wrong (max 0.10).
    • This was not the HTI race: [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward #8739 already used only the full-tile kernel.
    • At m=100, K = m is not a multiple of 64, so dW_g fell back to torch, and that fallback used the unrounded fp32 dgp while the reference uses the bf16-rounded dgp. The varying count came from different random inputs per run.
    • Fixed in 89bf56b: the fallback takes the same bf16 inputs, HTI is asserted off for every KDA GEMM, and the bit-exact nn/tn table was added.
    • CPU: both the fallback (m=100) and the GEMM path (m=256) now match the bf16-rounded reference exactly and fill NaN-initialized outputs.
  • Not verified yet: the new numbers on GPU (perf and torch.mm(out_dtype) availability on ROCm), the long rows on GPU (time and memory), the per-piece table on device, and the epilogue numerics.

TODO

Dependencies

Open in Web Open in Cursor 

@cursor
cursor Bot force-pushed the cursor/kda-fused-layer-bwd-8350 branch from 839beab to 6954663 Compare November 26, 2026 08:25
@cursor cursor Bot changed the title [Draft] KDA fused layer backward for Kimi-K3 training: interface, torch reference, op_test [WIP] Kimi-K3 KDA fused layer backward Nov 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter standard tests on MI35X
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:mi300x Run Aiter standard tests on MI300X in PRs; main branch always runs them
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
ci:windows Windows JIT op smoke test on the Radeon R9700 ROCm runner
ci:multi-gpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 8739 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Reviews:
A reviewer is usually assigned within one working day after the PR is ready for review (see Code Review Process). If nobody has responded for about a week, mention the area contact listed in CONTACTS.md. Want to help review? See REVIEWERS.md.

@cursor cursor Bot changed the title [WIP] Kimi-K3 KDA fused layer backward [WIP] Kimi-K3 KDA fused layer backward: interface, PyTorch reference, K3 op_test Nov 26, 2026
cursoragent and others added 6 commits November 26, 2026 08:39
Squashed from #6498 (branch zain/kda/bwd, head 966a494),
FLA chunk_kda_bwd Triton port by Micky774.

Co-authored-by: Micky774 <[email protected]>
Co-authored-by: Sealeen Zhang <[email protected]>
Add op_tests/test_kda_chunk_bwd.py (aiter-op-test structure): K3 shapes
(H=96/48/12 x 128) graded against an fp32 chunked torch reference adapted
from #8739, with a us/TFLOPS/TB/s summary table. Add 96-head cases to the

Co-authored-by: Sealeen Zhang <[email protected]>
#6498 pytest suite.
fast_launch moved to aiter/ops/triton/utils in #8061; the #6498 import path
no longer exists on main (also fixes ruff I001).

Co-authored-by: Sealeen Zhang <[email protected]>
Co-authored-by: Sealeen Zhang <[email protected]>
chunk_kimi_delta_attn(bwd_backend="flydsl") recomputes the backward's
forward chunk-state recurrence (h, v_new) on the FlyDSL GDN K5 kernel
(chunk_gated_delta_h, USE_GK, token-major w/u) instead of the Triton fwd_h;
dhu, wy_dqkg, intra and the gate/l2norm/beta backward stay Triton. Falls
back to Triton outside bf16, K=V=128, chunk 64, non-varlen.

op_tests/test_kda_chunk_bwd.py benchmarks and grades both backends; the
pytest suite checks flydsl against triton at H=96.

Co-authored-by: Sealeen Zhang <[email protected]>
…v bwd, pluggable chunk bwd

Co-authored-by: Sealeen Zhang <[email protected]>
@cursor cursor Bot changed the title [WIP] Kimi-K3 KDA fused layer backward: interface, PyTorch reference, K3 op_test [WIP] Kimi-K3 KDA fused layer backward: FlyDSL fused backend, PyTorch reference, K3 op_test Nov 26, 2026
cursoragent and others added 3 commits November 26, 2026 09:01
bwd_backend="flydsl" now runs every backward stage on FlyDSL:
- chunk-state recurrence on the GDN K5 kernel, read in its native layouts
  (h [B,NT,H,V,K], v_new [B,H,T,V]); the two transpose copies are gone.
- new kernels in aiter/ops/flydsl/kernels/kda_chunk_bwd.py: dav, dhu,
  wy_dqkg, intra (+ in-kernel l2norm and beta-sigmoid backward) and
  gate_cumsum (+ gate activation backward, dA_log/dt_bias partials).
Forward intermediates are still recomputed by the Triton fwd prologue.
gfx950, bf16, K=V=128, chunk 64, no GVA, non-varlen; Triton otherwise.

chunk_kda_bwd_flydsl implements #8739's register_chunk_bwd 7-tuple
contract with fuses {qk_l2norm, gate, beta_sigmoid}; register_with_kda_layer()
installs it. All kernels compile offline for gfx950 (no spills, LDS <= 147 KB);
not run on a GPU yet.

Co-authored-by: Sealeen Zhang <[email protected]>
… (no duplicate chunk fwd)

Co-authored-by: Sealeen Zhang <[email protected]>
cursoragent and others added 5 commits November 26, 2026 09:29
…pilogues; full-rank g_proj

Co-authored-by: Sealeen Zhang <[email protected]>
In the last (partial) chunk, padded rows j >= nvalid hold g = 0, so the
intra dkt exponent g[j] - g[r] was large and positive for a strongly decaying
gate (gate in kernel / lower_bound) and exp2 overflowed; 0 * inf then gave
NaN in dk/dg. Mask padded rows in both intra loops and clamp every decay
exponent to <= 0 (causal pairs are <= 0 by construction).

Add AITER_KDA_FLYDSL_CHECK=1 to name the first stage that writes a
non-finite value. Tests: normalize q/k when the contract test runs without
the in-kernel l2norm (unnormalized keys diverge, which was the remaining
contract failures), and cover T=100 (full chunk + 36-token tail).

Co-authored-by: Sealeen Zhang <[email protected]>
…-import, FlyDSL GEMMs for g_proj bwd

Co-authored-by: Sealeen Zhang <[email protected]>
…t-in) for chunk fwd/bwd and conv bwd

Co-authored-by: Sealeen Zhang <[email protected]>
…, Lumen#35 long-sequence block rows

Co-authored-by: Sealeen Zhang <[email protected]>
cursoragent and others added 21 commits November 26, 2026 13:06
…ntiguous, all as 128-bit stores

Co-authored-by: Sealeen Zhang <[email protected]>
…g and intra gathers

Transposed staging (wy_dqkg h / dv^T / Akk^T, dhu qg^T / w^T incl. its
prefetch, dav do^T): lanes walked the source row-major, so neighbouring
lanes wrote vec * ld_dst elements apart, a few banks per wave. Transposed
stages now give consecutive lanes consecutive source rows, so their writes
are contiguous; the 16-byte global loads are unchanged.

intra off-diagonal gathers read g / q / k / dA with the four lane groups 4
rows apart on unpadded rows, i.e. the same banks (4-way). Rows are now
padded by 16 bytes (g 132 fp32, q/k 136 bf16, dA 68 fp32), moving the groups
16 banks apart while keeping the b128 row reads aligned (LDS 129 -> 134 KB,
still one workgroup per CU). Same values. 0 spills on all variants.

Co-authored-by: Sealeen Zhang <[email protected]>
…rnels + K5 recurrence, dense and varlen, fwd_backend switch, op_test

Co-authored-by: Sealeen Zhang <[email protected]>
… in parallel + fp32 MFMA block rows (64 -> 23 barriers)

Co-authored-by: Sealeen Zhang <[email protected]>
…und gate, 128-bit row loads/stores

Co-authored-by: Sealeen Zhang <[email protected]>
…ut staging, contiguous inputs + channel-major test layout

Co-authored-by: Sealeen Zhang <[email protected]>
… the Triton prepare keywords

Co-authored-by: Sealeen Zhang <[email protected]>
… with default fallback, tuner, Kimi-K3 / K3.1 shape CSVs

Co-authored-by: Sealeen Zhang <[email protected]>
…e bwd forward-prepare hook (opt-in)

Co-authored-by: Sealeen Zhang <[email protected]>
…nd a FlyDSL vs Triton benchmark

Co-authored-by: Sealeen Zhang <[email protected]>
…lve scratch in the dead g buffer) for 2 programs per CU

Co-authored-by: Sealeen Zhang <[email protected]>
…e, default 64: 2x programs, 48 KB LDS)

Co-authored-by: Sealeen Zhang <[email protected]>
…el_major); out_bv default 128

Co-authored-by: Sealeen Zhang <[email protected]>
…erand reads) in intra and output; qg/kg early to keep intra at 216 VGPRs

Co-authored-by: Sealeen Zhang <[email protected]>
…FlyDSL bwd) + test vs Triton's disable_recompute intermediates

Co-authored-by: Sealeen Zhang <[email protected]>
…ntiguous, all as 128-bit stores

Co-authored-by: Sealeen Zhang <[email protected]>
…/Akk) when selected, Triton disable_recompute otherwise; save_fwd self-check graded vs an fp32 reference, self-checks no longer abort main; stub plumbing test

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…raded self-check, non-aborting self-checks; #8744 13275a2) into kda-integration

Conflicts in op_tests/test_kda_fused_layer_bwd.py:
- test_kda_save_fwd_matches_recompute takes #8739's new signature
  (chunk_bwd=); #8754's config_name_of and #8757's MXFP8 tests are kept
- main(): #8739's non-aborting self-checks; #8757's
  test_kda_mxfp8_weight_cache joins them the same way (logged and recorded
  in SELF_CHECK_FAILURES instead of raising)

Co-authored-by: Sealeen Zhang <[email protected]>
cursoragent and others added 3 commits November 26, 2026 13:19
… 0), assert every FlyDSL intermediate finite, check the FlyDSL bwd with them vs recompute

Co-authored-by: Sealeen Zhang <[email protected]>
…test no longer depends on sys.modules/the real module); fall back to Triton on NaN in FlyDSL Aqk/Akk intermediates

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
…ue self-checks); the mxfp8 weight-cache self-check reports the same way

Co-authored-by: Sealeen Zhang <[email protected]>
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
… into kda-integration

Conflicts in op_tests/test_kda_fused_layer_bwd.py: #8757's side of the
MXFP8 block was empty (already merged), HEAD kept; its main() now has the
same non-aborting mxfp8 weight-cache self-check, its wording taken.

Co-authored-by: Sealeen Zhang <[email protected]>
@huizzhan huizzhan changed the title [WIP] Kimi-K3 KDA fused layer backward: FlyDSL fused backend, PyTorch reference, K3 op_test [FlyDSL] [gfx950] Kimi-K3 KDA fused layer backward Nov 27, 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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants