Skip to content

Commit 8f2903b

Browse files
[Kimi-K3] Get the KDA gating route from aiter's support query
_use_aiter_kda_gating returns aiter's kda_gating.supports() for the gate lower bound, the state pool's dtype, the head size and the activation dtype, so ATOM keeps no copy of aiter's limits. aiter checks the live GPU, so gfx1250-strict parts route to aiter too. The route calls aiter's renamed entry, kda_gating_decode, and the error for a declined call tells how to log aiter's reason. The parity tests run H = 8, GLM-5.3-Flash's share at TP 8, again, and seed their inputs. The einops stand-in moves to tests/aiter_stub.py.
1 parent 3515e07 commit 8f2903b

4 files changed

Lines changed: 102 additions & 86 deletions

File tree

‎atom/models/kimi_k3/model.py‎

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,11 @@
2020
get_tensor_model_parallel_rank,
2121
get_tensor_model_parallel_world_size,
2222
)
23-
from aiter.jit.utils.chip_info import get_gfx
24-
from aiter.ops.triton.attention.kda_atom import (
25-
fused_sigmoid_gating_delta_rule_update as aiter_kda_gating_update,
23+
from aiter.ops.triton.attention.kda_gating import (
24+
kda_gating_decode as aiter_kda_gating_decode,
25+
)
26+
from aiter.ops.triton.attention.kda_gating import (
27+
supports as aiter_kda_gating_supports,
2628
)
2729
from einops import rearrange
2830
from torch import nn
@@ -86,25 +88,33 @@
8688

8789

8890
@functools.cache
89-
def _use_aiter_kda_gating(lower_bound: float | None) -> bool:
91+
def _use_aiter_kda_gating(
92+
lower_bound: float | None, head_dim: int, act_dtype: torch.dtype
93+
) -> bool:
9094
"""Whether decode and spec verify run the KDA gating update on aiter's
9195
gfx1250 kernel instead of ATOM's Triton kernel.
9296
93-
Decided from what is fixed before the first call: the arch, the gate and
94-
the state pool's dtype (aiter's kernel reads and writes an fp32 state).
95-
aiter checks the rest of its limits on every call. One cached decision and
96-
one log line serve every KDA layer.
97+
aiter's ``supports`` decides from what is fixed before the first call: the
98+
GPU, the gate, the state pool's dtype, the head size and the activation
99+
dtype. aiter checks the rest of its limits on every call. One cached
100+
decision and one log line serve every KDA layer.
97101
"""
98-
gfx = get_gfx()
99-
state_dtype = envs.ATOM_GDN_SSM_DTYPE
100-
on_aiter = gfx == "gfx1250" and lower_bound is not None and state_dtype == "fp32"
102+
state_dtype = getattr(dtypes, envs.ATOM_GDN_SSM_DTYPE, None)
103+
on_aiter = aiter_kda_gating_supports(
104+
lower_bound=lower_bound,
105+
state_dtype=state_dtype,
106+
head_k_dim=head_dim,
107+
head_v_dim=head_dim,
108+
act_dtype=act_dtype,
109+
)
101110
logger.info(
102-
"KDA decode and spec verify gating on %s (arch %s, lower_bound %s, "
103-
"ATOM_GDN_SSM_DTYPE=%s)",
111+
"KDA decode and spec verify gating on %s (lower_bound %s, head_dim %d, "
112+
"%s activations, ATOM_GDN_SSM_DTYPE=%s)",
104113
"aiter's gfx1250 kernel" if on_aiter else "ATOM's Triton kernel",
105-
gfx,
106114
lower_bound,
107-
state_dtype,
115+
head_dim,
116+
act_dtype,
117+
envs.ATOM_GDN_SSM_DTYPE,
108118
)
109119
return on_aiter
110120

@@ -134,32 +144,30 @@ def _kda_gating_update(
134144
without a launch, for inputs its kernel does not take, and a routed call
135145
that it declines raises.
136146
"""
137-
kernel = (
138-
aiter_kda_gating_update if on_aiter else fused_sigmoid_gating_delta_rule_update
139-
)
140-
result = kernel(
141-
A_log=A_log,
142-
a=a,
143-
b=b,
144-
dt_bias=dt_bias,
145-
q=q,
146-
k=k,
147-
v=v,
148-
o=o,
149-
initial_state=initial_state,
150-
inplace_final_state=True,
151-
cu_seqlens=cu_seqlens,
152-
ssm_state_indices=ssm_state_indices,
153-
ssm_state_indices_in=ssm_state_indices_in,
154-
num_accepted_tokens=num_accepted_tokens,
155-
use_qk_l2norm_in_kernel=True,
156-
is_kda=True,
157-
lower_bound=lower_bound,
158-
)
159-
if on_aiter and result is None:
147+
args = {
148+
"A_log": A_log,
149+
"a": a,
150+
"b": b,
151+
"dt_bias": dt_bias,
152+
"q": q,
153+
"k": k,
154+
"v": v,
155+
"o": o,
156+
"initial_state": initial_state,
157+
"inplace_final_state": True,
158+
"cu_seqlens": cu_seqlens,
159+
"ssm_state_indices": ssm_state_indices,
160+
"ssm_state_indices_in": ssm_state_indices_in,
161+
"num_accepted_tokens": num_accepted_tokens,
162+
"use_qk_l2norm_in_kernel": True,
163+
"lower_bound": lower_bound,
164+
}
165+
if not on_aiter:
166+
fused_sigmoid_gating_delta_rule_update(**args, is_kda=True)
167+
elif aiter_kda_gating_decode(**args) is None:
160168
raise RuntimeError(
161169
"aiter's gfx1250 KDA gating kernel declined a call routed to it; "
162-
"aiter's try_kda_gating lists the inputs it takes"
170+
"AITER_TRITON_LOG_LEVEL=DEBUG logs the reason"
163171
)
164172

165173

@@ -1194,7 +1202,9 @@ def __init__(
11941202
self._kda_gate_lower_bound = (
11951203
getattr(config, "linear_attn_config", {}) or {}
11961204
).get("gate_lower_bound", None)
1197-
self._kda_gating_on_aiter = _use_aiter_kda_gating(self._kda_gate_lower_bound)
1205+
self._kda_gating_on_aiter = _use_aiter_kda_gating(
1206+
self._kda_gate_lower_bound, self.head_dim, atom_config.torch_dtype
1207+
)
11981208
loader = _sharded_vector_loader(self.tp_rank, self.tp_size)
11991209
self.A_log.weight_loader = loader
12001210
self.dt_bias.weight_loader = loader

‎tests/aiter_stub.py‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
# SPDX-License-Identifier: MIT
22
"""Import ATOM modules without a GPU AITER build: `stubbed_aiter` for engine
33
modules that bind a few `aiter.dist` names, `atom_under_stubs` /
4-
`atom_without_aiter` for model code that needs AITER's enums and Triton."""
4+
`atom_without_aiter` for model code that needs AITER's enums and Triton, and
5+
`einops_where_missing` for model code that imports einops."""
56

67
import importlib
78
import importlib.abc
@@ -302,3 +303,19 @@ def atom_without_aiter():
302303
yield load
303304
else:
304305
yield importlib.import_module
306+
307+
308+
@contextmanager
309+
def einops_where_missing():
310+
"""A stand-in `einops` where it is not installed (the CPU job), for model
311+
modules that import it at the top."""
312+
if "einops" in sys.modules or importlib.util.find_spec("einops") is not None:
313+
yield
314+
return
315+
stand_in = types.ModuleType("einops")
316+
stand_in.rearrange = MagicMock(name="einops.rearrange")
317+
sys.modules["einops"] = stand_in
318+
try:
319+
yield
320+
finally:
321+
sys.modules.pop("einops", None)

‎tests/models/test_kimi_k3_kda_gating_dispatch.py‎

Lines changed: 30 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -2,81 +2,68 @@
22
# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
33
"""Which kernel runs the KDA gating update of Kimi-K3 decode and spec verify.
44
5-
aiter's gfx1250 kernel for the lower-bounded gate over an fp32 state pool on
6-
gfx1250, ATOM's kernel otherwise. AITER, Triton and einops are stood in for
7-
where they are not installed, so these tests run on the CPU job.
5+
aiter's gfx1250 kernel when aiter's `supports` takes the model setup, ATOM's
6+
kernel otherwise. AITER, Triton and einops are stood in for where they are not
7+
installed, so these tests run on the CPU job.
88
"""
99

10-
import importlib.util
1110
import inspect
12-
import sys
13-
import types
14-
from contextlib import contextmanager
15-
from unittest.mock import MagicMock, Mock
11+
from unittest.mock import Mock
1612

1713
import pytest
18-
from aiter_stub import atom_without_aiter
19-
20-
21-
@contextmanager
22-
def _einops_where_missing():
23-
"""model.py imports einops at the top, and the CPU job does not install it."""
24-
if "einops" in sys.modules or importlib.util.find_spec("einops") is not None:
25-
yield
26-
return
27-
stand_in = types.ModuleType("einops")
28-
stand_in.rearrange = MagicMock(name="einops.rearrange")
29-
sys.modules["einops"] = stand_in
30-
try:
31-
yield
32-
finally:
33-
sys.modules.pop("einops", None)
14+
import torch
15+
from aiter_stub import atom_without_aiter, einops_where_missing
3416

3517

3618
@pytest.fixture(scope="module")
3719
def model():
38-
with atom_without_aiter() as load, _einops_where_missing():
20+
with atom_without_aiter() as load, einops_where_missing():
3921
yield load("atom.models.kimi_k3.model")
4022

4123

4224
@pytest.fixture
4325
def decide(model, monkeypatch):
44-
"""`_use_aiter_kda_gating` for an arch and state pool dtype, decided afresh."""
26+
"""`_use_aiter_kda_gating` decided afresh, with aiter's `supports` mocked."""
4527
monkeypatch.setattr(model, "logger", Mock())
4628

47-
def decide(lower_bound=-5.0, gfx="gfx1250", ssm_dtype="fp32"):
48-
monkeypatch.setattr(model, "get_gfx", lambda: gfx)
29+
def decide(supported=True, ssm_dtype="fp32"):
30+
supports = Mock(return_value=supported)
31+
monkeypatch.setattr(model, "aiter_kda_gating_supports", supports)
4932
monkeypatch.setenv("ATOM_GDN_SSM_DTYPE", ssm_dtype)
5033
model._use_aiter_kda_gating.cache_clear()
51-
return model._use_aiter_kda_gating(lower_bound)
34+
return model._use_aiter_kda_gating(-5.0, 128, torch.bfloat16), supports
5235

5336
yield decide
5437
model._use_aiter_kda_gating.cache_clear()
5538

5639

40+
@pytest.mark.parametrize("supported", [True, False], ids=["supported", "unsupported"])
5741
@pytest.mark.parametrize(
58-
"case, on_aiter",
59-
[
60-
({}, True),
61-
({"gfx": "gfx950"}, False),
62-
({"lower_bound": None}, False),
63-
({"ssm_dtype": "fp16"}, False),
64-
],
65-
ids=["gfx1250-lower-bound-fp32-state", "gfx950", "no-lower-bound", "fp16-state"],
42+
"ssm_dtype, state_dtype",
43+
[("fp32", torch.float32), ("bf16", torch.bfloat16)],
44+
ids=["fp32-pool", "bf16-pool"],
6645
)
67-
def test_route(decide, case, on_aiter):
68-
assert decide(**case) is on_aiter
46+
def test_route_is_what_aiter_supports(decide, supported, ssm_dtype, state_dtype):
47+
on_aiter, supports = decide(supported, ssm_dtype)
48+
assert on_aiter is supported
49+
supports.assert_called_once_with(
50+
lower_bound=-5.0,
51+
state_dtype=state_dtype,
52+
head_k_dim=128,
53+
head_v_dim=128,
54+
act_dtype=torch.bfloat16,
55+
)
6956

7057

7158
def test_route_is_decided_and_logged_once(model, decide, monkeypatch):
72-
assert decide() is True
73-
monkeypatch.setattr(model, "get_gfx", lambda: "gfx950")
74-
assert model._use_aiter_kda_gating(-5.0) is True
59+
assert decide()[0] is True
60+
monkeypatch.setattr(model, "aiter_kda_gating_supports", Mock(return_value=False))
61+
assert model._use_aiter_kda_gating(-5.0, 128, torch.bfloat16) is True
7562
model.logger.info.assert_called_once()
7663

7764

7865
def test_routed_call_that_aiter_declines_raises(model, monkeypatch):
79-
monkeypatch.setattr(model, "aiter_kda_gating_update", lambda **kwargs: None)
66+
monkeypatch.setattr(model, "aiter_kda_gating_decode", lambda **kwargs: None)
8067
args = dict.fromkeys(inspect.signature(model._kda_gating_update).parameters)
8168
args["on_aiter"] = True
8269
with pytest.raises(RuntimeError, match="declined a call routed to it"):

‎tests/models/test_kimi_k3_kda_gating_parity.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ def _gfx1250() -> bool:
2424
pytestmark = pytest.mark.skipif(not _gfx1250(), reason="gfx1250 only")
2525

2626
K = 128
27-
# A rank's share of Kimi-K3's 96 KDA heads at TP 8, 4 and 2.
28-
HEADS = [12, 24, 48]
27+
# A rank's share of GLM-5.3-Flash's 64 KDA heads at TP 8, and of Kimi-K3's 96
28+
# at TP 8, 4 and 2.
29+
HEADS = [8, 12, 24, 48]
2930

3031

3132
@pytest.fixture(scope="module")
@@ -41,6 +42,7 @@ def _padded(table):
4142

4243

4344
def _compare(gating_update, heads, write, read, accepted, tokens_per_seq):
45+
torch.manual_seed(heads)
4446
t = write.size(0) * tokens_per_seq
4547
act = {"dtype": torch.bfloat16, "device": "cuda"}
4648
# beta is a column slice of the fused in-projection output in _forward_impl.

0 commit comments

Comments
 (0)