Skip to content

Allocate Kimi's block-residual bank once per forward - #3577

Merged
zhuyuhua-v merged 29 commits into
mainfrom
task-3312-bank-cpu-20261119
Nov 27, 2026
Merged

zhuyuhua-v merged 29 commits into
mainfrom
task-3312-bank-cpu-20261119

Conversation

@whx-sjtu

@whx-sjtu whx-sjtu commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Part of LLM-Booster#688. Ready for human re-review; requested fixes are addressed, and the new data requests are non-blocking.

Kimi allocates its residual bank once per forward, bounds active reads without repeated views, and sends only the written prefix across PP boundaries. Receivers reconstruct writable capacity. Reader indices widen before stride multiplication. Initialization reads the required DCP Config field directly. Closing sites with active candidates now store the prefix inside the attention-residual kernel. Read-only paths stay unchanged; the first site keeps its fallback copy because it does not launch that kernel.

Dev record

  • Found: closing blocks copied the prefix after the attention-residual kernel.
  • Decided: write the next bank slot in the existing kernel through a separate mutating operator; retain the read-only operators.
  • Surprised: none.
  • Left undone: maintainer disposition, memory/copy-time acceptance and final-tree checks.

Named result

GPU traces confirm actual 49K bank rows and written-prefix transport. The sampler diagnostic proves reference logits are all NaN; the partial layer diagnostic narrows the first observed bad last row to KDA layer 56. Candidate regression, output equivalence and PP performance gains remain unestablished.

Testing

Local PP2 accuracy evidence: Kimi-K3 DSpark TP4/PP2 eager, full GSM8K 3-shot. Candidate scored 1268/1319 flexible matches (0.961334); main scored 1261/1319 (0.956027), against 0.94.

Local accuracy scope and retained CI failure

Tested candidate CI merge c8dd8112 has the identical full tree as earlier PR head c26e607c; the reference is main 6180dbcf. Head 65793d25 additionally includes main changes to KDA flush synchronization, so these are earlier-tree results. Pinned inputs, base image, AITER wheel and observed software versions match, but prepared runtime images and physical nodes differ. No same-node A/B, causal or performance claim. The original CI result, 1234/1319 (0.935557), remains valid and its cause unestablished. Maintainer review and CI requirements remain.

At 8839a3a, CPU CI passed 16,498 tests (1,620 skipped, 3 xfailed), including all nine initialization/policy/daemon cases; Black/Ruff/catalog passed. Llama smoke completed six responses on the reviewed tree. Heavy model/GPU jobs were skipped. Four MI355X closing-store cases remain qualified at 0915e4a.

Gates

Formal CHANGES_REQUESTED remains; the PR currently carries ci:atom, with no hold-landing label. Written-prefix PP transport meets the original code alternative; the latest review explicitly treats reference PP NaNs and unmeasured PP gains as nonblocking.

Exact corrections and historical evidence

Squash commit message

Keep Kimi-K3 residual blocks in a fixed bank and repair PP state

Allocate the residual bank once per forward, bound reads to initialized slots,
and write closing prefixes inside the attention-residual kernel. Retain the
layer-0 fallback copy when no mixing kernel runs.

Fix vLLM K3 pipeline parallel state: the old path copied a [T, k, H] bank into a
2-D [T, H] placeholder. Send only the written prefix into a
[T, ceil(start_layer / block_size), H] placeholder and re-pad it to writable bank
capacity on the receiving stage.

Read the required Config field decode_context_parallel_size directly in
init_model_env instead of through a getattr default.

Historical CI for 8839a3a checked out 80f1b8cf98b95b0095c71a5b36f33a15836eef50, tree 7d8e8b42d3dbcba962731946e5b340b535b4a536, exactly the reviewed 8839a3a tree. JUnit records all four DCP cases, both custom-all-reduce/local-rank/communicator cases, both policy-forwarding checks and daemon loading as actual passes. Other green gate jobs do not imply heavy model execution. The ordinary Llama smoke supplies no new Kimi/PP numerical or performance result.

At 8839a3a, all three reviewer-named tests have the full CLAUDE header. Main's unified initialization flow retains local rank, custom-all-reduce policy and communicator forwarding with the direct DCP Config read. The existing DCP fixture follows that entry and retains its assertions. Independent primary and blind source review passed; the qualified closing-store wrapper/kernel/test blobs and the squash text above are unchanged.

Previous CPU and smoke CI for 7698b4a checked out 38a602afa4a1829b1ca4cafa63b56b84de45380b (main 659c3ba4 plus 7698b4a), whose whole tree 6f54cf3560371a6bc1bf261157da2831c0cd21a3 equals the reviewed candidate. JUnit records actual passes for both PP2/DCP4 stages, default DCP1, non-PP DCP4 and daemon loading without communicators or MoE setup. ATOMesh's green unit-test job evaluated its scope gate without running tests; heavy ATOM/vLLM/SGLang/ATOMesh accuracy, RDMA and benchmark jobs were skipped. The Llama smoke adds no Kimi PP/numerical or performance qualification.

At 7698b4a, both initialization paths read config.decode_context_parallel_size directly, the close descriptions cover the kernel and layer-0 fallback, and the full squash message above includes the vLLM PP placeholder and PP+DCP repairs. The five focused CPU cases, negative controls, Black/Ruff and independent source review passed before publication. The qualified closing-store wrapper/kernel/test blobs are unchanged from 0915e4a.

Closing-store GPU qualification at 0915e4a: python -m pytest -q tests/model_ops/test_kimi_k3_attn_res_strided.py::test_close_block_matches_copy_and_replays passed all four selected cases, with zero failures/errors/skips and 14 PyTorch deprecation warnings. The run used one MI355X (gfx950), Torch 2.10.0+rocm7.2.4.git3d3aa833, Triton 3.8.0 and AITER 9f3cba25ee1117e8152112e46b8984d94c90b676, in image sha256:1e2f22fd1b108d1ce50d3dbdd7e7eb983f65b2cc6e10638b5b24f493e73c35e5.

Cases cover H=7168, T=1/16/4096, BF16/FP8 and offset/non-unit-stride banks. Bitwise output and complete-storage guards passed eagerly, under fullgraph Inductor, and on two direct-close graph replays per case. The saved Inductor wrappers add no copy; the old non-unit-hidden-stride case used an active-prefix copy inside the op, removed in 0b6e5bae8b. Compilation and graph capture were tested separately.

For T4096/H7168 BF16 with two addends, median complete eager-call time was 118.202 us for mix plus explicit copy versus 96.773 us for fused close. These are three short alternating 50-call CUDA-event samples per arm after ten warmups; host enqueue gaps may contribute. They are operator observations, not model/PP throughput or an established system gain. Recorded peak allocation combines both arms, references, compiler and graph state, so it is not a memory-savings comparison.

Historical CI for 0915e4a checked out merge 84b511a (main 90bbf07 plus 0915e4a), tree f1f95e2165741444e4fd80f310af14877cd7655a. All six changed files equal the reviewed candidate. JUnit confirms the decoder no-copy, closing-schema and compiled bank-view mutation cases passed. Heavy model/GPU jobs were skipped; the smoke completed six Llama responses and does not qualify the new Kimi closing kernel.

At 7989461, the main merge passes 131 focused CPU tests (45 skipped), seven Engram copy tests and a fixture negative control; Black/Ruff pass. Maintained CPU CI passed 16,264 tests; general offline smoke passed.

At d3f31f58b107e3dd4e410cb80812d98ae3f54354, primary and sole independent reviews cleared the initialization correction. Source-backed CPU controls give 2 failed/2 passed on old code, then 4 passed with the fix. Black/Ruff/whitespace passed. Maintained CPU CI also passed: 15,239 tests, with 1,562 skipped and 3 xfailed; all four new contract cases and Black/Ruff/catalog passed.

The 37 positive reader GPU cases remain historical evidence at parent 71a6; they do not qualify the new closing store. No new full-model or PP success is claimed.

Main reconciliation 7989461 has parents d3f31f5 and de8d9d4. Only scaled_table required conflict resolution; its file now equals main after upstream moved UVA to owned copies. The Kimi E8M0 norm producer is inherited unchanged from main. All other feature blobs retain d3. Automatic maintained CI checked out 1a98aa359c055ee54bbcbd5689b8aac07a573fe1, whose tree 33a62fd0b9606fa0d64d6b820823a9d9314b7250 equals the reviewed candidate. The CPU suite reports 16,264 passed, 1,606 skipped and 3 xfailed; Black, Ruff and catalog checks pass. JUnit confirms the Engram copy/idempotence/refusal/cleanup cases ran. Offline smoke generated six responses with Meta-Llama-3-8B-Instruct. Heavy Kimi/model accuracy and benchmark jobs were skipped; this general smoke adds no Kimi PP/numerical or performance qualification.

Historical d3 evidence: tree 4daa346a28d8920e117eb029f72d055e086b3d87 appends to 71a6aba6a88068afc0cad4facd224f90ea94128a. That correction added three production lines and a 111-line CPU regression. All other Git blobs are unchanged. Full feature scope against incorporated main is weighted 169 code/822 test lines.

The guarded reference diagnostic used main cccc96a0 plus the reader correction and a declared temporary capture overlay. On every PP0/TP0–3 rank, _gather_pass_keys received a [12288,128] byte view, a [49152,128] output and the exact int32 permutation 0..49151. There were 36,864 indices outside the logical input axis on each rank. The backing allocation had capacity for 180,288 rows. The diagnostic stopped before the gather and completed owned cleanup; it is not a passing PP comparison.

init_model_env omitted decode_context_parallel_size in the PP call. The real init_pp_aware_dist_env consumed its default of one. Metadata still used configured DCP4, so the view was sized as one times 12,288 while its map addressed four shards. The initial d3 repair forwarded the getattr(config, "decode_context_parallel_size", 1) expression then present in the non-PP branch; the current implementation reads the Config field directly in the unified initializer.

The regression executes both real setup function bodies, including the callee's actual default, while recording device/process-initialization boundaries. It covers both PP2/DCP4 stages, default DCP1 and unchanged non-PP DCP4. These are source-backed CPU checks, not numerical stand-ins for GPU groups or complete module/GPU validation.

Prior CPU and reader evidence remains at 71a6. The earlier corrected-reference initialization failure retains timed N=0 and an unstarted candidate. The original unmodified-main failure and older observations keep their own sources and limits.

The subsequent paired run used corrected main 3b3c844ce449bcefec35d819efb9993cad57e169 versus d3, with the same startup group observer. Both five-phase protocols completed with actual PP2/TP4/DCP4 groups and 49152+512 forwards, but all five corresponding output tokens differed. All-rank traces confirm matching explicit active bank counts and written-prefix payloads; these shape facts do not establish finite values or performance gains.

The separate single-reference sampler run at execution 832b294c captured full original-dtype logits before constraints and at the real sampler: all 163840 BF16 values are NaN on each last-stage rank, followed by actual token 0. Its protocol completed and cleanup passed; model numerics failed. The next bounded observation at 051f63e8 retained all 372 first-chunk layer returns and independently verified layer 55 finite, then layer 56 prefix/routed/shared all NaN while its five live bank slots stayed finite and unchanged. The bank becomes nonfinite at the next block close. These are last-row observations, not an all-token or first-kernel proof.

The latter diagnostic's inner-model post-hook was bypassed by decorated __call__. Its stale observer state rejected the expected second chunk; stage exits, final norm and new sampler rows were not captured, and the client deadline ended the failed protocol with owned cleanup. This tool error is preserved separately from the numerical finding. Fresh request history and D2H synchronization remain explicit limits. That diagnostic introduced no candidate rerun, changed precision/chunk, mathematical fix or extra matrix. Current follow-up is reviewer disposition under the implemented written-prefix alternative.

ZhiweiYan-96 and others added 9 commits November 8, 2026 20:45
…nts are enabled

Several attention kernels route discarded lanes through block 0 (the
block-table zero-padding target): sparse-index gather writes 0 for
out-of-range top-k entries, the indexer's masked prefetch lanes read
there, and DSpark pad rows point there. This is safe while block 0
holds ordinary fp8 KV, but PAGE state checkpoints store fp32/bf16
state bytes into KV-pool blocks, and the min-heap allocator hands out
block 0 first. When block 0 is a checkpoint unit, those "harmless"
reads see fp8 NaN codes (0x7F/0xFF from the raw state bytes), poisoning
the attention row. Under DSpark verify with prefix caching this caused
garbled tool-call output on ~62% of affected DeepSWE tasks.

Fix: BlockPool.reserve_null_block() removes block 0 from the free set
before any allocation. Called by BlockManager when PAGE checkpoints are
enabled. Cost: one block out of thousands.
Use allocatable block capacity for admission, limits, occupancy, and watermarks. Reserve the padding block whenever PAGE state storage exists, including when prefix caching is disabled, and keep the physical address bound for deferred-block accounting.
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every eligible PR before approval:

  • ✅ Pre Checkin: Black, Ruff, catalog schema validation, non-GPU unit tests

Heavy model tests:

  • ✅ Gate checks are published on every PR so required checks do not stay missing
  • ✅ Expensive jobs run only after the PR is approved, or when a matching ci:* label is present
  • ✅ Pre Checkin must pass before approved heavy jobs continue
  • ✅ Without a matching label, expensive jobs also require a relevant path
  • ✅ A matching ci:* label is an explicit request and can open the gate even when paths would otherwise skip it

Path scope:

  • Native ATOM, vLLM, and SGLang use ignore lists: docs/markdown and unrelated plugin or Mesh paths are skipped
  • ATOMesh uses an include list: Mesh code, ATOMesh scripts/workflows/catalogs, OpenAI entrypoints, and Slurm helpers
  • Relevant path alone does not start expensive jobs; approval still opens the automatic path-scoped gate
Label Tests
ci:full Run all heavy PR model tests: native ATOM, vLLM, SGLang, and ATOMesh
ci:atom Run native ATOM model accuracy tests
ci:vllm Run ATOM vLLM OOT model accuracy tests
ci:sglang Run ATOM SGLang model accuracy tests
ci:mesh Run ATOMesh accuracy/benchmark gates for Mesh-related changes

Without a matching ci:* label, heavy jobs are skipped when the path is not relevant or the PR is not approved.
Add labels via the sidebar or gh pr edit 3577 --add-label <label>

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

some changes needed..

real kimi-k3 pp run for the bank transport across pp boundaries?

ci green.

Comment thread atom/model_ops/attention_residual.py Resolved
Comment thread atom/models/kimi_k3/model.py Resolved
@ganyi1996ppo

Copy link
Copy Markdown
Contributor

Review notes (read of the diff only; no GPU run)

1. as_strided ignores the bank's own storage offset (attention_residual.py::maybe_close_block)
start = layer_idx // block_size * slot_stride is an absolute storage offset. In eager the storage_offset() == 0 assert protects it, but under compile that assert is skipped (to avoid the Dynamo issue). If a compiled producer ever hands in a bank that is a slice of a larger buffer (non-zero offset, e.g. the row-sharding successor PR mentioned in the description, or a sliced PP receive buffer), the copy lands in the wrong place silently. Can this be made structurally safe, e.g. by computing the start from block_residual itself or by asserting at the allocation/receive site rather than relying on a convention?

2. PP transfer volume
Before, a stage sent only the closed candidates [T, k, H]; now block_residual is always the full [T, blocks, H] bank, including unwritten new_empty slots (uninitialized memory) and the zero-filled receive buffer. The description lists actual PP execution, transport and slicing as untested. Could we confirm that the bytes sent per boundary and the receive-buffer contract are what is intended, and test one real PP>1 forward?

3. Memory
The bank is allocated at full size at the start of every forward instead of growing, so early layers hold more memory than before, which matters at ctx=49152. The memory/copy-time result is still "Pending" in the description; please fill it in before landing.

@whx-sjtu
whx-sjtu marked this pull request as draft November 20, 2026 06:29
@whx-sjtu
whx-sjtu marked this pull request as ready for review November 20, 2026 07:25

@valar-cop valar-cop left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

LGTM

ci Offline inference smoke test failed — not sure yet (low): The job log is 0 bytes so the cause cannot be read. The job serves meta-llama/Meta-Llama-3-8B-Instruct, while this PR touches only Kimi-K3 paths (plus a pp_comm comment and the pre-checks dependency line), so a PR cause is unlikely, but it is unconfirmed.

(job log .valar/ci/job_136149113123.log is empty, 0 bytes)

ci ATOM Test Gate failed — not sure yet (medium): Gate log is empty. By .github/actions/evaluate-test-gate it fails when its optional offline-smoke-test is neither success nor skipped, so it is plausibly a cascade of the failing smoke job; the same gate also failed twice on recent main runs.

@whx-sjtu

whx-sjtu commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Part of #3577. For the offline-smoke question, the step log shows the rocm/atom-dev:latest image pull failed with docker: unauthorized: authentication required before model execution. The gate then reports offline-smoke-test=failure. This run did not validate inference; the underlying registry-authorization cause remains unknown.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (6)

  1. Delete the mono copy of KimiDecoderLayer.forward now that the cat is gone. The PR removes the only stated reason for the copy (old mono/runner.py:24-28) but keeps it and rewrites its docstrings. _fallback (atom/models/kimi_k3/mono/runner.py:578-592) is bit-equal to layer.forward(positions, prefix, blocks, add, add2)[:3] on every layer of the 25-layer test harness. Call .forward so the DSpark hook does not fire twice; _write_aux already covers the tap. Also reuse the new helpers instead of hand copies:
    • runner.py:459 → self.inner.block_bank(prefix), then drop num_blocks() (mono/config.py:217).
    • runner.py:584 → maybe_close_block.
    • aggregate_hidden_state (model.py:1843-1855) → res.window(block_residual). Its shape[1] < num_blocks guard can no longer fire.
  2. Post the PP and memory numbers, or ship only the written prefix. At head every PP boundary clones and sends the full [T, ceil(L/bs), H] bank, unwritten new_empty slots included (pp_comm.py:160-170). Before, it sent [T, k, H]. That is 2× the bank bytes at a PP2 split of 61 layers (1.75× of the total payload), and 2× at PP4. On the vLLM plugin, make_empty_intermediate_tensors (model.py:1932) now holds a persistent [max_num_tokens, 6, H] buffer on each non-first PP rank: about +1.17 GB at 16384 tokens. This PR is motivated by memory and copy cost, yet the body says ctx=49152 memory/copy is "Pending" and no PP numbers exist. valar-cop's thread at model.py:1974 and ganyi's asks are still open. Either trim to bank[:, :ceil(end_layer/bs)] and re-pad on receive, or post a PP2 before/after (bytes, clone/send time, E2E) plus ctx=49152 peak memory.
  3. Remove the per-call window() slice cost on eager forwards. Each AttnRes.forward now builds a bank[:, :k] view (attention_residual.py:174,204-209), which is about 123 views per forward. In-process CPU A/B (base vs head on one pinned core, with base/base and head/head controls) measured +230 µs per eager forward at L=61, T=1-16. That cost lands on every PP>1 run, because PP forces eager (model_runner.py:1517, and the PP2 recipe in recipes/Kimi-K3.md passes --enforce-eager). Fix: pass the slot count to ATOM's own apply_attn_res and let it read the bank by stride, or precompute the bound in __init__. Then show the eager A/B.
  4. Fix the stale comments. These clauses are no longer true:
    • attention_residual.py:115-116 "Set on a site handed the whole bank": output_attn_res gets the whole bank and has no block_size, while mono hands the decoder sites pre-sliced banks.
    • attention_residual.py:59 and :71: the candidates are now window(block_residual), and only the window can be empty (layer 0).
    • model.py:1716 "Only this site banks the running prefix": mlp_attn_res now also gets block_size. Say that only this site calls maybe_close_block, and that the MLP site's layer_idx is shifted by one for its window.
  5. Add a test that runs KimiLinearModel.forward. Reverting model.py:1974 to new_zeros(T, 0, H) still passes the suite, because no test drives either forward's bank allocation. Add the test to tests/model_ops/test_kimi_k3_attn_res_bank.py, which runs in the CPU lane: stub stack, first and last PP rank, compared with _cat_reference.
  6. Correct the PR description. "Preserve … the existing PP protocol" is false: the payload changes from [T, k, H] to [T, ceil(L/bs), H], and the vLLM placeholder changes from 2-D to 3-D. Since the head fixes vLLM K3 PP (base copied [T, k, H] into a [T, H] buffer), say so.

Pre-existing (not required for this PR): einops is imported at top level by kimi_k3/model.py and five other modules, but it is missing from pyproject.toml dependencies. The pre-checks pip line is a workaround.


Reviewed at beec9b6 (Deep; 3 hunters, 3 verifiers, C2). Already fixed: the sliced-bank absolute-offset write (valar-cop thread 1). CI: Offline smoke failed on a docker pull unauthorized, which is infra and not this PR; heavy model jobs were skipped.

@valar-cop

valar-cop commented Nov 20, 2026 •

Copy link
Copy Markdown

@whx-sjtu whx-sjtu left a comment

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.

ATOM PR #3577 — Bounded residual-bank reads and PP prefixes

Reuses native Mono forwarding, sends only written pipeline prefixes, and bounds residual reads without per-site views.

Review: ✅ LGTM for source/CPU corrections at 1e2ef92d14d387a47ffe8be3078a456f60f22a01; all six native review requests are addressed in source/tests. Native CHANGES_REQUESTED and hold landing remain; this is not formal or GPU approval.
Coverage: 8 files / 143 added lines -- within one review pass
Validation (advisory): Reviewer Windows Torch 2.10 CPU: 127 passed, 44 skipped; all eight bounded regression controls fail at the expected checks, without setup errors. One run, this box, unverified. Author CPU A/B source hashes and raw paired medians were checked; removal of prior eager-view overhead is supported. Actual GPU compilation, PP2/TP4, GSM8K, ctx=49152 memory/copy/send/E2E timing and final-tree qualification remain open.

Correction scope and integration boundaries

Mono calls layer.forward directly, shares block_bank, and keeps one manual auxiliary tap. Aggregate extraction uses the successor window with short-bank rejection. Native and plugin PP forwards share contiguous written-prefix sends, receiving-capacity reconstruction and stage-specific three-dimensional placeholders. The PR explicitly records the pre-existing vLLM placeholder correction.

AttnRes precomputes active counts. Ordinary, add, quant and add-quant real/fake APIs all carry num_blocks; None preserves existing full-bank callers. The checked-in tests execute native model/module paths with numerical stand-ins, plus the plugin/Mono production bodies through their documented engine/FlyDSL-free adapters. In-memory controls cover both forward allocations, PP payload/reconstruction/placeholders, adapter and kernel counts, and duplicate Mono hooks. Repository source bytes remain unchanged.

Author measurements use actual eager model/decoder bodies with no-op numerical operators on one pinned CPU core. Saved source hashes match ceee/beec/1e2 with Windows line endings; reported medians recompute from paired samples. No stable single-token gain over the original base or GPU/model gain is claimed.

Future B integration must carry both its gather-owner argument and num_blocks through combined add/add-quant consumers; C must preserve the count and allocation contracts. Their future merged runtime is outside this review. Formal native review disposition remains with the maintainer. The existing Linux run is 44737768368; historical GPU/smoke evidence is not transferred to this head.

@whx-sjtu
whx-sjtu marked this pull request as ready for review November 20, 2026 13:08
@whx-sjtu

whx-sjtu commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Part of #3577. The six requested source/test corrections are implemented at 1e2ef92: shared Mono forwarding/allocation, written-prefix PP transport, cached residual counts without per-call slices, corrected comments, both forward-allocation regressions, and the corrected PP description. Scoped review records the CPU controls and eager A/B removing the previous head's view overhead. Current PP and memory answer preserves the remaining numerical limitation.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (1)

Thanks, all three items from our 0915e4a review are fixed at 7698b4a, and the main merge is clean. One item is left, and an earlier round should have raised it:

Nit (still needs a change):

  1. Give the three new test files the full three-line header required by CLAUDE.md.
    • Files: tests/model_ops/test_kimi_k3_attn_res_bank.py:1, tests/model_ops/test_kimi_k3_attn_res_dispatch.py:1, tests/test_model_setup_dcp.py:1.
    • Each one carries only # SPDX-License-Identifier: MIT.
    • CLAUDE.md "Critical Rules" (CLAUDE.md:194-200) says every new file gets all three lines, so add these two after the SPDX line:
      # Copyright (C) 2026, Advanced Micro Devices, Inc. All rights reserved.
      # Copyright (c) 2026 ATOM Project Contributors
      
    • The rule was already in the tree at 0915e4a; we missed it last round, sorry.

Not blocking: the reference PP run's NaN logits and the unmeasured PP gains are disclosed in the body. Our earlier PP ask allowed the written-prefix alternative you shipped, and the CPU tests show the bank path bit-equal to the torch.cat loop. Please keep the squash message exactly as in the description; it now matches the code.


Reviewed at 7698b4a (Deep re-review; 1 hunter, 1 verifier; delta 0915e4a..27e7369 plus main merge 659c3ba). Already fixed: r1124 #1 (model_setup.py:122 and :139 read config.decode_context_parallel_size directly; tests/test_model_setup_dcp.py passes 4/4, and dropping the kwarg fails 3), #2 (model.py:1833 and mono/runner.py:24-28 now describe the in-kernel close and the layer-0 fallback correctly), #3 (the squash text names the vLLM PP placeholder fix and the PP+DCP init fix; every clause checked against the code). All review threads are resolved. CI: CPU, Black, Ruff and smoke are green; heavy Kimi jobs were not run.

@whx-sjtu

Copy link
Copy Markdown
Contributor Author

Ready for re-review, @valarLip. Could you take another look at the header and initialization fixes and validation?

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (1)

Thanks: the three test headers now match CLAUDE.md exactly, and the re-base onto main's unified init_model_env is correct. One squash-text item came from the main merge:

Nit (still needs a change):

  1. Update the PP+DCP paragraph of the squash message. Main's #3355 (aec84b1) replaced the two init_model_env branches with one init_pp_aware_dist_env call that already forwards decode_context_parallel_size. After the merge, this PR's only change there is getattr(config, "decode_context_parallel_size", 1) → config.decode_context_parallel_size (atom/model_engine/model_setup.py:116).
    • "Initialize PP groups with config.decode_context_parallel_size so PP+DCP group width matches metadata" now credits this commit with a fix main already made, and "in both PP and non-PP initialization" names two calls that no longer exist.
    • Suggested: "Read the required Config field decode_context_parallel_size directly in init_model_env instead of through a getattr default."
    • This replaces the PP+DCP clause our 0915e4a review asked for; main changed under it. Only the squash message needs this.

Reviewed at 8839a3a (delta re-review 7698b4a..8839a3a incl. main merge; passes A+B, both 1 Nit). Already fixed: r1124b #1 (all three new files, the only new files in the PR, carry the exact three-line header). tests/test_model_setup_dcp.py runs the real setup bodies, passes 4/4, and dropping the DCP kwarg fails 3. All review threads are resolved. CI: CPU (16498 passed), Black, Ruff, smoke and the heavy Kimi-K3 accuracy jobs incl. DSpark PP2 pass; 5 heavy jobs still pending.

@whx-sjtu

Copy link
Copy Markdown
Contributor Author

Ready for re-review, @valarLip. Corrected the squash message to:

Read the required Config field decode_context_parallel_size directly in init_model_env instead of through a getattr default.

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

Thanks for the work here. I traced the read bounds, the PP written-prefix send/receive and the in-kernel close, and found no concrete bug. Two non-blocking asks:

  1. Kernel timing for the int64 change (inline comment below).
  2. Real-model equivalence: the CPU tests compare the bank path against the torch.cat loop, and the 4 GPU cases cover the close kernel, but no real-model run covers the bank. Since the PP reference currently gives NaN logits (as described in the PR), could you share one non-PP run (e.g. TP8) comparing base vs this head, greedy and token-for-token? One such run would upgrade the evidence from CPU-only to real-model.

CI note: the red Check Pre Checkin Signal / ATOM Test Gate look infra. The failing step is Wait for Pre Checkin workflow, which logs "Failed to read Pre Checkin status after 40 attempts", while the Pre Checkin run for this head (45741144646) completed with success. A rerun of ATOM Test should clear it.

# outputs unsummed and skip an entire [T, H] elementwise kernel.
t = tl.program_id(0)
# Bank strides can place live rows or blocks past 2**31 elements.
t = tl.program_id(0).to(tl.int64)

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.

Question / suggestion (not blocking): program_id(0) and o_l are now int64 for every launch, including decode with small T where T * stride_bank_t cannot come close to 2^31. Could you share a kernel before/after timing at T=1..64 (a small microbenchmark is enough)? If there is a cost, the int64 path could be selected by a constexpr that is true only when T * stride_bank_t can overflow int32.

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.

@ganyi1996ppo, neither measurement is available yet. The prepared small-T test compares the index widths only where all offsets fit int32. The non-PP test compares base/head using the same runtime, four fixed prompts and TP8/PP1 greedy decoding. I will report both as non-blocking follow-ups; the latest green workflow skipped model execution.

@whx-sjtu whx-sjtu removed the agent-team/hold-landing Holds landing only; development and review go on label Nov 26, 2026
block_residual
if block_residual.stride(-1) == 1
else block_residual.contiguous()
else block_residual[:, :B].contiguous()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

...

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.

@valarLip Removed the copy fallback in 0b6e5bae8b: the original bank is passed directly, with a unit-H-stride guard. Token/block strides and storage offsets are retained. The focused CPU checks passed all 72 tests; the GPU module was skipped.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

⚠️ Action required before merge (1)

The squash sentence from our last round is fixed and the new head is only a main merge; CI is green, including Kimi-K3 TP8, DSpark, DSpark PP2 and K3.1-Pro.

  1. Remove the copy fallback at attention_residual.py:298-302 (this is the inline question on that line). Every caller passes the bank from KimiK3Model.block_bank (model.py:1946), which is hidden_states.new_empty(tokens, blocks, hidden), unit-stride in H; the mono runner (mono/runner.py:467) uses the same allocator. So block_residual.stride(-1) != 1 never happens in production and the block_residual[:, :B].contiguous() branch is dead. Pass block_residual straight through (raise if the H stride is not 1, if you want a guard), and drop any test that only exists to exercise the copy.

Reviewed at e5a5962 (delta since 8839a3a is a main merge only). Prior ask (squash text) verified fixed. Not raised: the int64 offsets at :130/:167 (needed past 2**31, unmeasured, already tracked as a non-blocking thread).

@whx-sjtu

whx-sjtu commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Ready for re-review, @valarLip. 0b6e5bae, unchanged at c26e607c, removes the dead copy fallback and preserves supported bank strides. All 72 focused CPU checks, Black and Ruff passed.

Local PP2 evidence: candidate 1268/1319 flexible matches (0.961334); main 1261/1319 (0.956027), both above 0.94. Different nodes; the original CI failure, 1234/1319 (0.935557), remains unexplained.

Local accuracy scope

Full GSM8K 3-shot, Kimi-K3 DSpark TP4/PP2, eager. Tested candidate c8dd8112 has the identical full tree as PR head c26e607c; reference is main 6180dbcf. The pinned base image, exact AITER wheel, observed versions, checkpoints, dataset, recipe and seeds match. Prepared runtime images and physical nodes differ. No same-node A/B, causal or performance claim; formal review and CI requirements remain.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ LGTM

The copy fallback is gone: _apply_attn_res_impl now passes block_residual straight to the kernel with its own strides and raises if the hidden dimension is not unit-stride (attention_residual.py:296-297). Every bank still comes from block_bank (model.py:2250, new_empty(tokens, blocks, hidden)) or its contiguous PP prefix (block_bank_prefix, :2263), used by the native model, the vLLM plugin and the mono runner, so the guard never fires in production. The strided-H tests that only exercised the copy were dropped, and the bank-view tests now use non-contiguous views that keep H unit-stride (storage[1:-1, 1:4, :8]), so the in-place write path is still covered. tests/model_ops/test_kimi_k3_attn_res_dispatch.py passes on CPU (25 passed); non-GPU CI is green; the GPU accuracy jobs were still pending at review time.

Root cause vs patch

Root problem: the residual bank was re-allocated (and re-copied) per layer block. Allocating it once per forward and having the fused kernel read and write the active prefix by stride removes the copies at the source; with the dead copy branch removed, nothing patch-like is left. Verdict: root fix.

Prior asks (e5a5962): remove the block_residual[:, :B].contiguous() fallback, fixed (above).


Reviewed at 529fb14 (re-review, two independent passes; delta since e5a5962 is the fallback removal and its tests). Already fixed: squash text, copy fallback. Not raised: the int64 offsets (tracked as a non-blocking thread).

@valarLip valarLip added the LGTM waiting pass for CI label Nov 27, 2026
@whx-sjtu

Copy link
Copy Markdown
Contributor Author

@zhuyuhua-v
zhuyuhua-v merged commit 380aeb8 into main Nov 27, 2026
179 of 185 checks passed
@zhuyuhua-v
zhuyuhua-v deleted the task-3312-bank-cpu-20261119 branch November 27, 2026 14:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci:atom LGTM waiting pass for CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants