Skip to content

[FlyDSL] [Feature] Add the Kimi-K3 KDA per-channel decay gate to GDR decode - #4577

Open
waqahmed-amd-fi wants to merge 86 commits into
mainfrom
waqahmed/KIMI-K3_KDA-Decode
Open

waqahmed-amd-fi wants to merge 86 commits into
mainfrom
waqahmed/KIMI-K3_KDA-Decode

Conversation

@waqahmed-amd-fi

@waqahmed-amd-fi waqahmed-amd-fi commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR extends the existing FlyDSL GDR decode kernel with a compile-time per-channel decay path for Kimi Delta Attention (KDA).

  • Decay a is per-channel (B, Sq, H, K) instead of per-head (B, Sq, H).
  • dt_bias is per-channel (H, K) instead of per-head (H), and may be f32 while activations stay bf16/fp16.
  • Gate math is g = g_min * sigmoid(exp(A_log) * (a + dt_bias)) with g_min = -5.
  • gate_mode is inferred from a.dim() ("kda" if 4-D, else "gdr"), so existing callers keep the same signature.
  • Scalar GDR is untouched; the KDA tilings are new and reach only the KDA path.
  • flydsl_gdr_decode is exported from aiter.ops.flydsl.

Technical details

Kernel (kernels/gdr_decode.py): gate_mode is a factory argument, so "gdr" and "kda" compile to separate lru_cache binaries and PER_CHANNEL folds out under const_expr. Only a non-gdr mode is suffixed onto the kernel name, so existing GDR symbols are unchanged. The scalar arm's one edit is the dt_bias copy atom, which is the same 16-bit copy whenever dt_bias carries the activation dtype.

Wrapper (linear_attention_kernels.py): in KDA mode a is (B, Sq, H_v, D_k) and dt_bias is (H_v, D_k), and both are checked against the shapes that query and value imply. The kernel bakes in a few layout assumptions, so the wrapper now rejects the inputs that would break them: a must be dense along D_k, out must be contiguous, and an unshuffled state must have unit stride in K. A caller-supplied stream must be on query's device, and the staging copies are enqueued on that same stream so they complete before the launch reads them. A negative slot index marks a CUDA-graph padding row: the kernel zeroes that row of out and leaves the state pool untouched.

Tuning: _KDA_DECODE_BY_PART stores one (NUM_BLOCKS_PER_V_DIM, NUM_WARPS, WARP_THREADS_K) triple per batch size, measured at B ∈ {1, 4, 64, 256} for a single shape: 12 key and value heads, 128 wide, bf16 activations over an f32 state. Only those four batch sizes are tuned; every other batch size and shape uses _decode_tiling(). NUM_BLOCKS_PER_V_DIM splits the value dimension so that one decode launches more blocks, which is how a small batch fills the GPU, and the split that pays therefore depends on how many CUs the part has. An arch name does not pin that down — MI300X has 304 CUs and MI308X 80, or 64 on some parts, all gfx942 — so the table is keyed on (arch, CU count), and a part with no entry of its own uses _decode_tiling(), which reads the CU count at runtime.

Tests and benchmark: the KDA cases live in op_tests/test_flydsl_linear_attention.py, the canonical test for this op. Gate mode, dt_bias dtype and state dtype are sweep axes next to the existing ones, and every case is checked against the fp32 torch reference in that file. The same run then checks each tuned tiling of the current part, that staging copies run on a caller-supplied stream, and that the KDA table is keyed by gate and part. bench_gdr_decode_kda.py sweeps FlyDSL tilings, parity-checks each one against the same reference, ranks them by kernel time from the profiler, and prints a _KDA_DECODE_BY_PART row.

Test plan

  • python3 op_tests/test_flydsl_linear_attention.py, the command CI runs: 384 sweep cases, the 4 tuned MI355X tilings and 3 contract checks pass on MI355X, alongside main's GDN packed decode/verify cases in the same file
  • pytest op_tests/test_flydsl_linear_attention.py: 43 passed on MI355X: 22 GDR decode cases, 4 of them new in this PR, and main's 21 packed GDN cases
  • Numerics vs the fp32 torch reference: elementwise rtol/atol 1e-3, or 1e-2 for a bf16 state, which rounds on store; the benchmark's parity check uses an RMSE-ratio-or-absolute 1e-3 pair
  • Sweep: bf16 and fp16 activations, bf16 and f32 dt_bias, f32 and bf16 state, both gates, sequence lengths 1 and 2, batch 1, 2 and 128, GQA ratios 4 and 2, with and without in-kernel Q/K normalization
  • Scalar GDR unchanged: same _decode_tiling() dispatch as main, and the existing GQA cases still pass
  • Device-time A/B against vLLM's Triton packed decode at B ∈ {1, 4, 64, 256}, 12 heads, K=V=128, bf16, f32 state, on MI355X and MI300X (304 CUs), with both kernels matching the fp32 reference
  • MI300X, gfx942, 304 CUs: the CI command (384 sweep cases, the 4 tuned tilings of its row, 3 contract checks) and pytest (22 passed, 21 skipped; the packed GDN cases are gfx950-only) pass; the row comes from the tuner on that part

Test result

Kernel time per call, read from the PyTorch profiler with L2 flushed before every call, so launch overhead is excluded; 5 trials on fresh inputs, mean ± std. Triton is vLLM's fused_recurrent_kda_packed_decode_kernel on the same inputs, launched from a script outside this PR. "Untuned" is FlyDSL on the config _decode_tiling() picks, so it shows what the tuned row buys.

MI355X, gfx950, 256 CUs:

B Triton µs FlyDSL µs speedup FlyDSL untuned µs
1 6.96 ± 0.16 4.35 ± 0.02 1.60x ± 0.03 4.36 ± 0.02
4 7.28 ± 0.04 4.61 ± 0.02 1.58x ± 0.01 4.66 ± 0.03
64 20.04 ± 0.04 18.44 ± 0.05 1.09x ± 0.00 19.95 ± 0.09
256 74.77 ± 0.09 73.35 ± 0.18 1.02x ± 0.00 84.95 ± 0.23

do_bench times between events, and at B ≤ 4 that window also holds launch time the L2 flush does not cover, so neither these tables nor the tuner use it.

MI300X, gfx942, 304 CUs:

B Triton µs FlyDSL µs speedup FlyDSL untuned µs
1 5.37 ± 0.97 4.76 ± 0.57 1.12x ± 0.06 4.98 ± 1.05
4 7.06 ± 0.07 5.51 ± 0.03 1.28x ± 0.02 6.92 ± 0.03
64 52.23 ± 0.46 34.59 ± 0.05 1.51x ± 0.01 44.89 ± 1.32
256 148.40 ± 1.84 125.06 ± 0.39 1.19x ± 0.02 133.05 ± 0.32

PR Self-Review

Reviewed revision

6c0c2968c242844245b4d97a8bc75de0ba55be29

Behavior and intent

flydsl_gdr_decode gains a per-channel decay gate for Kimi Delta Attention (KDA). Before this PR it had only the per-head GDR gate: one decay per head, from a of shape (B, Sq, H) and a dt_bias of shape (H) in the activation dtype. KDA needs one decay per key channel, g = g_min * sigmoid(exp(A_log) * (a + dt_bias)), from a of shape (B, Sq, H, K) and a dt_bias of shape (H, K) that may be f32. So KDA decode could not use this kernel; it ran on vLLM's Triton kernel, which is slower at every batch size in Test result. A 4-D a selects the new gate at compile time, so existing GDR callers keep the same signature and the same kernel. The wrapper also rejects layouts the kernel cannot read, runs its staging copies on the caller's stream, and picks tuned KDA tilings by architecture and CU count.

Validation and unverified scope

Run on MI355X (gfx950, 256 CUs) and MI300X (gfx942, 304 CUs), as listed under Test plan and Test result:

  • python3 op_tests/test_flydsl_linear_attention.py, the command CI runs: the 384 sweep cases, each part's 4 tuned KDA tilings and the 3 contract checks pass.
  • pytest op_tests/test_flydsl_linear_attention.py: 43 passed on MI355X; 22 passed and 21 skipped on MI300X, where the packed GDN cases are gfx950-only.
  • Kernel time against vLLM's Triton packed decode at B ∈ {1, 4, 64, 256}, with both kernels matching the fp32 reference.
  • At 6c0c2968c2 on MI355X (gfx950): op_tests/test_flydsl_linear_attention.py ran clean, and pytest passed 43 tests. This is the tested code at 8fc2524666 plus the 3-line rename of GDR_GPU_ARCH to _gdr_gpu_arch() in the test file.

Unverified:

  • Not re-run on gfx942 at 6c0c2968c2.
  • Tuning covers one shape at those four batch sizes: 12 heads, K = V = 128, bf16 activations and an f32 state. Every other shape and batch size uses the _decode_tiling() config; the sweep checks some of them for correctness, but they are not tuned.
  • The table has rows for MI308X (80 and 64 CUs), but no MI308X run is reported here, and no other part was tested.
  • CI's python3 run covers only main(): the sweep, the tuned tilings and the 3 contract checks. The other pytest items, including the new a stride check, are not covered by CI; they passed under pytest above.

PR-specific question

Run against main's wrapper and kernel:

  • Every sweep case whose dt_bias dtype differs from the activations, such as an f32 dt_bias, trips main's assertion that dt_bias has the activation dtype. The other kda cases fail too, because main has only the per-head softplus gate.
  • The tuned-tiling run, test_flydsl_gdr_decode_kda_tiling_is_kda_only and test_flydsl_gdr_decode_kda_tiling_needs_this_parts_row fail because main has no _KDA_DECODE_BY_PART table.
  • test_flydsl_gdr_decode_rejects_noncontiguous_vector_dimension[4-a-kda] fails because main never checks a's strides, so it does not raise the expected ValueError.
  • test_flydsl_gdr_decode_stages_inputs_on_the_launch_stream trips the same dtype assertion through its f32 dt_bias. Past that, main reshuffles the state on the current stream but launches on stream, so with the current stream busy the launch can read the state before the reshuffle runs.

The gdr cases with dt_bias in the activation dtype exercise behavior main already has; they guard the per-head path, whose dt_bias load this PR edits.

No existing test covers the new behavior. op_tests/test_flydsl_linear_attention.py is the canonical test for flydsl_gdr_decode and the only one that calls it; before this PR it built only per-head inputs with dt_bias in the activation dtype and never passed a stream. The KDA decode tests under op_tests/triton_tests/gated_delta_net/ cover the Triton kernels, not this one.

Changed op tests

  • op_tests/test_flydsl_linear_attention.py: the canonical test for this op, extended in place rather than with a second suite. It adds gate mode, dt_bias dtype and state dtype as sweep axes, all checked against the file's fp32 reference, which now models the per-channel gate. It also runs each tuned KDA tiling of the current part and adds 4 pytest items: the a stride check, staging copies on a caller's stream, and two checks that the KDA table applies only to kda and only to its own (arch, CU count). No other test reaches the per-channel path, so none of it is redundant.
  • op_tests/op_benchmarks/flydsl/bench_gdr_decode_kda.py: the tuner behind _KDA_DECODE_BY_PART. It sweeps tilings, parity-checks each one against the test file's ref_func, ranks them by profiler kernel time and prints a table row; CI does not run it. It is not redundant: the test file's main() times only the tiling the wrapper picks, and the GDR benchmarks under op_tests/op_benchmarks/triton/ time Triton kernels, so this script is the only way to add a row for a new part.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

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

Extended tests (opt-in via labels):

Label Tests
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
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: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
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 4577 --add-label <label>

@waqahmed-amd-fi waqahmed-amd-fi self-assigned this Aug 5, 2026
waqahmed-amd-fi and others added 12 commits August 5, 2026 06:26
… harness

Expose the in-package decode check as `check_gdr_decode` so `op_tests`
can reuse the Triton reference, and add f32 `dt_bias` test cases against
lower-precision queries. The new `op_tests/test_flydsl_gdr_decode.py`
covers both package-namespace exports and numeric correctness.
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
- Detect KDA mode from 4D `a` and 2D `dt_bias`; keep the existing GDR scalar path unchanged.
- Implement per-channel decay in the FlyDSL kernel as `g_min * sigmoid(exp(A_log) * (a + dt_bias))` with vectorized K loads.
- Add a pure-PyTorch KDA reference in `aiter/ops/torch_ref/kda.py`.
- Extend op tests to validate the per-channel kernel against the torch reference and pin the reference itself.
K3 decodes at H_k == H_v == 12, which matches no row in gdr_decode_tuned.csv --
every row there is GQA at ratio 2 or 4 -- so the kernel fell back to
NUM_BLOCKS_PER_V_DIM=1, NUM_WARPS=4, WARP_THREADS_K=8. Untuned it is slower than
the Triton kernel it is meant to replace at three of four batch sizes, so the
sweep is what makes this a win rather than a regression.

Adds op_tests/op_benchmarks/flydsl/bench_gdr_decode_kda.py:

  --sweep   parity-checks all 44 legal configs against the torch reference, then
            re-times the top 5 over 5 trials and ranks on the median. A
            single-shot argmin is not enough: the leaders land within a few
            percent, the same order as run-to-run variation.
  --bench   A/B against vLLM's fused_recurrent_kda_packed_decode on identical
            inputs, with both sides parity-checked so a timing cannot be
            reported for a kernel that computes the wrong thing.

gfx950, H=12, K=V=128, bf16 over an f32 state, per-call us:

     B   Triton   untuned    tuned   speedup
     1     7.36      8.94     6.85     1.07x
     4     7.87      9.47     7.34     1.07x
    64    22.48     23.69    21.00     1.07x
   256    79.41     87.49    76.35     1.04x

WARP_THREADS_K is 16 or 32 in every winning row, never the fallback's 8, which
is the register-pressure behaviour the per-channel gate was expected to show.

The four new csv rows are additive: 12x12 appears nowhere in that file, so no
existing shape's config moves and the scalar path stays bit-identical.

Also copies two landmines from vLLM's setup that the tests were missing: the
exact padded-state stride assertion (stride()[1:] == (D*D, D, 1), which pins
that only the outer stride is padded) and a strided state_indices column, which
vLLM parametrizes and a serving stack really does hand over.

The comparator is loaded directly from a vLLM checkout with three stubbed
imports rather than importing vllm, which would drag in pydantic and the rest of
the config stack. The stubs are faithful -- under the default FLA_USE_FAST_OPS=0
vLLM's exp/log are tl.exp/tl.log -- and the script refuses to run if that
variable is set, so it cannot silently benchmark different math.

gfx942 is still outstanding; the ticket asks for both architectures.
…bias

`a` is vector-loaded along D_k, so require stride(-1)==1 and reject
strided views. Drop the dt_bias contiguity assertion since it is copied
contiguous below. Add tests covering strided-a rejection and
non-contiguous dt_bias acceptance.

@samremes samremes 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.

Code-level review only; no tests, builds, imports, or benchmarks were run. The per-channel recurrence math looks consistent with the intended formula. Residual gaps: confirm first-call JIT-only deployment is intentional, and extend automated coverage to the larger supported head counts and target batches.

)
# `a` reaches the kernel with its own strides and is read as vectors
# along D_k, so that axis has to be dense -- a strided one would be
# misread, not rejected. dt_bias needs no such check: it is copied

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.

High: Allowing non-contiguous dt_bias introduces an explicit-stream race. The later .contiguous() is enqueued on PyTorch's current stream, while _run_compiled launches on the caller-provided stream; the kernel can start reading before the copy completes. The shuffled-state copies have the same issue before and after launch. Please put preprocessing, launch, and postprocessing in the supplied stream context, or add explicit event dependencies.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed, and it reproduced: with the launch on a side stream and the current stream held busy, the output came back at RMSE ratio 0.98 — the kernel was reading unwritten staging memory.

dt_bias.dim() == 2
), f"per-channel `a` needs a 2D (H_v, D_k) dt_bias, got {tuple(dt_bias.shape)}"
assert (
a.shape[-1] == query.shape[-1]

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.

High: This only checks the last dimension, not the complete a == (B, Sq, H_v, D_k) shape. A consumer-native (1, B, H, K) view passes these checks but the kernel indexes it as (B, Sq, H, K), causing wrong-row or out-of-bounds reads for B > 1. Please validate the full shapes of q/k/v/a/b, indices, state, and out before creating the kernel.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. key, value, out, a, b, dt_bias, A_log, read_indices, write_indices and state are now validated against the full (B, Sq, H, D) layout before the kernel is created.

Comment thread aiter/ops/flydsl/kernels/gdr_decode.py Outdated
@@ -105,6 +116,7 @@ def gdr_decode_kernel(
dtype_ = get_dtype_in_kernel(dtype)
fx_dtype_ = fx.BFloat16 if dtype == "bf16" else fx.Float16

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.

High: Activation and state storage types are still conflated. vec_t is derived from dtype_, so fp16 activations with bf16 state truncate the final state vector to fp16 before the bf16 store. The wrapper also accepts fp32 activations, but this fallback selects fp16 for output conversion. Please restrict activation dtypes to the intended fp16/bf16 set and derive a separate state-store vector type from state_dtype_; add mixed fp16-activation/bf16-state coverage.

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.

(Probably this mixed case won't ever happen though?)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both fixed. The state store derives its vector type from state_dtype_ now, and activations are restricted to fp16/bf16 — asserted in the kernel factory, rejected with a clear error in the wrapper so fp32 callers don't trip an assert deep inside. Added mixed coverage parametrized over both activation types; it fails on fp16 if I revert just the vector type.

On whether it can happen: not today, no tuned row uses fp16 activations. But bf16 state is half the table (2688 rows), fp16 activations are already in the tests, and the two are independent arguments — so only coincidence keeps them apart, and the failure is silent state corruption. The fix costs nothing at runtime and the scalar path stays bit-identical, so I kept it.

Comment thread aiter/ops/flydsl/gdr_decode_tuned.csv Outdated
gfx950,torch.bfloat16,torch.float32,254,1,16,64,128,128,8,4,16,360.0035000000007
gfx950,torch.bfloat16,torch.float32,255,1,16,64,128,128,8,1,4,361.3235000000004
gfx950,torch.bfloat16,torch.float32,256,1,16,64,128,128,8,4,16,362.8634999999995
gfx950,torch.bfloat16,torch.float32,1,1,12,12,128,128,8,2,16,6.80

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.

Medium: get_default_kwargs does not include gate_mode in its key, so these per-channel-tuned 12:12 rows are also selected by scalar GDR and change its previous fallback geometry. Please add gate mode to the CSV schema/lookup key, treating existing rows as scalar mode. Also, all four new rows are gfx950-only; gfx942 still takes the untuned fallback despite being an explicit target.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. Added a gate_mode column to the CSV and to the lookup key; the 5376 existing rows are tagged gdr, the four new ones kda, and --sweep emits the tag. Scalar GDR at 12:12 is back on the (1,4,8) fallback (new test pins that). The column is appended last so an old-format row still parses as scalar, which is why the diff touches every line.

gfx942 is still outstanding: no gfx942 box available. The rows are additive now that the key distinguishes gates.

Comment thread aiter/ops/torch_ref/kda.py Outdated
x = a.float() + dt_bias.float()
A = A_log.float().exp()
# a is (..., H) or (..., H, K); line A up with the head axis either way.
A = A if a.shape[-1] == A.shape[0] else A[:, None]

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.

Medium: Inferring scalar versus per-channel mode from a.shape[-1] == len(A_log) is ambiguous. For a legal channel shape with H == K, this chooses scalar broadcasting and applies A_log over K instead of H, corrupting the oracle. Please branch on a.dim() and validate the expected shapes explicitly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. kda_gate branches on a.dim() now, and validates the head axis against A_log plus dt_bias against the selected mode, so a tensor meant for the other gate raises instead of broadcasting. Added a square H == K case that fails under the old shape-based rule.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
if not shuffle:
initial_state = initial_state.transpose(-1, -2)

kernel_pool = pool.clone()

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.

Medium: For the padded, non-dense view built above, pool.clone() materializes contiguous storage, so the kernel never sees the outer padded stride this test claims to exercise. Please clone the padded backing allocation and recreate the view, or use empty_strided(pool.shape, pool.stride()) followed by a copy; assert the resulting kernel pool keeps the original stride.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Switched to empty_strided(pool.shape, pool.stride()) plus a copy, with the stride assertion you suggested

waqahmed-amd-fi and others added 6 commits August 8, 2026 05:07
…ed geometries and 64-head fallback

Add test cases for B=1/64/256 with H=12 to exercise the tuned rows in gdr_decode_tuned.csv, and a B=2 H=64 case to cover the fallback geometry past K3's head count.
#4609 removed the `vector`/`arith` imports the per-channel branch still used,
and the merge left `r_g_vec` outside the scalar `else`, so building a
`gate_mode="kda"` kernel raised NameError. The benchmark's direct kernel call
also needed #4573's q/k/v strides and read/write index split.

Scalar path bit-identical; 47 tests pass on gfx950.
…opies

`a` was checked on D_k alone, so a consumer-native (1, B, H_v, D_k) view was
read row-shifted for B > 1. Validate every tensor against query's layout;
shape only, since callers pass strided views.

The `.contiguous()` staging and state copies ran on the caller's stream while
the kernel launched on `stream`, reading unwritten memory. Run them on
`stream`, entered only when it is foreign (~5us against a ~7us kernel).
…lar and KDA rows

Add `gate_mode` to the `gdr_decode_tuned.csv` schema and use it as a lookup key in `get_default_kwargs()`, so KDA-tuned rows cannot be selected for scalar GDR calls. Update the KDA benchmark to emit `gate_mode=kda` rows and add a regression test ensuring scalar GDR falls back to default configs at 12-head K3 geometries.

@samremes samremes 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.

I think the tests need some streamlining.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
)


def test_flydsl_gdr_decode_is_importable_from_package_namespace():

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.

I think this test is really quite unnecessary, all test should be only about testing it, not checking if it importable in some specific way.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
assert callable(flydsl_ops.flydsl_gdr_decode)


def test_flydsl_gdr_decode_is_advertised_in_all():

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.

Same here, not really relevant for testing the kernel itself.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
assert "flydsl_gdr_decode" in flydsl_ops.__all__


def test_package_export_is_the_kernel_wrapper_itself():

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.

Same.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
not is_flydsl_available(), reason="flydsl is not installed"
)

# Skips at import when flydsl or a GPU is missing, taking this module with it.

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.

What does this comment mean?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Revised. The helper module calls pytest.skip(allow_module_level=True) at import when flydsl or a GPU is missing, so this import can skip this file's tests as a side effect.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated

CI collects only ``op_tests/test_*.py`` at depth 1 (see
``.github/scripts/split_tests.sh``), so the in-package suite at
``aiter/ops/flydsl/test_flydsl_linear_attention.py`` never runs automatically.

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.

Should we still have the test under flydsl? And we could have the CI pull in the tests from there as likely intended. Anyway, this kind of commentary is not relevant to have in this test file.

Comment thread op_tests/test_flydsl_gdr_decode.py Outdated
assert not torch.equal(kernel_pool[0], pool[0])


def test_kda_tuned_rows_are_not_reachable_from_the_scalar_gate():

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.

Is this test relying on the CSV having a specific set of tuned rows? The test definitely should be independent of any CSV file and only test the dispatch/lookup logic. So remove this one and maybe replace with one where the tuning data is constructed explicitly in the test itself, and testing that the lookup picks the right one.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rewritten.

It now patches the parsed config map with rows built in the test and asserts only the lookup: two rows differing only in gate_mode each resolve to their own config, and with just a per-channel row present the scalar gate falls back.

Comment thread op_tests/test_kda_torch_ref.py Outdated
@@ -0,0 +1,121 @@
# SPDX-License-Identifier: MIT

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.

Why are we testing the reference? I'd just remove this file.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'd keep it. aiter/ops/torch_ref/kda.py is shipped code, not test scaffolding, and it has three consumers: the KDA kernel tests, the benchmark, and this file. It's the oracle those kernel tests judge against. if it drifts, they either fail and send you into the kernel, or agree with a wrong kernel and pass.

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.

I'd say that's the wrong place to put the torch_ref/kda.py then, it is not supposed to be "shipped code" in the sense that somebody would use it. The reference should be test-only oracle implementation that is simple enough to reason about without tests. If we want to have some tests for it, then the reference that the reference is judged against has to be something else, especially not the flydsl kernel, and also not something that just essentially reduces to torch.something() == torch.something()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and done in b4e6545.

aiter/ops/torch_ref/kda.py -> op_tests/kda_ref.py, so test-only is structural rather than a claim in a docstring, and op_tests/test_kda_torch_ref.py is gone.

The gate is the KDA form only now. The scalar softplus branch and the rank dispatch that chose between the two lost their last caller with that test, and the kernel's scalar path is already covered by the Triton reference in test_flydsl_linear_attention.py. What's left is a port of vLLM's naive_recurrent_kda plus a two-line gate, which is the "simple enough to reason about without tests" bar.

The benchmark under op_tests/op_benchmarks/flydsl/ imports it via a repo-root sys.path insert, since it is no longer reachable from an installed wheel.

head_k_dim: int
head_v_dim: int
use_qk_l2norm: bool = True
# KDA pairs an f32 bias with a lower-precision query; None is pre-847 behaviour.

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.

This is an existing file, but should the test file be moved under op_tests? Or does it make sense to have it here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Claude suggests to keep it where it is, for two reasons.

First, it doubles as a helper module. op_tests/test_flydsl_gdr_decode.py imports Args and check_gdr_decode from it, and only the in-package path works under both ways tests get run. CI executes files as python3 , which puts just op_tests/ on the path; pytest instead imports them as op_tests.* from the repo root. So after a move, neither from op_tests.test_… import … nor the bare from test_… import … would work in both modes.

Second, moving it would start running 22 tests that have never run in CI. If any of them is unhappy on another runner, this PR takes the blame.

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.

True, this has to be another PR that fixes the situation properly also for some existing flydsl tests.

Comment on lines +108 to +115
# Set only for a foreign launch stream, the one case needing reordering.
producer_stream = None
if stream is None:
stream = torch.cuda.current_stream(device)
else:
current_stream = torch.cuda.current_stream(device)
if stream != current_stream:
producer_stream = current_stream

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.

This logic does not make sense to me. If the stream is given, or we use the current_stream, we just need to put all operations on that stream. There is no need to have a separate producer stream?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, removed. The launch stream now simply defaults to the device's current one, and all the work runs on it.

nullcontext() if producer_stream is None else torch.cuda.stream(stream)
):
if producer_stream is not None:
stream.wait_stream(producer_stream)

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.

why are we waiting for anything? we should just put everything on the user-given stream (which defaults to current stream of the device) and it will run them in the correct order.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Dropped it. Also fixed the regression test.

…ctivations

fp16 activations truncated the final state to fp16 before a bf16 store; the two types agreeing is what hid it. Activations are now restricted to fp16/bf16, so the out store's f16 fallback can no longer narrow a wider type.
…, not shape

When heads equaled channels, `a.shape[-1] == len(A_log)` silently routed a per-channel gate through the scalar path. Pick the mode from `a`'s rank (3-D scalar vs 4-D per-channel) and validate `a`, `A_log`, and `dt_bias` shapes explicitly so mismatches raise instead of broadcasting.
samremes
samremes previously approved these changes Oct 23, 2026

@samremes samremes 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.

LGTM, thanks. All the findings so far are addressed at 64f1e5f: the in-package test is gone, the KDA cases are in the canonical op_tests/test_flydsl_linear_attention.py against the fp32 reference, the tuning-table scope is documented, and the comments and description are cleaned up. python3 op_tests/test_flydsl_linear_attention.py and pytest both pass locally on MI355X, and CI passes it on MI300X and MI35X. The remaining red shard is a runner that lost its connection.

@samremes

Copy link
Copy Markdown
Contributor

@waqahmed-amd-fi There is also a conflict in the tests now.

@waqahmed-amd-fi

waqahmed-amd-fi commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@waqahmed-amd-fi There is also a conflict in the tests now.

@samremes Fixed now.

waqahmed-amd-fi and others added 5 commits October 26, 2026 10:37
Refresh the MI355X (gfx950, 256 CUs) decode tile selections for
head_dim 1 and 256 in the FlyDSL linear attention kernel config table.
Refresh the MI300X (gfx942, 304 CUs) decode tile selections for
head_dim 1, 4, and 256 in the FlyDSL linear attention kernel config table.
@jamestangg
jamestangg requested review from huizzhan and yiijin October 28, 2026 11:20
@huizzhan
huizzhan requested a review from xytpai October 29, 2026 02:50
@jamestangg
jamestangg requested a review from jayzlee147 October 29, 2026 09:41
Keep both `flydsl_fp8_quant` and `flydsl_gdr_decode` in the FlyDSL export list.

Co-authored-by: Cursor <[email protected]>
@aiter-bot

aiter-bot commented Nov 6, 2026 •

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 6c0c2968c242 · mode shadow

Author self-review accepted. Readiness report:

Author answers

  • PASS — current-SHA answers are present and structurally specific
Show the author's self-review answers

Behavior and intent

`flydsl_gdr_decode` gains a per-channel decay gate for Kimi Delta Attention (KDA). Before this PR it had only the per-head GDR gate: one decay per head, from `a` of shape `(B, Sq, H)` and a `dt_bias` of shape `(H)` in the activation dtype. KDA needs one decay per key channel, `g = g_min * sigmoid(exp(A_log) * (a + dt_bias))`, from `a` of shape `(B, Sq, H, K)` and a `dt_bias` of shape `(H, K)` that may be f32. So KDA decode could not use this kernel; it ran on vLLM's Triton kernel, which is slower at every batch size in Test result. A 4-D `a` selects the new gate at compile time, so existing GDR callers keep the same signature and the same kernel. The wrapper also rejects layouts the kernel cannot read, runs its staging copies on the caller's `stream`, and picks tuned KDA tilings by architecture and CU count.

Validation and unverified scope

Run on MI355X (gfx950, 256 CUs) and MI300X (gfx942, 304 CUs), as listed under Test plan and Test result:

- `python3 op_tests/test_flydsl_linear_attention.py`, the command CI runs: the 384 sweep cases, each part's 4 tuned KDA tilings and the 3 contract checks pass.
- `pytest op_tests/test_flydsl_linear_attention.py`: 43 passed on MI355X; 22 passed and 21 skipped on MI300X, where the packed GDN cases are gfx950-only.
- Kernel time against vLLM's Triton packed decode at B ∈ {1, 4, 64, 256}, with both kernels matching the fp32 reference.
- At `6c0c2968c2` on MI355X (gfx950): `op_tests/test_flydsl_linear_attention.py` ran clean, and pytest passed 43 tests. This is the tested code at `8fc2524666` plus the 3-line rename of `GDR_GPU_ARCH` to `_gdr_gpu_arch()` in the test file.

Unverified:

- Not re-run on gfx942 at `6c0c2968c2`.
- Tuning covers one shape at those four batch sizes: 12 heads, K = V = 128, bf16 activations and an f32 state. Every other shape and batch size uses the `_decode_tiling()` config; the sweep checks some of them for correctness, but they are not tuned.
- The table has rows for MI308X (80 and 64 CUs), but no MI308X run is reported here, and no other part was tested.
- CI's `python3` run covers only `main()`: the sweep, the tuned tilings and the 3 contract checks. The other pytest items, including the new `a` stride check, are not covered by CI; they passed under pytest above.

PR-specific question

Run against `main`'s wrapper and kernel:

- Every sweep case whose `dt_bias` dtype differs from the activations, such as an f32 `dt_bias`, trips `main`'s assertion that `dt_bias` has the activation dtype. The other `kda` cases fail too, because `main` has only the per-head softplus gate.
- The tuned-tiling run, `test_flydsl_gdr_decode_kda_tiling_is_kda_only` and `test_flydsl_gdr_decode_kda_tiling_needs_this_parts_row` fail because `main` has no `_KDA_DECODE_BY_PART` table.
- `test_flydsl_gdr_decode_rejects_noncontiguous_vector_dimension[4-a-kda]` fails because `main` never checks `a`'s strides, so it does not raise the expected `ValueError`.
- `test_flydsl_gdr_decode_stages_inputs_on_the_launch_stream` trips the same dtype assertion through its f32 `dt_bias`. Past that, `main` reshuffles the state on the current stream but launches on `stream`, so with the current stream busy the launch can read the state before the reshuffle runs.

The `gdr` cases with `dt_bias` in the activation dtype exercise behavior `main` already has; they guard the per-head path, whose `dt_bias` load this PR edits.

No existing test covers the new behavior. `op_tests/test_flydsl_linear_attention.py` is the canonical test for `flydsl_gdr_decode` and the only one that calls it; before this PR it built only per-head inputs with `dt_bias` in the activation dtype and never passed a `stream`. The KDA decode tests under `op_tests/triton_tests/gated_delta_net/` cover the Triton kernels, not this one.

Changed op tests

- `op_tests/test_flydsl_linear_attention.py`: the canonical test for this op, extended in place rather than with a second suite. It adds gate mode, `dt_bias` dtype and state dtype as sweep axes, all checked against the file's fp32 reference, which now models the per-channel gate. It also runs each tuned KDA tiling of the current part and adds 4 pytest items: the `a` stride check, staging copies on a caller's stream, and two checks that the KDA table applies only to `kda` and only to its own `(arch, CU count)`. No other test reaches the per-channel path, so none of it is redundant.
- `op_tests/op_benchmarks/flydsl/bench_gdr_decode_kda.py`: the tuner behind `_KDA_DECODE_BY_PART`. It sweeps tilings, parity-checks each one against the test file's `ref_func`, ranks them by profiler kernel time and prints a table row; CI does not run it. It is not redundant: the test file's `main()` times only the tiling the wrapper picks, and the GDR benchmarks under `op_tests/op_benchmarks/triton/` time Triton kernels, so this script is the only way to add a row for a new part.

PR state

  • PASS — pull request is marked ready for review

Copilot findings

  • PASS — no active Copilot finding lacks a substantive author reply
  • ADVISORY — Copilot did not review the current head SHA

Code and op-test hygiene

  • PASS — no committed artifact or conflict marker detected

Required CI

  • PASS — Black: passed
  • PASS — Ruff: passed
  • PASS — Repository dependency: passed
  • FAIL — Aiter Test Gate: failed
  • Required CI failed; fix it before requesting human review.

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@waqahmed-amd-fi waqahmed-amd-fi changed the title [FlyDSL] [KIMI-K3] Enable KDA per-channel decay gate in FlyDSL GDR decode [FlyDSL] [Feature] Add the Kimi-K3 KDA per-channel decay gate to GDR decode Nov 6, 2026
@zufayu
zufayu requested review from coderfeli and removed request for coderfeli November 11, 2026 06:48

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.

4 participants