Skip to content

perf(kimi_k3): gfx1250 FlyDSL KDA backend without fla, fla fused KDA ops and [b, s] KDA projections - #1519

Draft
boyang-amd wants to merge 10 commits into
mainfrom
dev/boyang/kimi-k3.1-pro-mi455x-kda
Draft

boyang-amd wants to merge 10 commits into
mainfrom
dev/boyang/kimi-k3.1-pro-mi455x-kda

Conversation

@boyang-amd

Copy link
Copy Markdown
Collaborator

Stacked on #1451 (FlyDSL situ): the branch starts at its head 1cd6baa5, and the PR targets #1451's branch until #1451 is merged, then main. No Primus-Turbo change is needed.

Why

After #1451, the KDA core (short convs, q / k L2 norm, decay gate, chunk_kda, gated output RMSNorm) is the largest non-GEMM block left in the Kimi K3.1 Pro 4-layer proxy on 4 x MI455X: 365 ms of GPU kernel time per step and rank in the #1413 profile. About half of it is eager fp32 elementwise chains (kda_l2norm, kda_gate, KimiGatedRMSNorm); the rest is fla's Triton chunk_kda and conv, which run well below the hardware on gfx1250. On one MI455X, at the recipe's per-rank shape (B 2, T 4096, 96 heads, K = V = 128), the KDA core forward + backward takes 11.2 ms, about 270 ms per step over 3 KDA layers x 8 micro-batches. Around the core, every q / k / v / gate projection output was also transposed from [s, b] to the [b, s] layout the kernels take.

What

Two ways to run KDA faster, selected with the existing backend field (kda_backend, or use_kimi_k3_attention_backend, which supersedes it), and one layout change for every backend:

  • kda_backend: flydsl on gfx1250 (new; kda_kernels/_flydsl_gfx1250/, does not import fla). gfx950 keeps its existing flydsl implementation (_flydsl_v1); load_flydsl_kda_backend picks one by architecture, as attn_res_backend: flydsl does.
    • chunk.py: the chunked delta rule as fla's chunk_kda evaluates it with safe_gate and disable_recompute (the order of the steps and the tensors passed between them adapted from fla, MIT, credited in the file header), every step a FlyDSL kernel: the chunk-local gate cumsum, the fused forward intra step (Aqk, Akk = (I + L)^-1, w, u, qg, kg in one kernel), the forward state recurrence, the output, and in backward dAqk / dv, the state-gradient recurrence, wy_dqkg and the intra step (which writes dq / dk in bf16 directly), then the reverse cumsum. Nothing is recomputed in backward.
    • ops_kernel.py: the q / k L2 norm, the bounded gate and the gated output RMSNorm, forward and backward (16 lanes per 128-wide row, shuffle_xor row sums; the parameter gradients summed per lane and once on the host); conv_kernel.py: the short causal conv + SiLU.
    • Each kernel module builds its FlyDSL launchers once and keeps one compiled kernel per device (and per launcher name or conv width); every shape, element count and the stream are runtime arguments, and the inputs are cast to the fixed dtypes (bf16 q / k / v, fp32 g / beta / norm weight) before the launch, so other shapes reuse the compiled kernel without a stale result (the tests run two shapes in one process).
    • Requirements, checked when the model is built or on the first call, with a kda_backend: fla hint: the bounded gate (kda_gate_lower_bound in [-5, 0)), head dim 128, sequence lengths that are multiples of 64, no initial / final state, no conv bias, no context parallelism (packed sequences already go through the per-sample path). Tuning values are fixed at their measured best.
  • kda_backend: fla gets three opt-in fields (all default false): kda_fla_fused_ops puts the L2 norm, gate and gated RMSNorm on fla's fused kernels (as models/hybrid/kimi_delta_attention.py does); kda_fla_safe_gate and kda_fla_disable_recompute are passed to fla's chunk_kda (fla backend only; safe_gate needs the bounded gate). The flydsl backend does not read them.
  • Projections on one [b, s] copy of the input (every backend): without sequence or context parallelism, KimiDeltaAttention transposes the hidden-wide input to [b, s, h] once and runs the q / k / v / f_a / b / g projections on it, so their outputs are already in the kernels' layout; only o_proj's output is transposed back to [s, b, h]. With SP or CP the projections keep the [s, b, h] shard.
  • kimi_delta_attention.py: _resolve_kda_ops resolves the L2 norm, gate, conv and chunk_kda arguments once at construction; KimiGatedRMSNorm and _short_conv take the selected kernels.
  • examples/megatron/configs/MI455X/kimi_k3.1_pro_4L-BF16-pretrain.yaml: kda_backend / use_kimi_k3_attention_backend default flydsl (PRIMUS_ATTN_BACKEND=fla switches to fla, eager to the reference), and the three kda_fla_* fields on for the fla backend.
  • patches/fla_kda_autotune_patches.py: comment only (chunk_kda_fwd_kernel_intra_sub_chunk is reachable with safe_gate).
  • Tests: test_kda_flydsl_gfx1250.py and test_kda_fla_options.py (new; the latter skips without a GPU, as test_model_registry.py does).

Results

All on one MI455X (gfx1250), branch head 9cf24cdd, image amdprimus/amdprimus:tas-20261109 for the kernel benchmarks and tas-20261019 for training. Baseline: #1451's KDA path, the first row of each table; one GPU, so tokens/s is tokens/s/GPU.

KDA core forward + backward (B 2, T 4096, 96 heads, K = V = 128, bf16; the same inputs for every arm; relative error against the first row):

backend ms ms per step (x 3 layers x 8 micro-batches) vs #1451 memory held for backward largest relative error
#1451 (eager ops, fla conv, fla chunk_kda defaults) 11.201 269 1.00x 5.05 GB -
fla with the three kda_fla_* fields 5.798 139 0.52x 3.44 GB 2.3e-3
flydsl (this PR's recipe) 3.793 91 0.34x 3.23 GB 1.6e-3

The flydsl chunk step by step (forward + backward 2.50 ms through autograd, ms): cumsum 0.078, forward intra 0.307, state recurrence 0.206, output 0.185; backward dAqk / dv 0.160, state gradient 0.268, wy_dqkg 0.733, intra 0.555, reverse cumsum 0.079.

Training: the MI455X recipe cut to 3 layers, all KDA + dense MLP (no MoE / MLA; --num_layers 3 --linear_attention_freq '[1]*3' --moe_layer_freq '[0]*3' --routed_expert_hidden_size None), EP 1, MBS 2, GBS 16 (8 micro-batches, as per rank in the recipe), seq 4096, mock data, 12 iterations, arms interleaved twice, all on this branch (the [b, s] projections apply to every arm):

arm ms/iter tokens/s vs first row loss at iteration 12 hip mem usage
fla, kda_fla_* off (#1451's KDA kernels) 1115.7 / 1118.7 58,738 / 58,585 1.00x 3.284112 111.05 GB
fla, kda_fla_* on 983.0 / 980.8 66,673 / 66,822 0.88x 3.284026 106.23 GB
flydsl (this PR's recipe) 940.5 / 938.2 69,678 / 69,854 0.84x 3.284102 110.70 GB
  • flydsl is 178 ms per iteration faster than the first row (-16%), 7.4 ms per KDA layer and micro-batch. Losses over iterations 1-12 match the first row within 7.6e-5 relative (fla with the fields: 6.4e-5); the two runs of an arm are bitwise equal.
  • ms/iter and tokens/s: Primus's running averages as logged at iteration 12; memory: hip mem usage at iteration 12.
  • The [b, s] projections alone (flydsl, the same proxy, interleaved with the commit before): 967.6 -> 944.9 ms per iteration, 0.9 GB less memory, losses within 6.3e-5. The bf16 dq / dk in the intra step: bwd_intra 0.747 -> 0.556 ms, losses bitwise unchanged.
  • The 4 x MI455X recipe also runs 3 KDA layers x 8 micro-batches per rank; its end-to-end numbers are not in this draft yet (see Test).

Test

  • tests/unit_tests/backends/megatron/kimi_k3/ on gfx1250 (MI455X): 87 passed, 26 of them new. test_kda_flydsl_gfx1250.py: the flydsl chunk kernel against eager_chunk_kda (two shapes) and against fla's chunk_kda with safe_gate / disable_recompute; the L2 norm, gate (with the A_log / dt_bias gradients), gated RMSNorm (fp32 and bf16 weight), both cumsums and the conv against their eager forms, in the output and every input gradient; a negated beta, a halved gate bound, a negated output gate and a dropped SiLU fail the same checks; unsupported inputs raise with the kda_backend: fla hint; a run of every kernel in a fresh process imports no fla module. test_kda_fla_options.py: fla's fused ops and chunk_kda options against the eager path, the config defaults and the option resolution.
  • test_grouped_mlp.py, test_fla_kda_autotune_patches.py, test_mla_rope_qk_norm_patches.py, test_kimi_k3_quantile_balancing_patches.py: 75 passed (162 with the above). tests/unit_tests/configs/test_example_configs.py -k kimi: 5 passed.
  • The one-GPU runs above (no NaN, no MES / reset errors in dmesg).
  • pre-commit on the changed files, including thirdparty-lock.
  • 4 x MI455X recipe, end to end: not run yet.
  • gfx950 / MI355X: not run; the MI355X recipe keeps fla and the kda_fla_* fields off, and gfx950's flydsl implementation is unchanged.

Not in this PR

  • fla's chunk_kda_bwd_intra with a wider K block for the fla backend.
  • Fusing the KDA backward kernels further: the combined kernels would need more LDS and run at lower occupancy than the separate ones.

@github-actions

Copy link
Copy Markdown

Primary maintainers: @wenxie-amd @Xiaoming-AMD

Reach out to the primary maintainers with any questions about this PR.

Outside China Standard Time (UTC+8) working hours, for urgent issues you can also reach out to: vidushi8, lorri-rao, GeneDer, amd-fuyuajin, JohnQin-llm.

…nk_kda safe_gate and disable_recompute

After #1451 the KDA core is the largest non-GEMM block in the Kimi K3.1 Pro proxy on MI455X, about half of it eager fp32 chains that transcribe fla kernels the run already imports. Three config fields, all off by default: kda_fla_fused_ops puts the q / k L2 norm, the bounded decay gate and the gated output RMSNorm on fla's fused kernels (as models/hybrid/kimi_delta_attention.py does); kda_fla_safe_gate and kda_fla_disable_recompute are passed to fla's chunk_kda (fla backend only; safe_gate needs the gate bound in [-5, 0)). _resolve_fla_options resolves them once at construction. On one MI455X at the recipe's per-rank shape the KDA core forward + backward goes from 12.66 to 6.64 ms.
…ger path

The fused L2 norm, gate and gated RMSNorm against the eager ops in the output and every input gradient; chunk_kda with safe_gate / disable_recompute against its defaults on K3-shaped inputs; a halved gate bound and a negated output gate fail the same checks; config defaults and resolution errors.
… safe_gate and disable_recompute

kda_fla_fused_ops, kda_fla_safe_gate and kda_fla_disable_recompute on (PRIMUS_KDA_FLA_* override them), listed among the differences from the MI355X recipe.
…DSL without fla

On gfx1250 the flydsl KDA backend becomes a standalone implementation (kda_kernels/_flydsl_gfx1250, no fla import): the chunked delta rule as fla's chunk_kda evaluates it with safe_gate and disable_recompute (step order adapted from fla, MIT, credited in chunk.py), every step a FlyDSL kernel (chunk-local cumsum, fused forward intra step, state recurrence, output; dAv, dhu, wy_dqkg and intra in backward, nothing recomputed), plus FlyDSL kernels for the q / k L2 norm, the bounded gate, the gated output RMSNorm and the short convs. gfx950 keeps _flydsl_v1; load_flydsl_kda_backend picks by architecture, as attn_res_backend flydsl does, and load_flydsl_kda_ops returns the gfx1250 ops. _resolve_kda_ops selects the L2 norm, gate, conv and chunk_kda arguments once at construction; the kda_fla_* fields apply to the fla backend only. Unsupported inputs (unbounded gate, head dim other than 128, T not a multiple of 64, initial / final state, conv bias, context parallelism) raise with a kda_backend: fla hint. One MI455X, recipe per-rank shape: KDA core forward + backward 6.64 ms (fla with the kda_fla_* fields) -> 4.17 ms.
…out fla imported

The chunk kernel against eager_chunk_kda and fla's chunk_kda (safe_gate, disable_recompute); the L2 norm, gate, gated RMSNorm, cumsums and conv against their eager forms in the output and every input gradient; a negated beta, a halved gate bound, a negated output gate and a dropped SiLU fail the same checks; unsupported inputs raise; a fresh process runs every kernel with no fla module imported. The fla option tests follow _resolve_kda_ops (kda_fla_* ignored by non-fla backends).
…ackend

kda_backend / use_kimi_k3_attention_backend default flydsl; PRIMUS_ATTN_BACKEND=fla switches to fla with the kda_fla_* fields, eager to the reference.
…failing collection

models.kimi_k3 imports megatron.training, whose import chain needs a
visible GPU (aiter reads the gfx arch from rocminfo), so on a CPU-only
runner the module raised RuntimeError during collection. Skip it there,
as test_model_registry.py does; with a GPU the error still fails the run.
Without sequence or context parallelism, KimiDeltaAttention transposes
the hidden-wide input to [b, s, h] once and runs the q / k / v / f_a /
b / g projections on it, so their outputs are already in the [b, s, ...]
layout the kernels take; only o_proj's output is transposed back to
[s, b, h]. Before, every projection output was transposed. With SP or
CP the projections keep the [s, b, h] shard.

3-layer KDA proxy on one MI455X (kda_backend flydsl, EP 1, MBS 2,
GBS 16, seq 4096, 12 iterations): 967.6 -> 944.9 ms per iteration,
0.9 GB less memory, loss within 6.3e-5 of the [s, b] path.
The chunk backward returned dq and dk cast to bf16 from kda_bwd_intra's
fp32 outputs, which nothing else reads. The kernel now rounds them to
bf16 itself (round to nearest even, as .to(torch.bfloat16)) and stores
one 16-byte vector per 8 columns; dg stays fp32 for the reverse cumsum.

On one MI455X at B 2, T 4096, 96 heads, K 128: bwd_intra 0.747 ->
0.556 ms, the chunk forward + backward 2.822 -> 2.564 ms. The 3-layer
KDA proxy's losses are bit for bit unchanged over 12 iterations.
…ls; math.isnan in KDA tests

Seven gfx1250 FlyDSL KDA kernel modules defined _MAX_VIEW_BYTES without
reading it (the size checks are in chunk.py, conv_kernel.py and
ops_kernel.py), and two KDA tests spelled the NaN check err != err.
No behaviour change; flagged by code scanning on the PR.
@boyang-amd
boyang-amd force-pushed the dev/boyang/kimi-k3.1-pro-mi455x-kda branch from 9cf24cd to db75ffc Compare November 25, 2026 08:45
}


def _fla_or_skip():
return math.inf if math.isnan(err) else err


def _gfx1250_or_skip():

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