Skip to content

asm-census: refuse overwritten loop counters and spilled flags - #1066

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fix-tile-units-iq1s
Nov 1, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fix-tile-units-iq1s

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 31, 2026 •

Copy link
Copy Markdown
Collaborator

타일 비용 유도기가 덮어쓴 loop counter와 spill된 flag를 잘못 읽어 틀린 명령 수를 받아들이던 문제를 막았습니다.

Supersedes #1063.

What and why

tools/ref/asm-census.py derives the host tile cost rows from the kernels' disassembly. To count a loop's trips it proves that only the latch changes the loop counter, or that a flag loop's flag is set to one on entry and cleared once in the latch. Main proved this by reading what each instruction writes, and every gap in that reading let a wrong cost come out as a green row: a store or a call over a spilled flag, a stack slot at a negative offset, a byte alias such as %dil, the implicit writes of cmpxchg, lahf and cltq, xchg, xadd and mulx writing both outputs or a matching operand, a latch that cleared its flag and then set it again, and a memory bt, bts, btr or btc whose bit index reaches a slot far from its written address.

The reader no longer models write semantics for the counter or the flag. It allows a fixed set of instructions on them and refuses the loop on anything else:

  • Counted loop: only the latch's add $s, %r and cmp $n, %r may name the counter in any alias, the jne must return to the loop's head, and n must be a positive multiple of s.
  • Flag loop: only test $1, FLAG and one clear in the latch (xorl of the register's 32-bit name, or mov $0, SLOT) may touch the flag. The test's block must dominate the latch, and only instructions that write no flags may stand between the test and its je.
  • An instruction touches a register when an operand outside an address names any part of it. It touches a stack slot when it reads or stores an overlapping offset, stores through any other address, or names %rsp. Every instruction with implicit effects (call, push, pop, xchg, xadd, cmpxchg, mulx, one-operand mul, div and imul, lahf, cltq, cqto) and a memory bt, bts, btr or btc refuses the loop wherever it stands in it.
  • Entry value: the first instruction on the entry path that touches the location must write it a constant, either directly or, for a spilled flag, by storing a register that was set to one.

The flag alone proves the two trips, so the induction register is no longer read.

PIN(2026-11-01): Removed the induction-value refusal and its test because the flag's entry value, dominating test, and latch clear prove two trips without an induction register. An instruction or operand form the reader does not list is still refused by name. The cost table and crates/model/src/ops.rs are unchanged.

Release notes: Fixed: the tile cost derivation refuses a loop whose counter or flag it cannot follow instead of reporting a wrong cost.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. Logic two models (or two call sites) share has one common owner; I lifted it there instead of
    copying it (AGENTS.md "Common code first", docs/rust-quality.md R14). Where I found an existing copy, I
    named it below.
  • Model code holds only architecture facts. A model's own files carry only what its architecture forces
    (tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
  • Dead code is gone. Nothing I made unused is left behind (functions, flags, gate clauses, docs).
  • No silent failure. Undefined input is a named error or panic, never a defined-looking output.
  • Comments state what is true now. No dates, issue numbers or how a bug was found (tools/check-comments.sh).
  • No relaxed gate. No band, tolerance or lint moved to make a check pass; a re-pin carries PIN(YYYY-MM-DD):
    and its reason.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line): none.

What I ran

The self-test feeds one table of 115 refusal cases to the reader and checks the reason each one names. It covers the shapes above and the earlier counter and flag cases. Fed to the reader in main, 50 of the first 67 are accepted: 47 as an all-green report, two as a trip count from Cfg.trips (a counted latch whose jne leaves the loop, read as 8 trips, and a flag test the latch can bypass, read as 2), and one as a stale row. For example:

main: accepted (Q4_K ok, Q8_0 ok, red=0): a counted loop whose head touches its counter with xaddq %rax, %rax
main: accepted (Q4_K ok, Q8_0 ok, red=0): a spilled flag cleared then overwritten in the latch by movl $0x1, 0x20(%rsp)
head: refused: the loop at 0x58: `xaddq %rax, %rax` may touch the counter %rax besides the latch's add and compare

The 48 memory bit cases (bt, bts, btr, btc with no suffix, w, l and q, in the head, the entry and the latch of a spilled flag loop) were all accepted before the guard, and the self-test failed:

FAIL-FIRST: old guard accepted 48/48; self-test rc=1
OLD-GUARD: rows=[('Q4_K', 82, 10, 'ok'), ('Q8_0', 4, 2, 'ok')] red=0

After the fix:

python3 tools/ref/asm-census.py --self-test
asm-census self-test: ok (legacy and sse4a lists, the loop census, the normalized diff, a loopless function, the tile-units derivation and its refusals)

Derivation over the current qdot listing:

tools/ref/tile-units.sh
IQ2_XXS  Iq2Xxs   256 386,440,488,547,602                             -   2.0%  (600, 75)      -  REFUSED (the loop at 0xb55: a cycle of blocks no loop inside it accounts for (a body whose paths re-enter their own cycle, so no latch shows its trips))
tile-units: 1 of 15 rows missing, stale, refused or without a tile kernel: the table in ops.rs is not what the code derives

The same listing derives the same report with the reader in main (diff empty). The other 14 rows are within tolerance of the table, IQ1_S's flag loops included, and IQ2_XXS is refused on its own row as it is on main.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added the tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo label Oct 31, 2026

@github-actions github-actions Bot 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.

Verdict: MUST_FIX: A memory bit instruction can still produce a green derivation with the wrong loop count, and a removed test case lacks its required dated reason.

Must fix

1. Refuse memory bit instructions before checking stack overlap

tools/ref/asm-census.py:307 bounds btrq %rdx, 0x10(%rsp) to eight bytes. With %rdx=0x80, that instruction clears bit 0 at 0x20(%rsp). The spilled-flag fixture exits on its first test, but the reader reports two trips. Setting %edx=0x80 on entry and using this instruction as the fixture's head produces (82, 10), both rows ok, and red=0.

One refusal now prevents a later stale-table approval. Replace the guard at line 293:

    if kind == "implicit" or (re.fullmatch(r"bt[rcs]?[wlq]?", mn) and any("(" in o for o in ops)):
        return True

Add this case to tile_refusals() so restoring the bug makes the self-test fail:

        ("a bit reset aliases the spilled flag",
         flagged("spill", inner="btrq\t%rdx, 0x10(%rsp)", entry=("movl\t$0x80, %edx",)),
         "may touch the flag"),

The replacement passes the existing self-test and rejects this case.

2. Date the removal of the induction-refusal test

tools/ref/asm-census.py:1017 replaces the refusal table without its former movl $0x2, %eax induction-count case. The body explains why the flag alone proves the trips, but the gate-removal contract also requires a dated reason.

Record the reason while the deleted case is visible in this diff. Add this line to the PR body:

PIN(2026-11-01): Removed the induction-value refusal and its test because the flag's entry value, dominating test, and latch clear prove two trips without an induction register.

Checked

Duplicates: no duplication finding submitted. No dryer pairs were supplied.
Complexity: no Rust functions changed; crapper supplied no function scores.
Silent failure: the missed write in item 1 reaches two green rows with red=0.
Tests: the existing self-test passes. The proposed regression fails on head and passes with the suggested fix. The inline replacement is valid Python on an added line.
Gates: tolerance unchanged; the removed induction-refusal case needs the dated reason in item 2.
Escape catalog: no patterns matched. This change touches tool code, with no inference hot path.

Notes

dryer and crapper did not run because no Rust file changed.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

Comment thread tools/ref/asm-census.py Outdated
%rsp is a register operand, an operand at %rsp may overlap the slot's SLOT_BYTES (its width the widest register
operand or integer suffix, unknown: overlapping), or a "D"/"DF" instruction stores through any other address."""
mn, ops, kind = form(ins)
if kind == "implicit":

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.

A register bit index lets memory bt/bts/btr/btc reach another stack slot. Refuse these forms before applying the fixed-width overlap check.

Suggested change
if kind == "implicit":
if kind == "implicit" or (re.fullmatch(r"bt[rcs]?[wlq]?", mn) and any("(" in o for o in ops)):

… touch them

The derivation proved loop trip counts by reading what each instruction
writes, and every gap in that reading let a wrong loop cost come out as a
green row: an overlapping store or a call over a spilled flag, a byte alias
such as %dil, the implicit writes of cmpxchg, lahf and cltq, xadd and mulx
with matching operands, and a latch that cleared its flag and then set it
again.

The counter and the flag now carry no write semantics. In a counted loop
only the latch's `add $s, %r` and `cmp $n, %r` may name the counter
(any alias), and the jne must return to the loop's head. In a flag loop only
the `test $1, FLAG` and one clear in the latch (`xorl` of the register's
32-bit name, or `mov $0, SLOT`) may touch the flag, and the test must
dominate the latch. Any other instruction that names the location outside
an address, reads or stores an overlapping stack slot, stores through
another address or moves %rsp refuses the loop, and so does every
instruction with implicit effects (call, push, pop, xchg, xadd, cmpxchg,
mulx, one-operand mul, div and imul, lahf, cltq, cqto). Between the flag
test and its je only instructions that write no flags may stand. The entry
value is read from the first instruction on the entry path that touches the
location, which must write it a constant (or, for a slot, store a register
that does). An instruction or operand form the table does not list is still
refused by name.

The flag alone proves two trips, so the induction register is no longer
read. The self-test feeds one table of refusals, these shapes and the earlier
ones, and checks each reason. The table report on the current qdot listing
is identical to main: 14 rows within tolerance and IQ2_XXS refused on its
own row.
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-fix-tile-units-iq1s branch from 56cceb0 to b72726f Compare November 1, 2026 01:16

@github-actions github-actions Bot 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.

Since the last review:

Verdict: CLEAN: Both earlier findings are resolved, and the interdiff has no remaining finding.

Checked

Duplicates: 0 new functions, types or constants; the added cases reuse the existing fixture. No dryer pairs supplied.
Complexity: no crapper scores; the edit adds one guard predicate and a parameterized refusal matrix.
Silent failure: 3 callers of the changed guard followed through counted-loop checks, flag-loop checks and entry inference. Memory bit operations produce named refusals.
Tests: self-test passes. All 48 new cases assert the refusal reason. Removing the memory-bit clause at line 294 accepts all 48 and makes the self-test fail. Indexed, segment-based, immediate-index and negative-offset probes also refuse; unrelated register-only bit operations remain allowed.
Gates: no tolerance changed. The removed induction-refusal case now has its dated PIN and reason.
Escape catalog: no patterns matched. Only tool code changed; no inference hot path.

Notes

dryer and crapper did not run because no Rust file changed.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 1397a0b into midagedev:main Nov 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant