Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
945cf21
fix(page-checkpoint): reserve block 0 as null page when PAGE checkpoi…
ZhiweiYan-96 Nov 9, 2026
ad05a55
Merge remote-tracking branch 'origin/main' into fix/reserve-null-bloc…
whx-sjtu Nov 18, 2026
e487dc0
fix(cache): reserve null storage at pool construction
whx-sjtu Nov 18, 2026
e63edaf
test(cache): reproduce sparse MLA reads beside raw state
whx-sjtu Nov 18, 2026
b0d041f
style: align null-block test imports
whx-sjtu Nov 18, 2026
c2c6932
fix(cache): warm checkpoint copies without writing pages
whx-sjtu Nov 18, 2026
3218500
refactor(cache): share checkpoint warmup in the base builder
whx-sjtu Nov 18, 2026
503c2b2
fix(vllm): bind inherited native checkpoint descriptors
whx-sjtu Nov 18, 2026
ec76c78
Allocate Kimi's block-residual bank once per forward
whx-sjtu Nov 19, 2026
514173a
Split qualified Kimi KDA prefill input projections
Nov 19, 2026
e4166f4
Exclude online quantization targets from KDA projection split
whx-sjtu Nov 19, 2026
beec9b6
Fix sliced block-residual bank slot writes
whx-sjtu Nov 20, 2026
1e2ef92
Bound Kimi residual reads and pipeline payloads
whx-sjtu Nov 20, 2026
e6350bc
Stabilize Engram registration fixture page spans
whx-sjtu Nov 20, 2026
cb34b10
Merge corrected residual-bank parent into KDA projection split
whx-sjtu Nov 20, 2026
8f098db
Reuse cached Linear row views for KDA input projections
whx-sjtu Nov 20, 2026
1473016
Merge complete null-block prerequisite into residual-bank parent
whx-sjtu Nov 21, 2026
c916574
Merge main and preserve decode-image checkpoint warmup
whx-sjtu Nov 21, 2026
8c2f7f6
Merge residual-bank parent c916574f5 into KDA projection split
whx-sjtu Nov 21, 2026
46361d5
Match KDA projection fixture to Linear BF16 fallback state
whx-sjtu Nov 21, 2026
71a6aba
Fix wide Kimi residual bank offsets
whx-sjtu Nov 22, 2026
3e8527a
Merge commit '71a6aba6a88068afc0cad4facd224f90ea94128a' into codex/35…
whx-sjtu Nov 22, 2026
9ee08f4
Merge main after landing the Kimi residual bank parent
whx-sjtu Nov 27, 2026
c638070
Keep small prefills outside cached projection admission
whx-sjtu Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions atom/model_ops/linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
86 changes: 65 additions & 21 deletions atom/models/kimi_k3/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

where is the gfx950/TP8 crossover number? no timing anywhere, so this threshold is a guess..

@whx-sjtu whx-sjtu Nov 22, 2026 •

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.

At actual M=8192 on eight gfx950 GPUs, the split lowers whole-request median from 0.925402 to 0.911623 seconds (N=5, 1.49%). Matched GSM8K scores are 32/32 per arm; 30 candidate questions directly exercise the split and are correct. Larger measured points remain mixed, so 8192 is not an established general crossover.

Sources, larger shapes and incomplete-protocol limits

Current reference/candidate are 71a6aba/3e8527a1, executed as 9da62c2f/ae03f00d with the same startup-profiler overlay; accuracy observers were installed after timing/tracing. Runtime: TP8/DCP8/PP1, BF16 KV, FP8 index, Mono on, level3/FULL, Torch2.10/ROCm7.2.4, AITER b9e08dac. Timing includes the following 2,048 prompt rows; serial arms and small N limit interpretation. All eight ranks show actual M8192 and 69 KDA layers, with BF16 N6284 versus N6144+N140 projections. The N6144 route is aiter::bf16gemm_bf16_tn_256x256.

The earlier c916574/46361d57 comparison, with its same declared startup-profiler overlay, gives host medians 1.233926 to 1.237164 seconds at M12288 (+0.262%) and 1.560075 to 1.547117 at M16384 (-0.831%), N=5 each. Separate traced complete-KDA times are effectively flat. The one-GPU TP8-shaped operator probe at 8f098db/B9 is 5.38% slower at M12288. These results preserve the inherited threshold's limitation.

The matched GSM8K inputs cover documents 0–31; 29 complete outputs agree and three differ with correct answers. Actual M16331 exposes documents 0–29 to N6144 calls on 69 layers and eight ranks; documents 30–31 run at M845. That phase does not directly record N140. The candidate protocol fails after 32 outputs because shallow-copied row views share hook dictionaries, causing the temporary observer to mislabel the tail. Its second batch never runs; reference completes 64/64. Completed phases remain usable, but the candidate's overall protocol failed.

Existing full GSM8K remains 1282/1319 at source 0277 and its original recipe; this is not a matched full-dataset comparison. The new subset uses cap512 versus the earlier cap256. No candidate protocol success or universal crossover is inferred from these results.



def _is_e8m0_blockscale(
quant_config: QuantizationConfig | None, quant_type: QuantType
) -> bool:
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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__

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

type(self) is class blocks the vllm and glm subclasses too, intentional? gate on geometry plus opt-out instead?

@whx-sjtu whx-sjtu Nov 20, 2026 •

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.

Intentional: this optimization covers native Kimi only. vLLM adds state/capture handling; GLM folds its output gate after load. Matching geometry does not qualify those runtimes. The exact-class guard and tested generic-subclass fallback remain; enabling either subclass needs separate runtime qualification.

# 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,
Expand Down Expand Up @@ -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

Expand All @@ -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)
)

Expand Down Expand Up @@ -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)
Expand Down
Loading