Repository navigation
asm-census: refuse overwritten loop counters and spilled flags - #1063
juliankang4 wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Verdict: MUST_FIX: The new disassembly analysis can certify incorrect tile costs.
Must fix
1. Reject flag writes before the exit test
tools/ref/asm-census.py:451 checks writes only in the tail. In canned_flag(), replace the first instruction at address 4 with xorl %eax, %eax: the loop exits after 8 instructions, but total() returns 21. Embedded in a tile listing, this certifies (68, 10) instead of (42, 10) with zero red rows. These counts are derived from the canned instructions.
Fixing this before more rows are derived prevents incorrect scheduler weights from spreading.
Insert before the existing writes = ... line, and add this listing to the refusal cases:
if any(
self._sets(ins, flag) is not False
for b in blocks - tail
for _, ins in self.body[slice(*self.blocks[b])]
):
return None2. Check the shared path sets its flag before removing edges
tools/ref/asm-census.py:585 infers a set flag from the other path's zeroing instruction. Replace movb $0x1, %dl in canned_shared() with xorl %edx, %edx: the group executes its 27-instruction preparation path, but the analysis removes it and reports 10. The complete tile report still accepts the resulting row. Counts are derived from that fixture.
Rejecting this shape now prevents a successful derivation from hiding missing work.
Insert after at, target, flag = sites[0], and add the zero-flag setup as a refusal case:
setup = [ins for addr, ins in body if at < addr < target]
writes = [w for ins in setup if (w := Cfg._sets(ins, flag)) is not False]
if writes[-1:] != [1]:
raise TileError("the shared-halves path does not set its flag to one")Checked
Duplicates: dryer reported 0 pairs; the cost table now lives on TileKind::units.
Complexity: crapper flagged TileKind::units at 16; its exhaustive cost-table match is harmless growth.
Silent failure: both reported flag inferences accept incorrect instruction counts.
Tests: the existing Python self-test passes without detecting either case. Both fixture mutations reproduce, including acceptance by the complete tile report. Both proposed guards preserve the self-test and reject the corresponding inputs. Rust tests were not run.
Gates: no tolerance moved; exhaustive matching replaces the removed table-membership clause.
Escape catalog: no C1–C4 pattern matches either finding; no ledger lessons are in force.
Notes
The PR carries a generation smoke run on an RTX 5090, but no just gate-* commands with output. GPU gate evidence is false.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
c158f45 to
04068b9
Compare
There was a problem hiding this comment.
Since the last review:
- Earlier item 1, pre-test flag writes: original reproduction fixed.
- Earlier item 2, shared flag setup: original reproduction fixed.
Verdict: MUST_FIX: Unrecognized writes still let the census certify incorrect tile costs.
Must fix
1. Recognize both outputs of exchanges
tools/ref/asm-census.py:420 handles both outputs only for mulx. canned_tile(inner="xchgq\t%rax, %rcx") exchanges two initially zero counters. On its first entry the inner loop executes 15 trips, but the new write guard sees only the latch's add and charges 8. The complete report accepts (200, 10) with zero red rows. These counts are derived from the fixture.
Fixing the shared write detector now prevents underpriced rows from becoming scheduler inputs.
Replace the mulx condition with this line, and add the exchange fixture to the refusal cases:
if mn.startswith(("mulx", "xchg", "xadd")):2. Invalidate stack facts when another store can overlap them
tools/ref/asm-census.py:422 invalidates stack facts when %rsp moves, but otherwise compares operand strings. In canned_shared(**spill), replace the first consume instruction with movq $0x0, 0xc(%rsp). That store zeros the saved flag at 0x10(%rsp), yet the reload retains the inferred value 1. Later groups execute 27 instructions while the census charges 10; the complete report accepts (34, 2) with zero red rows. These counts are derived from the fixture.
Rejecting this store now prevents compiler changes from silently changing the meaning of accepted cost rows.
Until byte ranges are tracked, discard stack facts on other memory stores. Insert before the multiply/exchange case, and add the overlapping-store fixture to the refusal cases:
if (STACK_SLOT.fullmatch(loc) and ops and "(" in ops[-1]
and locs[-1] != loc and not READS_ONLY.fullmatch(mn)):
return NoneChecked
Duplicates: diagnostics report 0 dryer pairs.
Complexity: crapper flagged TileKind::units at 16; its exhaustive table match is unchanged in this interdiff and harmless.
Silent failure: 2 unrecognized write patterns followed through tile_units to green rows.
Tests: Python self-test passes. Six production guard/copy mutations turn it red. The two additional fixtures expose the findings; both proposed fixes preserve the self-test and reject those fixtures. Rust tests were not run.
Gates: no pins, tolerances or test cases removed or relaxed in the interdiff.
Escape catalog: no C1–C4 patterns match. No ledger lessons are in force.
Notes
The RTX 5090 generation smoke run has no just gate-* commands with output. GPU gate evidence is false.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| return None if loc in CALLER_SAVED else False | ||
| if re.fullmatch(r"i?(mul|div)[bwlq]?", mn) and len(ops) == 1: | ||
| return None if loc in ("rax", "rdx") else False | ||
| if mn.startswith("mulx"): |
There was a problem hiding this comment.
Exchanges write both operands; missing the first lets the counter loop run 15 trips on its first entry while the census charges 8.
| if mn.startswith("mulx"): | |
| if mn.startswith(("mulx", "xchg", "xadd")): |
04068b9 to
99cba54
Compare
There was a problem hiding this comment.
Since the last review:
- Earlier item 1, exchange outputs: fixed.
- Earlier item 2, overlapping stores: still open for negative stack offsets, at the guard linked below.
Verdict: MUST_FIX: The census still accepts incorrect costs when an overlapping store clears a red-zone flag.
Must fix
1. Recognize negative stack offsets
tools/ref/asm-census.py:424 applies alias invalidation only when STACK_SLOT matches. Its pattern excludes negative displacements, which x86 uses for red-zone locals.
In the regression below, the head's store clears the flag and the loop exits after 8 instructions, but Cfg.total returns 21. Embedded in canned_tile, this makes tile_units accept a row of (66, 10) with zero red rows instead of the actual (40, 10). These counts are derived from the fixture. The caller receives a green report for incorrect scheduler costs.
Fixing the shared matcher now prevents accepted derivations from depending on this incorrect count.
Replace the matcher:
STACK_SLOT = re.compile(r"(-?0x[0-9a-f]+)?\(%rsp\)")Add this case to the existing flag-loop refusal cases:
("a red-zone flag overwritten in the head", canned_flag(
start="movl\t$0x1, -0x10(%rsp)", head="movq\t$0x0, -0x14(%rsp)",
test="testb\t$0x1, -0x10(%rsp)", clear="movl\t$0x0, -0x10(%rsp)")),Checked
Duplicates: 0 new functions, types or constants in the interdiff; dryer reports 0 pairs.
Complexity: crapper's TileKind::units at 16 is unchanged here; its exhaustive table match is harmless.
Silent failure: exchange writes, overlapping stores and stack-pointer writes followed; negative-offset overlap reaches a green report.
Tests: self-test passes before and after the proposed fix. The red-zone fixture confirms 21 reported versus 8 executed loop instructions and a green (66, 10) row; the fix rejects both fixtures. Rust tests were not rerun because this interdiff changes only the Python tool.
Gates: no pins, tolerances or cases removed or relaxed in the interdiff.
Escape catalog: no C1–C4 patterns match. No ledger lessons are in force.
Notes
The RTX 5090 generation smoke run has no just gate-* commands with output. GPU gate evidence is false.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| FLAGS_SET = re.compile(r"v(u?comis|p?test)") # the vector ones that set them | ||
| READS_ONLY = re.compile(r"(cmp|test|bt|push)[bwlq]?|j\w+|nop\w*|prefetch\w*|v?u?comis[sd]|v?p?test\w*") # write no operand | ||
| CALLER_SAVED = {"rax", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11"} # a call leaves them unknown | ||
| STACK_SLOT = re.compile(r"(0x[0-9a-f]+)?\(%rsp\)") |
There was a problem hiding this comment.
Include negative stack offsets so an overlapping red-zone store invalidates the flag instead of certifying an incorrect cost row.
| STACK_SLOT = re.compile(r"(0x[0-9a-f]+)?\(%rsp\)") | |
| STACK_SLOT = re.compile(r"(-?0x[0-9a-f]+)?\(%rsp\)") |
99cba54 to
518896c
Compare
There was a problem hiding this comment.
Verdict: MUST_FIX: Four write-tracking gaps still let the derivation accept incorrect loop costs.
Must fix
1. Use the shared tracker for spill initialization
tools/ref/asm-census.py:482 still skips overlapping stores and source-register exchanges on entry. Insert movq $0, 0x1c(%rsp) after initializing the flag at 0x20(%rsp): the canned spill loop exits after one trip, but the reader prices two and returns green. Reusing _sets now removes this second decoder (R14).
Replace the definition:
def _entry_value_op(self, header, op, reg):
"""The proven entry value of a register or a spill with one source-register indirection."""
if reg is not None:
return self._entry_value(header, reg)
want = op
for ins in self._entry_ins(header):
value = self._sets(ins, want)
if value is False:
continue
if value is not None:
return value
ops = operands(ins)
if want == op and mnemonic(ins).startswith("mov") and len(ops) == 2 and ops[1] == op:
want = gpr(ops[0])
if want is not None:
continue
return None
return None2. Recognize the remaining byte-register aliases
tools/ref/asm-census.py:576 relies on gpr, which misses %dil, %sil, %bpl, %spl and the high-byte registers. With the canned flag in %edi, movb $0, %dil in the head clears it immediately; _sets reports no write and the two-trip cost remains green. Fixing the alias owner now covers flags and counters together.
Replace gpr:
def gpr(op):
"""The 64-bit family of an integer register operand, else None."""
op = op.strip()
m = re.fullmatch(r"%[re]?(ax|bx|cx|dx|si|di|bp|sp)", op)
if m:
return "r" + m.group(1)
m = re.fullmatch(r"%([abcd])[lh]", op)
if m:
return "r" + m.group(1) + "x"
m = re.fullmatch(r"%(si|di|bp|sp)l", op)
if m:
return "r" + m.group(1)
m = re.fullmatch(r"%r(\d+)[dwb]?", op)
return f"r{m.group(1)}" if m else NoneBefore the zeroing-xor check in _sets, keep narrow writes from proving a full-register constant:
if ops and gpr(ops[-1]) == loc and ops[-1] not in (f"%{loc}", f"%e{loc[1:]}", f"%{loc}d"):
return NoneUse that proof in the existing clear helper too, so adding %ah does not make xor %ah, %ah prove all of %eax zero:
def _clears(ins, op, reg):
"""Whether the instruction proves the flag operand is zero."""
value = Cfg._sets(ins, reg or op)
return value is not False and value == 03. Account for implicit accumulator writes
tools/ref/asm-census.py:579 handles implicit multiply/divide outputs but misses cmpxchg and lahf. With a flag initially in %eax, %rcx=0 and induction in %r12d, cmpxchgq %rbx, %rcx clears the flag on failure. The loop executes once while the reader accepts two trips. A counted %rax loop containing lahf is also accepted although %ah changes. Rejecting these writes now prevents incorrect costs from becoming accepted baselines.
Insert before two_outputs:
if mn.startswith("cmpxchg") and loc in ("rax", "rdx"):
return None
if mn == "lahf" and loc == "rax":
return None4. Invalidate stack flags across calls
tools/ref/asm-census.py:578 reports every stack slot unchanged by a call. A returning call whose return address has bit 0 clear overwrites the flag at -0x8(%rsp). With induction in callee-saved %r12d, the loop exits after one trip while the reader returns green for two. Its callee can also overwrite aliased slots. Closing this case now avoids accepting more incorrect spill costs.
Replace the return in the call branch:
return None if loc in CALLER_SAVED or STACK_SLOT.fullmatch(loc) else FalseAdd refusal cases for these paths to the existing self-test; each must fail when its corresponding fix is removed.
Checked
Duplicates: 4 new items checked; spill-entry constant decoding remains a second owner. No other duplicate found.
Complexity: no Rust functions changed; the new Python function combines register effects and stack alias checks.
Silent failure: six constructed listings return green despite ignored writes, covering the four findings above.
Tests: head and proposed-fix self-tests pass; the fixes reject all six listings. Seven mutants turn the self-test red: dropped counter guard (408), each omitted multi-output opcode (581), unsigned-only slots (40), ignored overlap (595), and split indexed operands (223).
Gates: no threshold, tolerance or pin moved.
Escape catalog: no C1–C4 pattern matched.
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)
| mn = mnemonic(ins) | ||
| locs = [gpr(o) or o for o in ops] | ||
| if mn.startswith("call"): | ||
| return None if loc in CALLER_SAVED else False |
There was a problem hiding this comment.
A call overwrites a flag at -0x8(%rsp) with its return address; the callee can also overwrite aliased slots, so stack values must become unknown.
| return None if loc in CALLER_SAVED else False | |
| return None if loc in CALLER_SAVED or STACK_SLOT.fullmatch(loc) else False |
…reads The derivation proved loop trip counts through several narrow write readers, and each one missed a different write: an overlapping store or a source register exchange after a spilled flag's setup, a byte register such as %dil, the implicit accumulator writes of cmpxchg, lahf and cltq, a call that overwrites a stack slot, and a flag-writing instruction between the exit test and its je. Each gap let a wrong loop cost come out as a green row. writes() now classifies the register, memory and condition-flag writes of every instruction the derivation reads from one table, WRITE_CLASSES. An instruction or operand form the table does not list is refused by name instead of being read as writing nothing. The counter check, the flag checks, the entry-value reader (with its one register indirection for a spilled flag) and the exit-test scan all read it, which replaces the separate readers. A register's constant counts only when the write covers the whole register, or its low byte or word for the bit a flag test reads; %ah..%dh never prove a flag. A spilled flag stays known only across stores proven disjoint from its 8 bytes. Indexed addresses are read as one operand. The self-test refuses each of these listings and checks the 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.
518896c to
63731a7
Compare
There was a problem hiding this comment.
Verdict: MUST_FIX: two write-tracking gaps accept incorrect loop counts.
Must fix
1. Restrict the identical-operand exemption to xchg
tools/ref/asm-census.py:312 skips both writes when the operands match, including xadd and mulx. With xaddq %rax, %rax in the counted fixture's head, the counter follows 0 → 4 → 12 → 28 → 60 and never reaches 32, but the reader reports eight trips and a green Q4_K row. mulxq %rsi, %rax, %rax also bypasses the write guard and produces a green row.
Fixing the shared decoder now prevents both forms from validating incorrect costs. Replace this branch:
elif kind in ("2", "2F") and len(ops) >= 2:
if not mn.startswith("xchg") or ops[-1] != ops[-2]:
put(ops[-2])
put(ops[-1])2. Require the last latch write to clear the flag
tools/ref/asm-census.py:521 accepts any clearing write in the latch. With flag=1 and counter=0 on entry, a latch that clears the flag, restores it to one, writes counter=1 and jumps back never takes the test $1, flag; je exit. The reader nevertheless returns trips() == 2, reproduced with both a register flag and a spilled flag.
Closing this overwrite path now avoids accepting a cost from a loop whose trip count is unproved. Replace the clearing check:
if next((v for i in reversed(latch_ins)
if (v := self._sets(i, flag, low=True)) is not False), None) != 0:
raise TileError(f"{where}: the flag {shown} is not cleared in the latch")Add refusal cases for identical xadd/mulx outputs and for a latch that clears then overwrites its flag. The current self-test passes with both defects present.
Checked
Duplicates: the retained findings concern separate guards.
Complexity: write decoding and latch transitions reviewed; only Python changed.
Silent failure: write effects followed through _sets, trip counts and dynamic counts to cost rows.
Tests: self-test passes with both defects present. Both inline suggestions compile, preserve the self-test and reject all four counterexamples: matching-output xadd/mulx, and register/spill flag overwrites.
Gates: no pins moved.
Escape catalog: no C1–C4 patterns matched.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
| 0 if mn.startswith("xor") and len(ops) == 2 and ops[0] == ops[1] else None) | ||
| put(ops[-1], value) | ||
| elif kind in ("2", "2F") and len(ops) >= 2: | ||
| if ops[-1] != ops[-2]: # an exchange of an operand with itself (`xchg %ax, %ax` padding) changes nothing |
There was a problem hiding this comment.
Only xchg can skip matching operands; xadd doubles the register and mulx still writes its destination.
| if ops[-1] != ops[-2]: # an exchange of an operand with itself (`xchg %ax, %ax` padding) changes nothing | |
| if not mn.startswith("xchg") or ops[-1] != ops[-2]: |
| latch_ins = [i for _, i in self.body[s:e]] | ||
| if not any(_clears(i, flag, freg) for i in latch_ins): | ||
| raise TileError(f"{where}: the flag {flag} is not cleared in the latch") | ||
| if not any((v := self._sets(i, flag, low=True)) is not False and v == 0 for i in latch_ins): |
There was a problem hiding this comment.
A later latch write can overwrite the cleared flag; require its last write to leave zero.
| if not any((v := self._sets(i, flag, low=True)) is not False and v == 0 for i in latch_ins): | |
| if next((v for i in reversed(latch_ins) | |
| if (v := self._sets(i, flag, low=True)) is not False), None) != 0: |
|
Superseded by a new pull request from the same branch; the link follows. |
|
Superseded by #1066. |
타일 비용 유도기가 덮어쓴 loop counter와 spill된 flag를 잘못 읽어 틀린 명령 수를 받아들이던 문제를 막았습니다.
What and why
tools/ref/asm-census.pyderives the host tile cost rows from the kernels' disassembly. On top of the flag-tested latch reading in main, three cases still let it accept a wrong cost. A loop whose counter is written somewhere in the loop besides its latch was counted as if the counter only stepped there. A flag spilled to the stack and then overwritten was still read as the old value: the stack matcher missed negative displacements, which x86 uses for locals below the stack pointer, and a store through another address that may overlap the slot did not clear it. Writes thatxchg,xaddandmulxmake to both of their outputs, and addresses with a comma inside the parentheses, were not read as writes either.Further cases the reader still accepted: a spilled flag kept across a
call, a counter written implicitly bycmpxchg,lahforcltq, a flag cleared through a byte register such as%dil, a flag test whosejereads flags thatbsforvptestrewrite, and instructions or operand forms the reader had no rule for.The reader now takes every write to the counter and the flag from one place, a single allowlist of instruction write effects, including exchanges and stores at negative or indexed stack offsets. It stops with a named error on a write it cannot account for, and on an instruction or operand form the allowlist does not list. A store that provably ends before the tracked slot is still accepted. The cost table and
crates/model/src/ops.rsare 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.
copying it (
AGENTS.md"Common code first",docs/rust-quality.mdR14). Where I found an existing copy, Inamed it below.
(tensor shapes, the attention kind, the quant). A common owner gained no per-model branch, flag or trait method.
tools/check-comments.sh).PIN(YYYY-MM-DD):and its reason.
cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.Duplication found or removed (
path:line): none.What I ran
Failing line before, the new self-test cases against the
tools/ref/asm-census.pyin main:New self-test refusal cases fed to the reader without the fix (17 of 29 were accepted as a green row):
After the fix:
Derivation over the current qdot listing:
The listing derives the same table as with the reader in main (
diffempty). The other 14 rows are within tolerance of the table. IQ2_XXS is refused on its own row, as it is on main.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.