Skip to content

loom: the handover's epoch chunking and control words, as arithmetic (engine#3157, L4) - #3170

Merged
bong-water-water-bong merged 2 commits into
mainfrom
cl-hrxnan/3157-epoch-driver
Nov 21, 2026
Merged

bong-water-water-bong merged 2 commits into
mainfrom
cl-hrxnan/3157-epoch-driver

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs #3157 (L4, part 2). The layout merged as dc0ad4431; this is the driver arithmetic between that layout and a real handover run.

Why the chunking is forced, not chosen

$ loom-link --print-config-schema <card>/program/llm.loom
llm.context        required  range 16 … 262144
llm.spans          required  range  1 … 8192
llm.tokens         required  range  1 … 8192
llm.epoch_spans    required  range  1 … 8192
llm.epoch_tokens   required  range  1 … 8192

An epoch carries at most 8192 tokens and the context may be 262144 — a full prompt is 32 epochs. And the position that places KV is word 0 of the caller-owned control block, absolute, not epoch-relative: kernel/attention_decode.loom:104 loads it, :108 multiplies it into %token_cache_base, and kernel/decode_control.loom:54-59 sets it to position_base + token_count when a prefill finishes. So a handover is a sequence of epoch-sized writes whose bases advance by the full limit, ending with a decode block at base + tokens.

What app/loom_epoch_driver.h adds (93 lines, arithmetic only)

  • epoch_count(tokens, limit) — with epoch_count(0) == 1 deliberately: a zero-token handover is the zero-length qwen38_prefill_finish_control path that establishes the decode position without writing a cache byte, so returning zero epochs would skip the only thing that sets up decode.
  • epoch_at(i, base, tokens, limit) — base advances by the full limit, so a short final epoch keeps its absolute position: position is a property of the token, never of the chunk index.
  • prefill_control_word / decode_control_word / handover_position — both ABIs from the library's field order. Word 2 (eos) is deliberately not computed: it is the caller's on both ABIs, and inventing a value is the class of silent wrongness the merged layout header documents.
  • kEpochTokenLimit (8192) and kContextCeiling (262144) as the card's bounds, next to the sources that state them.

The test (33 assertions, device-free)

Literals for both bounds; epoch counts for exact multiples, remainders, one token, zero; epoch shapes with a non-zero base (a handover into a session that already decoded); both control ABIs' words; and the zero-token finish not advancing the position. The arm that matters most is the sweep:

0…40 000 tokens × limits 1/3/9/…/8192 — every epoch's token counts sum exactly to the handover length, each epoch starts where the previous base + limit lands (no gap, no overlap), and no epoch exceeds the limit.

That is the arm that catches a driver which rounds, drops the tail, or overlaps chunks — none of which the per-case assertions can see.

Verified

$ g++ -std=c++17 -Wall -Wextra -Iapp -o /tmp/led tests/loom_epoch_driver_test.cpp   # clean
$ /tmp/led   → 33 ok, 0 FAIL, "loom_epoch_driver_test: pass"
$ bash scripts/pre-pr-checks.sh --base origin/main → all 15 check(s) green, 2 skipped, 0 could-not-tell, rc 0
$ python3 tools/copyright.py --check → rc 0

add_dependencies(onebit loom_epoch_driver_test) is in the CMake row, because ci.yml builds onebit and an add_test alone never reaches ctest there — the gap #3159 needed fixing, applied pre-emptively.

What this does not do

No device run, no claim about speed, no routing change: it is the chunk arithmetic a hybrid driver needs, testable before anything touches memory. The gate (#3158) remains L4's next obligation, and it is a measurement.

Citations are by symbol rather than line number on purpose — program/control.loom's offsets differ by card (+8 in the UD-Q4_K_XL card vs the other three we hold), so line numbers are not portable across cards and a reviewer should not have to discover that again.

(engine#3157, L4)

app/loom_kv_layout.h (merged, dc0ad44) says where Loom's state lives.
This says in what chunks a handover fills it and what the control block says
between chunks -- the driver arithmetic that sits between the layout and a
real run, and the part of #3157 item 4 that was still prose.

Two facts from the shipped card force the shape:

- A Loom epoch carries at most 8192 tokens. `loom-link --print-config-schema
  <card>/program/llm.loom` reports llm.spans / llm.tokens / llm.epoch_spans /
  llm.epoch_tokens as `required, range 1..8192`, while llm.context is
  `range 16..262144`. So a full-context prompt is 32 epochs, not one.
- The position that places KV is word 0 of the caller-owned control block,
  absolute and not epoch-relative (kernel/attention_decode.loom:104,108;
  kernel/decode_control.loom:54-59 sets it to position_base + token_count).

So a handover of N tokens at base B is epochs at B, B+limit, ... summing to N,
after which the decode form carries position B+N. This header is that
arithmetic and nothing else: no device, no Loom, no runtime.

Details that are decisions rather than transcription:
- epoch_count(0) == 1, not 0: a zero-token handover is the zero-length
  qwen38_prefill_finish_control path that establishes the decode position
  without writing a cache byte, so a driver that returns no epochs would skip
  the only thing that sets up decode.
- an epoch's base advances by the FULL limit, so a short final epoch keeps its
  absolute position: position is a property of the token, never of the chunk
  index.
- word 2 (eos) is deliberately not computed here -- it is the caller's on both
  ABIs, and inventing a value for it would be the kind of silent wrongness the
  merged layout header documents.

33 assertions: the two bounds as literals, epoch counts for exact multiples /
remainders / one token / zero, epoch shapes with a non-zero base, and a sweep
(0..40000 tokens x limits 1/3/9/.../8192) asserting exact coverage, no gap, no
overlap and no epoch over the limit -- the arm that catches rounding, a dropped
tail or overlapping chunks. Plus both control ABIs' words from the library's
field order, and the zero-token finish not advancing the position.

Header-only, -Wall -Wextra clean, gate 15 green / 2 skipped / 0 could-not-tell,
and the target is a build dependency of `onebit` so ci.yml's build actually
runs it (the gap #3159 needed fixing).
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 3170

"The chunking is forced, not chosen" — with the command that shows it ($ loom-link --prin…). That is the distinction this field needs: a design that says "I chose to chunk" invites a reviewer to ask why not once; a design that says "the tool emits N and the runtime takes M, so it must be split" is a fact about two artefacts, and the only remaining question is whether the split is correct.

And it follows the merged layout rather than inventing one: #3159's header landed as dc0ad4431, and this is "the driver arithmetic between that layout and a real handover run" — which is the right order. Layout first (testable as arithmetic, device-free), driver second (the same arithmetic, against a real epoch). A driver written before the layout would have discovered the layout.

Four asks:

  1. the arm must be the boundary of the split — a payload that is exactly one chunk, one byte over, and one byte under. The forced-chunking argument is about sizes, so the failure it can hide is an off-by-one at each boundary, and a 232-line driver with one arm in the middle tests none of them;
  2. loom-link's emitted numbers belong in the header as static_asserts, the same ask I made on loom: the hybrid handover's state layout as arithmetic, with a device-free test (engine#3157, L4) #3159: if the tool emits a chunk size and the runtime takes a capacity, a mismatch should be a build error, not a wrong number at handover — and that is the one class of bug this pair of PRs can introduce that no test would catch, because both sides would be "correct" against their own constant;
  3. say what an epoch boundary does to the GDN state — the recurrence carries a gdn_state root per ordinal (from loom: the hybrid handover's state layout as arithmetic, with a device-free test (engine#3157, L4) #3159's table), and a chunk boundary inside a recurrence is exactly where a state copy is either required or a bug. One line: "the chunk boundary is only taken between epochs, because …" or "inside a recurrence, and the state is copied because …";
  4. and the control word (in the title, not yet in the body) needs the same treatment — who writes it, who reads it, and what happens if the reader sees a word from a previous epoch. That is a generation counter by another name, and a generation that is not checked is a stale-read waiting for a slow launch.

On the shape: +232 across app/loom_epoch_driver.h, its test and CMakeLists.txt, Refs #3157 (L4 part 2). Device-free arithmetic again, which is why this pair can land before any Loom run exists.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at ec019cf: READY. I built and ran it, and — because its load-bearing claim is about a kernel, not about its own arithmetic — I checked the four citations against the Loom sources on this box.

Ran

g++ -std=c++17 -O1 -Iapp over app/loom_epoch_driver.h + tests/loom_epoch_driver_test.cpp → rc 0, test pass, all arms ok, including the two that pin the end state (decode word 0 is the absolute position after the handover (18432), a zero-token handover leaves the position where it was (2000)).

The premise, verified at source (hrx-loom-library, Qwen3.8-27B card)

The whole design rests on "the position is absolute, not epoch-relative", and that is four lines of Loom, all of which say exactly what the PR claims:

model/Qwen/Qwen3.8-27B/program/kernel/attention_decode.loom:104
    %position_i32 = view.load %control_view[0]            <- word 0 IS the position
:105  %position = index.assume %position0 [range(%position0, 0, 262143), lt(%position0, %cache_capacity)]
:108  %token_cache_base = index.mul %position, %c1024     <- used DIRECTLY as the KV offset
model/Qwen/Qwen3.8-27B/program/kernel/decode_control.loom:54-59
    %next_position = scalar.addi %position_base, %token_count
    view.store %next_position, %control_view[0]           <- the block advances it by the token count

So a handover really is a sequence of writes whose bases advance by whole epochs, and the only arithmetic the driver has to get right is the chunking and the three control words — which is precisely what this header is. range(…, 0, 262143) also corroborates the "context up to 262144" figure independently of the schema.

What I could not verify, and the reason is itself worth knowing

The loom-link --print-config-schema table (llm.context 16…262144, llm.epoch_tokens 1…8192, …) I take as stated: the loom-link on this box cannot parse that card —

~/.cache/scratch-cl-hrxkern/loom/qwen38-27b/program/llm.loom:94:18: error [PARSE/006]: unknown op 'vector.constant'

— i.e. a toolchain-version skew between the local loom-link and the card's dialect. That is exactly the class of drift config/loom.config and loom_pin_check.py (engine#3160, merged this morning) exist to make visible; it is not a defect of this PR, and I am not asking for anything about it here. If the schema numbers ever need re-deriving, loom-link at the pin will do it.

One consequence I did check while I was there: 18432 = 8192 + 8192 + 2048 — three epochs, the last partial, which is the shape the chunking has to produce for a non-multiple-of-8192 prompt. The test asserts that end position rather than an epoch count, which is the right invariant (the count follows from it).

Not checked: anything against a real handover run — this is arithmetic, and a device run is L4's next step, not this PR's.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT at ec019cf: READY

Three files, +232, arithmetic only. Built and run at this head, and every source claim in the body checked against the card and the library rather than taken on trust.

Measured

$ git rev-parse --short HEAD                 → ec019cf6c
$ ninja -C build1336 loom_epoch_driver_test  → builds
$ ./build1336/loom_epoch_driver_test         → 33 ok, 0 FAIL, "loom_epoch_driver_test: pass"
$ pre-pr-checks --base origin/main           → rc 0, 15 green / 2 skipped / 0 could not be told

The claims behind the arithmetic, re-derived

  • The epoch limits are the card's, from bartowski-Qwen3.8-27B-loom/program/llm.loom:
    @llm.context range(16, 262144), @llm.spans, @llm.tokens, @llm.epoch_spans, @llm.epoch_tokens all range(1, 8192). So "an epoch carries at most 8192 tokens and the context may be 262144" is the card's own bound — 32 epochs for a full context, which is the number the driver's chunking has to produce.
  • The position is word 0 and it is absolute, which is what makes "bases advance by the limit" the right rule rather than a choice: kernel/attention_decode.loom:104 loads %control_view[0] as the position and :108 multiplies it into %token_cache_base — the citation is exact.
  • The finish conversion is the library's, not the driver's: kernel/decode_control.loom:54-59 computes position_base + token_count, stores it to word 0 and sets word 1 to 1. The test's two arms (decode word 1 is generated_count = 1 after a handover, a zero-token handover leaves the position where it was) are that sentence, checked.
  • epoch_count(0) == 1 is asserted deliberately and the test carries it (and its single epoch carries no tokens), which is the case a caller is most likely to get wrong in the other direction — a zero-token handover that decides to produce no epoch at all would leave the position unadvanced and no control block to finish.

What this is not

It is arithmetic between the merged layout (dc0ad4431) and a handover run: no device, no Loom, no card is opened, and the PR says so. It also does not decide the %control ownership question (#3157's open question 1) — it takes the two ABIs the library already writes and derives the chunking they imply, which is the right order.

Gate is green and the row is registered through add_dependencies(onebit …) the way ci_targets_check wants, so it will exist in the configuration CI builds rather than being a target nobody compiles.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

PR Reviewer Guide 🔍

(Review updated until commit c69e34d)

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

3157 - Partially compliant

Compliant requirements:

  • Implementation of epoch chunking logic based on Loom's card configuration limits
  • Arithmetic implementation of control words for handover between prefill and decode phases
  • Header-only implementation that can be tested without device or Loom presence
  • Zero-copy mechanism for KV buffer handover

Non-compliant requirements:

  • None

Requires further human verification:

  • Verification that the handover mechanism works correctly with actual Loom hardware
  • Performance and accuracy testing of the Loom route vs fallback

3158 - Partially compliant

Compliant requirements:

  • None

Non-compliant requirements:

  • The gate testing has not yet been performed due to toolchain blockers

Requires further human verification:

  • Performance and accuracy testing of the Loom route vs fallback
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Epoch Counting Logic

The epoch_count function handles the special case of zero tokens by returning 1, which is necessary for the zero-length finish path. However, this behavior should be clearly documented as it's not immediately obvious from the function name and implementation that it's specifically handling the zero-token case for the finish path.

inline constexpr uint64_t epoch_count(uint64_t tokens, uint64_t limit = kEpochTokenLimit) {
    if (limit == 0) {
        return 0;
    }
    if (tokens == 0) {
        return 1;
    }
    return (tokens + limit - 1) / limit;
}
Control Word Calculation

The prefill_control_word function returns 0 for word 2 (eos) which is correct for the caller's responsibility, but the function signature and implementation could be clearer about which words are handled by the driver vs. which are handled by the caller.

// Words of the control block, in both ABIs the library uses over the same storage.
inline constexpr uint64_t prefill_control_word(uint64_t epoch_index, uint64_t base_position, uint64_t tokens,
                                               uint64_t word, uint64_t limit = kEpochTokenLimit) {
    const Epoch e = epoch_at(epoch_index, base_position, tokens, limit);
    // 0 = token_count, 1 = position_base (kernel/decode_control.loom:49-51)
    return word == 0 ? e.token_count : (word == 1 ? e.position_base : 0);
}

inline constexpr uint64_t decode_control_word(uint64_t base_position, uint64_t tokens, uint64_t word) {
    // 0 = position, 1 = generated_count (kernel/decode_control.loom:17-19); a handover leaves 1 generated token
    return word == 0 ? handover_position(base_position, tokens) : (word == 1 ? 1 : 0);
}

@github-actions

Copy link
Copy Markdown

Persistent review updated to latest commit c69e34d

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

VERDICT at c69e34d: READY

Built and ran it at this head, and — because every number in this header is a claim about artifacts, not about its own arithmetic — checked the claims against the card and the library rather than against the body.

$ g++ -std=c++20 -I app tests/loom_epoch_driver_test.cpp -o led && ./led
… 33 × ok, "loom_epoch_driver_test: pass", rc 0

The three citations, resolved in the sources

kernel/decode_control.loom on Qwen3.8-27B (library copy):

:17-19   view.load %control_view[%c0] -> %position ; [%c1] -> %generated_count ; [2] -> %eos_token
:49-51   view.load %control_view[%c0] -> %token_count ; [%c1] -> %position_base ; [2] -> %eos_token
:54-59   %next_position = scalar.addi %position_base, %token_count
         view.store %next_position, %control_view[%c0]      ; position := base + count
         view.store %c1_i32,        %control_view[%c1]      ; generated_count := 1
kernel/attention_decode.loom:104,108
         %position_i32 = view.load %control_view[0] … %token_cache_base = index.mul %position, %c1024

So the two field orders are different and the header has both right — prefill [token_count, position_base] (prefill_control_word), decode [position, generated_count] (decode_control_word) — and handover_position = base + tokens with generated_count = 1 is :54-59 verbatim, not a choice. attention_decode.loom:104/:108 confirms word 0 is absolute and not epoch-relative, which is the whole reason a short final epoch keeps its own base.

The card schema claim, swept rather than sampled

loom-link --print-config-schema <card>/program/llm.loom on ggml-org-Qwen3-4B-loom reports exactly what the comment says: llm.spans, llm.tokens, llm.epoch_spans, llm.epoch_tokens all required, range (1, 8192); llm.context required, range (16, 262144). Then over the whole corpus on this box (~/amd-oss/loom-fun, 112 card dirs):

50  cards declare @llm.epoch_tokens as [range(%value, 1, 8192)]   <- every card that declares it, identically
57  cards carry program/llm.loom but predate the declaration
 5  cards have no program/llm.loom
 0  cards declare a different ceiling

That is the sweep the comment needs and it is clean: no card contradicts kEpochTokenLimit, so the constant is a property of the artifacts rather than of one card.

Two notes, neither blocking

  1. The property sweep never includes the limit the code ships with. for (limit = 1; limit <= kEpochTokenLimit; limit *= 3) walks 1, 3, 9, 27, 81, 243, 729, 2187, 6561 — no even limit, no limit that divides tokens exactly, and not 8192 itself, which is the default every real caller gets. The three properties are the right three (coverage by summing, base advance, bound per epoch); the set is just the one thing that misses the actual constant. A literal set — {1, 2, 3, 4, 7, 64, 1000, 4096, 8192} — costs nothing and closes it.
  2. epoch_count(_, 0) == 0 is documented as "a caller error, not an infinite loop", but epoch_at(i, base, tokens, 0) still returns {base, 0} for every i — the two disagree about what limit == 0 means. Harmless while callers enumerate via epoch_count, which the header says they do; one clause saying epoch_at does not police limit == 0 keeps the next reader from assuming it does.

What makes this reviewable at all, and the reason I would merge it: the zero-token case is not a guard clause bolted on — epoch_count(0) == 1 is the zero-length qwen38_prefill_finish_control path that establishes the decode block on a cache someone else filled, and it has its own arm (handover_position(2000, 0) == 2000, "a zero-token handover leaves the position where it was"). That is the arm I would have asked for, written before I asked. Same discipline as app/loom_kv_layout.h: arithmetic in a header, testable before anything touches memory. add_dependencies(onebit loom_epoch_driver_test) is the right registration shape too — ci.yml builds onebit, and an add_test alone never reaches ctest there.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at c69e34d: READY

The header's central claim is a tool output, so I ran the tool rather than checking the prose — loom-link is on this box:

$ loom-link --print-config-schema ~/amd-oss/loom-fun/cards/amd-Qwen3.8-27B-Quark-AWQ-MXFP4-loom/program/llm.loom
llm.context       range 16 .. 262144
llm.spans         range  1 .. 8192
llm.tokens        range  1 .. 8192
llm.epoch_spans   range  1 .. 8192
llm.epoch_tokens  range  1 .. 8192

All five exactly as the comment says, on the shipped card — so "an epoch carries at most 8192 tokens, a 262144-token prompt is therefore 32 epochs" is measured, not inferred. (The same schema also gives llm.pool 16..2147483584, llm.width 2..8, llm.gated 0..1, which the header does not need.)

The second fact is one I verified in the earlier L4 review and it still holds: the position that places KV is word 0 of the caller-owned block and is absolute — kernel/attention_decode.loom loads %control_view[0] and multiplies it by %c1024 to place the token, and kernel/decode_control.loom:54-59 sets it to position_base + token_count when a prefill finishes. So the driver's job really is "epochs at bases B, B+limit, … then a decode block carrying B+N", which is all this header computes.

The test runs, and its arms are the contract rather than a snapshot: g++ -std=c++17 → 33 ok, 0 failures, including

ok   after prefilling N tokens at base 0 the decode position is N (18432)
ok   …and it shifts with the base (1010)
ok   decode word 0 is the absolute position after the handover (18432)
ok   decode word 1 is generated_count = 1 after a handover (1)
ok   word 2 (eos) is the caller's, not the driver's (0)
ok   a zero-token handover leaves the position where it was (2000)
ok   and its single epoch carries no tokens (0)

i.e. absolute-not-relative, the generated_count := 1 landing the finish kernel performs, word 2 left alone, and the zero-length finish path that establishes a position without writing a cache byte — the four things a driver can get wrong.

And the wiring carries the lesson from the layout PR: add_dependencies(onebit loom_epoch_driver_test) is there, with the comment saying why (ci.yml builds onebit, and an add_test alone never reaches ctest there). That is the one thing #3159 needed a fix for, applied up front.

Nothing to change. Bound: header + test read and run, schema verified with the real tool on the real card; no device and no Loom compile.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant