diff --git a/atom/model_ops/linear.py b/atom/model_ops/linear.py index 1abe514b99..fe064275db 100644 --- a/atom/model_ops/linear.py +++ b/atom/model_ops/linear.py @@ -1911,9 +1911,8 @@ def make_row_view(self, start: int, length: int) -> "LinearBase": # `self`. It does NOT isolate the bytes and is not meant to: the view # narrows `self.weight.data`, so an in-place write to the parent -- a # weight sync, or `shuffle_weights`, which no longer rebinds -- is seen - # through it. `_local_q_proj` is the only caller and rebuilds the view on - # every call anyway (its `is not` guard compares two `param.data` - # objects, and that attribute hands back a fresh one each access). + # through it. Cached views must be rebuilt if the parent replaces its + # weight storage instead of updating it in place. view._parameters = dict(self._parameters) view.weight = nn.Parameter( self.weight.data.narrow(0, start, length), requires_grad=False diff --git a/atom/models/kimi_k3/model.py b/atom/models/kimi_k3/model.py index 52ca6698d3..0bd240d033 100644 --- a/atom/models/kimi_k3/model.py +++ b/atom/models/kimi_k3/model.py @@ -179,6 +179,10 @@ def _extract_layer_idx(prefix: str) -> int: ) +# Legacy TP8 threshold; the current runtime crossover remains unqualified. +_KDA_IN_PROJ_SPLIT_MIN_TOKENS = 8192 + + def _is_e8m0_blockscale( quant_config: QuantizationConfig | None, quant_type: QuantType ) -> bool: @@ -1230,20 +1234,23 @@ def __init__( self.fuse_f_a_quant = ( f_b_type == QuantType.per_Token and f_b_dtype == dtypes.fp8 ) + self._split_in_proj = False + self._in_proj_views = None def get_streaming_deferred_modules(self) -> tuple[nn.Module, ...]: """Children that must remain unquantized until KDA fuses their weights.""" return self.in_proj, self.f_a_proj def process_weights_after_loading(self) -> None: - """Fuse all hidden-input projections into the single in-proj (one GEMM). + """Fuse all hidden-input projections into a single in-proj weight. Upstream already loads q/k/v/g into a single ``in_proj`` (``MergedColumnParallelLinear``) via ``packed_modules_mapping``. Here we extend that fused weight in place with the two remaining projections that also consume ``hidden_states`` -- ``b_proj`` (beta) and ``f_a_proj`` -- - so ``forward`` runs one ``self.in_proj(...)`` producing - ``[q | k | v | g | b | f_a]`` instead of three separate launches. The + so ``forward`` can emit ``[q | k | v | g | b | f_a]`` in one launch. + Eligible large prefills split this weight into ``[q | k | v | g]`` + and ``[b | f_a]`` row views to use the tuned tile-aligned GEMM. The tail storage is then released (the modules stay as empty shells; their bf16 post-load hooks are no-ops and never re-run). Runs once; idempotent. @@ -1294,6 +1301,35 @@ def process_weights_after_loading(self) -> None: dim=0, ).contiguous() self._in_proj_fused = True + self._split_in_proj = self._supports_in_proj_split() + if self._split_in_proj: + qkvg_rows = 4 * self.local_proj_size + # A plain tuple keeps the views out of the loader's post-load walk. + self._in_proj_views = ( + self.in_proj.make_row_view(0, qkvg_rows), + self.in_proj.make_row_view( + qkvg_rows, self.num_local_heads + self.head_dim + ), + ) + + def _supports_in_proj_split(self) -> bool: + from aiter.jit.utils.chip_info import get_gfx_runtime + + # Keep wrappers/subclasses outside the inherited native-only scope. + return ( + type(self) is __class__ + # Child post-load hooks may quantize the fused BF16 weight later. + and effective_layer_quant(self.in_proj.quant_config, self.in_proj.prefix)[0] + == QuantType.No + and self.tp_size == 8 + and self.hidden_size == 7168 + and self.local_proj_size == 1536 + and self.num_local_heads == 12 + and self.head_dim == 128 + and self.in_proj.weight.dtype == torch.bfloat16 + and self.in_proj.weight.shape == (6284, 7168) + and get_gfx_runtime() == "gfx950" + ) def _run_kda( self, @@ -1391,35 +1427,43 @@ def _forward_impl( hidden_states = hidden_states[:num_actual_tokens] if hidden_states_scale is not None: hidden_states_scale = hidden_states_scale[:num_actual_tokens] - # Single fused in-proj GEMM producing [q | k | v | g]; slice out each - # part. `out_gate` is the KDA output gate consumed at o_norm below - # (computed here so it rides the same GEMM instead of a separate one - # after the recurrence). in_proj's weight was grown in - # process_weights_after_loading to the fused [q | k | v | g | b | f_a], - # so this single unquantized call emits all six; f_b_proj stays a - # separate GEMM because it consumes f_a's output, not hidden_states. + # Split only the eligible large-prefill case; f_b_proj still consumes + # f_a's output and stays a separate GEMM in either path. lp = self.local_proj_size nlh = self.num_local_heads hd = self.head_dim - fused_in = self.in_proj(hidden_states, x_scale=hidden_states_scale) + if ( + kda_metadata.num_prefills > 0 + and num_actual_tokens >= _KDA_IN_PROJ_SPLIT_MIN_TOKENS + and self._split_in_proj + and hidden_states.dtype == torch.bfloat16 + and hidden_states_scale is None + and hidden_states.is_contiguous() + ): + qkvg_proj, tail_proj = self._in_proj_views + qkvg = qkvg_proj(hidden_states) + tail = tail_proj(hidden_states) + else: + fused_in = self.in_proj(hidden_states, x_scale=hidden_states_scale) + qkvg, tail = fused_in[..., : 4 * lp], fused_in[..., 4 * lp :] # No .contiguous() needed: mixed_qkv is a column slice (feature stride 1, - # row stride N_fused). Both causal-conv consumers read the token stride + # row stride N). Both causal-conv consumers read the token stride # from the tensor itself — causal_conv1d_fn uses x.stride(1) after # transpose (channel-last: stride(0)==1), and causal_conv1d_update only # requires x.stride(1)==1 (feature-contiguous, which the slice preserves). - mixed_qkv = fused_in[..., : 3 * lp] - out_gate = fused_in[..., 3 * lp : 4 * lp] + mixed_qkv = qkvg[..., : 3 * lp] + out_gate = qkvg[..., 3 * lp :] # beta is widened to fp32 inside _run_kda (see the note there): the KDA # delta-rule write strength must stay fp32 for accuracy. - beta = fused_in[..., 4 * lp : 4 * lp + nlh].unsqueeze(0) + beta = tail[..., :nlh].unsqueeze(0) # f_a feeds a second GEMM (f_b_proj) and is a column slice of the fused - # output, so it needs a unit row stride rather than the fused N_fused one. + # output, so it needs a unit row stride rather than the output's N. # Under a per-token FP8 f_b_proj that copy would be followed by a quant # of the same [T, head_dim]; strided_per_token_quant does the gather AND the # quant in one kernel, so only the quantized result is ever written. # Otherwise the plain contiguous copy runs and f_b_proj quantizes (or # not) exactly as before. - f_a_view = fused_in[..., 4 * lp + nlh : 4 * lp + nlh + hd] + f_a_view = tail[..., nlh : nlh + hd] if self.fuse_f_a_quant: from atom.model_ops.kimi_k3 import strided_per_token_quant @@ -1437,7 +1481,7 @@ def _forward_impl( # Prefill returns its own contiguous output. Allocate this buffer only # for decode/spec-decode, where the recurrence writes into it directly. if kda_metadata.num_prefills <= 0: - out = fused_in.new_empty( + out = qkvg.new_empty( (num_actual_tokens, self.num_local_heads, self.head_dim) ) @@ -1517,9 +1561,9 @@ def _forward_impl( ) # o_norm only reads this tensor, so keep the contiguous KDA output # instead of materializing an identical copy into `out`. - assert kda_out.dtype == fused_in.dtype, ( - "KDA output dtype must match the former fused_in-backed output " - f"buffer: got {kda_out.dtype} vs {fused_in.dtype}" + assert kda_out.dtype == qkvg.dtype, ( + "KDA output dtype must match the projection output " + f"buffer: got {kda_out.dtype} vs {qkvg.dtype}" ) assert kda_out.is_contiguous(), "KDA output must be contiguous for o_norm" out = kda_out.squeeze(0) diff --git a/tests/models/test_kimi_k3_kda_in_proj_split.py b/tests/models/test_kimi_k3_kda_in_proj_split.py new file mode 100644 index 0000000000..e72b4c7822 --- /dev/null +++ b/tests/models/test_kimi_k3_kda_in_proj_split.py @@ -0,0 +1,334 @@ +# SPDX-License-Identifier: MIT +# Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved. +# Copyright (c) 2026 ATOM Project Contributors + +"""CPU dispatch and row-slice checks around the real KDA load and forward paths.""" + +from types import SimpleNamespace + +import pytest +import torch +import torch.nn.functional as F +from aiter_stub import atom_without_aiter +from torch import nn + + +@pytest.fixture(scope="module") +def modules(): + with atom_without_aiter() as load: + yield SimpleNamespace( + kimi=load("atom.models.kimi_k3.model"), + ops=load("atom.model_ops.kimi_k3"), + glm=load("atom.models.glm5_next"), + chip=load("aiter.jit.utils.chip_info"), + linear=load("atom.model_ops.linear"), + ) + + +@pytest.mark.parametrize( + "override,arch,accepted", + [ + ({}, "gfx950", True), + ({}, "gfx942", False), + ({}, "gfx1250", False), + ({"tp_size": 4}, "gfx950", False), + ({"hidden_size": 4096}, "gfx950", False), + ({"local_proj_size": 3072}, "gfx950", False), + ({"num_local_heads": 24}, "gfx950", False), + ({"head_dim": 64}, "gfx950", False), + ({"dtype": torch.float16}, "gfx950", False), + ({"dtype": torch.float32}, "gfx950", False), + ({"shape": (6285, 7168)}, "gfx950", False), + ({"shape": (6284, 4096)}, "gfx950", False), + ({"glm": True}, "gfx950", False), + ({"subclass": True}, "gfx950", False), + ({"online_type": "No"}, "gfx950", True), + ({"online_type": "per_Tensor"}, "gfx950", False), + ({"online_type": "per_Token"}, "gfx950", False), + ({"online_type": "per_1x128"}, "gfx950", False), + ({"online_type": "per_1x32"}, "gfx950", False), + ], +) +def test_only_supported_native_geometry_is_enabled( + modules, monkeypatch, override, arch, accepted +): + cls = ( + modules.glm.Glm5NextKDAAttention + if override.get("glm") + else modules.kimi.KimiKDAAttention + ) + if override.get("subclass"): + + class Wrapper(cls): + pass + + cls = Wrapper + attn = object.__new__(cls) + nn.Module.__init__(attn) + for name, value in { + "tp_size": 8, + "hidden_size": 7168, + "local_proj_size": 1536, + "num_local_heads": 12, + "head_dim": 128, + }.items(): + setattr(attn, name, override.get(name, value)) + # Parent KDA fuses BF16 before the child can apply its online target. + quant_config = None + prefix = "layers.0.self_attn.in_proj" + if "online_type" in override: + + def layer_config(name, use_online_quant=False): + assert name == prefix + return SimpleNamespace( + quant_type=( + getattr(modules.kimi.QuantType, override["online_type"]) + if use_online_quant + else modules.kimi.QuantType.No + ), + quant_dtype=( + modules.kimi.dtypes.fp8 if use_online_quant else torch.bfloat16 + ), + ) + + quant_config = SimpleNamespace( + online_quant=True, get_layer_quant_config=layer_config + ) + # Metadata only: no production-sized weights or device allocation. + attn.in_proj = SimpleNamespace( + quant_config=quant_config, + prefix=prefix, + weight=SimpleNamespace( + dtype=override.get("dtype", torch.bfloat16), + shape=override.get("shape", (6284, 7168)), + ), + ) + monkeypatch.setattr(modules.chip, "get_gfx_runtime", lambda: arch) + # Plugin construction temporarily rebinds this module symbol. + monkeypatch.setattr( + modules.kimi, "KimiKDAAttention", modules.glm.Glm5NextKDAAttention + ) + assert attn._supports_in_proj_split() is accepted + + +HIDDEN, HEADS, HEAD_DIM = 16, 2, 4 +LP = HEADS * HEAD_DIM + + +class _Projection(nn.Module): + def __init__(self, in_features, out_features, quant_type, prefix): + super().__init__() + self.weight = nn.Parameter( + (torch.randn(out_features, in_features) / 8).bfloat16(), + requires_grad=False, + ) + self.quant_type = quant_type + self.quant_config = None + self.prefix = prefix + self.bias = self.weight_scale = None + self.params_dtype = torch.bfloat16 + self.native_a8_group_rows = None + self.runs_bf16 = False + self.is_output_padded = False + self.tp_dim = None + self.output_size = out_features + self.calls = [] + + def forward(self, x, x_scale=None): + self.calls.append((x, x_scale)) + return self._linear_forward(self, x, x_scale) + + +def _attention(modules, monkeypatch, tokens): + kimi = modules.kimi + torch.manual_seed(0) + row_views = [] + + def row_view(self, start, length): + view = modules.linear.LinearBase.make_row_view(self, start, length) + view.calls = [] + row_views.append(view) + return view + + monkeypatch.setattr(_Projection, "make_row_view", row_view, raising=False) + monkeypatch.setattr( + _Projection, + "_linear_forward", + staticmethod(modules.linear.LinearBase.forward), + raising=False, + ) + monkeypatch.setattr( + modules.linear, + "tgemm", + SimpleNamespace(mm=lambda x, w, bias=None, **kwargs: F.linear(x, w, bias)), + ) + + def linear(inputs, outputs, **kwargs): + outputs = sum(outputs) if isinstance(outputs, list) else outputs + return _Projection(inputs, outputs, kimi.QuantType.No, kwargs["prefix"]) + + for name in ( + "MergedColumnParallelLinear", + "ColumnParallelLinear", + "ReplicatedLinear", + "RowParallelLinear", + ): + monkeypatch.setattr(kimi, name, linear) + monkeypatch.setattr(kimi, "get_tensor_model_parallel_world_size", lambda: 1) + monkeypatch.setattr(kimi, "get_tensor_model_parallel_rank", lambda: 0) + config = SimpleNamespace( + hidden_size=HIDDEN, + linear_num_key_heads=HEADS, + linear_key_head_dim=HEAD_DIM, + linear_conv_kernel_dim=3, + rms_norm_eps=1e-6, + ) + attn = kimi.KimiKDAAttention( + SimpleNamespace( + hf_config=config, + compilation_config=SimpleNamespace(static_forward_context={}), + ), + None, + prefix="layers.0.self_attn", + ) + assert attn._split_in_proj is False + expected = torch.cat( + [attn.in_proj.weight, attn.b_proj.weight, attn.f_a_proj.weight] + ) + qualifications = [] + + def qualify(): + # The real load hook must finish fusing before it caches eligibility. + torch.testing.assert_close(attn.in_proj.weight, expected) + qualifications.append(True) + return True + + monkeypatch.setattr(attn, "_supports_in_proj_split", qualify) + loaded_modules = set(dict(attn.named_modules())) + attn.process_weights_after_loading() + attn.process_weights_after_loading() + assert qualifications == [True] and attn._split_in_proj + assert len(row_views) == 2 + assert attn._in_proj_views == tuple(row_views) + # Views must not be reprocessed by the loader under their suffixed prefixes. + assert set(dict(attn.named_modules())) == loaded_modules + assert attn.b_proj.weight.numel() == attn.f_a_proj.weight.numel() == 0 + monkeypatch.setattr(kimi, "causal_conv1d_fn", lambda x, *a, **k: x.T.split(LP, -1)) + monkeypatch.setattr( + modules.ops, "gather_kda_initial_state", lambda s, idx, _: s[idx].clone() + ) + attn._run_kda = lambda q, k, v, g, b, s, *_: ( + (q + k + v + g * b.unsqueeze(-1)).contiguous(), + s, + ) + monkeypatch.setattr( + attn.o_norm, "forward", lambda out, gate, is_prefill: out * gate + ) + monkeypatch.setattr(attn.o_proj, "forward", lambda x: x) + meta = SimpleNamespace( + num_actual_tokens=tokens, + num_prefills=1, + has_initial_state=torch.tensor([False]), + non_spec_state_indices_tensor=torch.tensor([0]), + non_spec_state_indices_in_tensor=None, + non_spec_query_start_loc=torch.tensor([0, tokens]), + ) + cache = SimpleNamespace( + k_cache=torch.zeros(1, 3 * LP, 3), + v_cache=torch.zeros(1, HEADS, HEAD_DIM, HEAD_DIM), + ) + ctx = SimpleNamespace( + attn_metadata=SimpleNamespace(kda_metadata=meta), + kv_cache_data={"layer_0": cache}, + ) + monkeypatch.setattr(kimi, "get_forward_context", lambda: ctx) + return attn, meta, row_views, qualifications + + +@pytest.mark.parametrize("tokens,padded", [(1, 1), (8191, 8192), (8192, 8192)]) +@torch.inference_mode() +def test_real_prefill_matches_fused_projection(modules, monkeypatch, tokens, padded): + attn, _, views, qualifications = _attention(modules, monkeypatch, tokens) + x = torch.randn(padded, HIDDEN).bfloat16() + got = attn._forward_impl(x) + weights = [view.weight for view in views if view.calls] + assert len(attn.in_proj.calls) == (tokens < 8192) + assert len(weights) == (2 if tokens >= 8192 else 0) + if weights: + assert [tuple(w.shape) for w in weights] == [ + (4 * LP, HIDDEN), + (HEADS + HEAD_DIM, HIDDEN), + ] + assert all( + w.untyped_storage().data_ptr() == attn.in_proj.weight.data_ptr() + for w in weights + ) + assert [w.storage_offset() for w in weights] == [0, 4 * LP * HIDDEN] + # f_a must have its own packed rows even for the one-row fallback. + f_a = attn.f_b_proj.calls[-1][0] + assert f_a.stride() == (HEAD_DIM, 1) and f_a.storage_offset() == 0 + attn._split_in_proj = False + expected = attn._forward_impl(x) + torch.testing.assert_close(got, expected) + fused = F.linear(x[:tokens], attn.in_proj.weight) + q, k, v, out_gate, beta, f_a = fused.split([LP, LP, LP, LP, HEADS, HEAD_DIM], -1) + gate = F.linear(f_a.contiguous(), attn.f_b_proj.weight) + beta = beta.unsqueeze(-1).expand(-1, -1, HEAD_DIM).reshape(tokens, LP) + reference = (q + k + v + gate * beta) * out_gate + torch.testing.assert_close(got, reference) + assert got.shape == (tokens, LP) + assert qualifications == [True] # No qualification/probing during forward. + + +@torch.inference_mode() +def test_cached_row_views_follow_inplace_weight_updates(modules, monkeypatch): + attn, _, views, _ = _attention(modules, monkeypatch, 8192) + x = torch.randn(8192, HIDDEN).bfloat16() + before = attn._forward_impl(x) + cached = attn._in_proj_views + attn.in_proj.weight.add_(0.125) + got = attn._forward_impl(x) + assert attn._in_proj_views is cached and len(views) == 2 + attn._split_in_proj = False + torch.testing.assert_close(got, attn._forward_impl(x)) + assert not torch.equal(got, before) + + +@pytest.mark.parametrize( + "fallback", ["disabled", "decode", "scale", "dtype", "strided"] +) +def test_unsupported_inputs_call_the_original_projection( + modules, monkeypatch, fallback +): + attn, meta, views, _ = _attention(modules, monkeypatch, 8192) + x = torch.zeros(8193, HIDDEN, dtype=torch.bfloat16) + scale = None + if fallback == "disabled": + attn._split_in_proj = False + elif fallback == "decode": + meta.num_prefills = 0 + elif fallback == "scale": + scale = torch.ones(8193, 1) + elif fallback == "dtype": + x = x.float() + elif fallback == "strided": + x = torch.zeros(8193, HIDDEN * 2, dtype=torch.bfloat16)[:, ::2] + calls = [] + + class ProjectionReached(Exception): + pass + + def fused(inp, x_scale=None): + calls.append((inp, x_scale)) + raise ProjectionReached + + monkeypatch.setattr(attn.in_proj, "forward", fused) + with pytest.raises(ProjectionReached): + attn._forward_impl(x, scale) + assert len(calls) == 1 and not any(view.calls for view in views) + assert torch.equal(calls[0][0], x[:8192]) + assert calls[0][0].stride() == x.stride() + if scale is not None: + assert torch.equal(calls[0][1], scale[:8192]) + else: + assert calls[0][1] is None