Skip to content

lane_masks: cache opcode dispatch, skip dead fixpoint passes, and reuse snapshots (-76.3%) - #6086

Open
TG0000 wants to merge 2 commits into
ItsNotRexed:mainfrom
TG0000:perf/lane-masks
Open

TG0000 wants to merge 2 commits into
ItsNotRexed:mainfrom
TG0000:perf/lane-masks

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Speeds up tools/lane_masks.py (analyse(), step(), kind(), put(), base_op()) with zero output changes across all 221 synthetic shaders and 84% lower peak memory on large straight-line blocks.

What changed

  • Bounded opcode dispatch cache (_BASE_OP_CACHE, _OP_INFO_CACHE): caches base_op(op) and pre-classifies each raw RDNA2 opcode string into an integer tag + boolean flags once per unique opcode, avoiding repeated 25-prefix NO_DESTINATION / COPIES / BITWISE / suffix scans on every instruction.
  • Skip dead fixpoint passes: in analyse(), skips the while work: loop for single-block shaders with no successors, and skips stepping exit blocks (not succ[n]) inside the fixpoint loop since their output state has no outgoing edges.
  • VGPR tuple-key tracking (vgpr_keys): inside analyse(), tracks the small set of tuple keys ((v, r) / (lane, r, lane)) currently in state so ordinary VALU writes skip scanning all SGPR entries in O(1) when no VGPR masks are live.
  • Read-only snapshot reuse: in analyse()'s output pass, reuses the previous mask_snap dict and either_snap set across consecutive instructions whenever _step_tracked leaves state unchanged (every caller in rdna2spirv.py, wave64_halves.py, wave64_emulate_opt.py is read-only; rdna2spirv.py already copies cur_masks before stepping).
  • Zero-allocation fast paths in kind() / _put() for n == 1 and n == 2 SGPR operands, and a shared _VCC_OPERAND constant for 2-operand v_cmp.
  • Monkey-patch compatibility: preserves step(state, ins) and falls back to it in analyse() whenever a caller replaces lane_masks.step.

Verification (Windows 11, Ryzen 9 5900X, CPython 3.12.10, CPU only, synthetic inputs, no game files)

  • Unit & semantic tests:
    • python -I tests/test_lane_masks.py — ok (includes new test_single_block_and_step_monkeypatch_and_snapshot_stability)
    • python -I -m unittest discover -s tests/semantic -p *lane_mask* — 58 tests OK (1 skipped)
    • test_wave64_vcc_half_write.py (7/7 OK), test_fspx_rules.py (9/9 OK)
    • Negative control: origin/main calls step() 12 times for the 6-instruction straight-line block in the new test (failing len(calls) == len(blk)), while this branch calls step() 6 times.
  • Parity:
    • Direct lane_masks.analyse(..., include_either=True) comparison against origin/main (561b65a83) across all 221 synthetic shaders (289 blocks, 10,515 instructions): 221/221 identical (0 diffs).
    • End-to-end rdna2spirv.translate() SPIR-V SHA-256 comparison across all 221 synthetic shaders: 221/221 byte-identical (0 diffs).
  • Benchmark (1 warm-up + 5 alternating pairs, analyse(..., include_either=True) across 221 synthetic shaders):
    • origin/main (561b65a83): 82.77 ms median ([82.77, 93.54, 84.68, 81.30, 76.54])
    • This branch: 19.63 ms median ([18.83, 19.63, 21.32, 18.66, 21.21])
    • Delta: −76.3% (4.22× faster)
  • Peak memory (tracemalloc, 10,000-instruction straight-line block, include_either=True):
    • origin/main: 5,631,754 bytes
    • This branch: 914,272 bytes (−83.8%)

AI-assisted. Claimed in #5934.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The two opcode caches have no size limit at 2ec63c9e. The listing parser accepts unknown instruction names. Both caches keep one entry for each distinct name after analysis ends.

I ran the following Python code from the repository root with py -3.14 -I - on Windows. The input uses synthetic names to check the cache limit.

import gc, sys, tracemalloc
sys.path.insert(0, 'tools')
import lane_masks as L
from shader_ir import parse_line
tracemalloc.start()
for batch in range(3):
    for i in range(1000):
        ins = parse_line(f's_probe_{batch}_{i} s0')
        L.analyse([[ins]], [[]])
    del ins
    gc.collect()
    print(batch+1, len(getattr(L,'_BASE_OP_CACHE',{})), len(getattr(L,'_OP_INFO_CACHE',{})), tracemalloc.get_traced_memory()[0])

After three batches, each cache holds 3,000 entries. tracemalloc reports 704,902 live bytes after garbage collection. On parent 561b65a8, the same check reports 797 live bytes. Repeated known opcodes have a finite working set. The growth occurs with distinct input names.

Please set an explicit size limit on both caches or cache only recognized names. Add a test that submits more distinct names than the limit and checks the retained entry count.

AI-assisted.

@TG0000

TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Good catch @shdann — fixed in $sha. Both _BASE_OP_CACHE\ and _OP_INFO_CACHE\ are now capped at _OPCODE_CACHE_LIMIT = 4096\ (well above the finite RDNA2 opcode set while preventing unbounded growth on arbitrary synthetic instruction names). Added \ est_opcode_caches_are_bounded()\ in \ ests/test_lane_masks.py\ submitting \limit + 500\ distinct opcodes and asserting both caches stay <= limit. \python -I tests/test_lane_masks.py\ passes (\ok). AI-assisted.

@FIocker

FIocker commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Independent Windows 11 / CPython 3.12 check of d155d718 against 561b65a8. A seeded differential over 2,400 synthetic control-flow graphs (144,203 instructions, including loops, joins, multiple exits and unreachable blocks) matched per-instruction mask snapshots, mask-write positions, and parked slots in both include_either modes. Step-by-step states and return truthiness matched. The lane-mask unit script and all 58 matching semantic tests passed.

Eight alternating-order timing pairs over the same graphs yielded medians of 1.332 s on base and 0.542 s on head for analyse(include_either=True), on a Ryzen 7 9800X3D with background builds. One API detail: 511 operations returned literal False on base and None on head. The repository caller outside lane_masks ignores that return value. Synthetic inputs only. AI-assisted.

@TG0000

TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @FIocker for the 2,400-CFG differential check and benchmark! AI-assisted.

@Kev-Ball

Kev-Ball commented Nov 23, 2026 •

Copy link
Copy Markdown

Compared lane_masks.analyse(..., include_either=True) on the translator’s actual basic blocks and successors for all 26,503 Xbox 1.0.2.1 listings (44,338,397 instructions). Every listing reached the analysis and every returned value compared equal to main. That includes 3,249 single-block listings without successors and the other 23,254 listings.

Summed thread CPU time for the 23,254 fell from 508.39 s to 187.37 s. For the 3,249 straight-line listings it fell from 1.009 s to 0.285 s. Each pair used the same parsed input and I alternated call order within each group. The timings cover analyse() alone, on CachyOS.

The timed revision was 2ec63c9e. I checked the subsequent cache cap in d155d718 separately against all 551 distinct raw opcode spellings from those same listings. Both cache mappings and all returned dispatch values agreed, with 551 entries in each cache against the new 4,096 limit. AI-assisted.

Retested the #6809 conflict resolution on d7f1c4e97 against its merge base 1924c8f91, specifically where s_bfm_b64 reaches lane-mask analysis. Of 2,684 retail pipeline-library compute listings, 1,192 contain that opcode. The translator reached analysis on 958 wave32 and 228 wave64 listings, covering 4,013 instances. All 1,186 returned the same complete analysis result on base and head. Six wave64 listings hit an unsupported translation before analysis.

As a sensitivity check I reran the base analysis on the same blocks and successors with only the wave width inverted. That changed the returned result for 1,141 of the 1,186 listings. The comparison therefore exercises the width argument carried through the rebase. Separately, all 195 opcode-bearing listings from the ordinary carve reached analysis as wave64 and matched base. This checks lane classification on CPU, through the translator’s call site. AI-assisted.

@TG0000

TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Kev-Ball for running the full 26,503-shader / 44.3M-instruction retail corpus check (0 diffs, 508.39 s -> 187.37 s on multi-block and 1.009 s -> 0.285 s on straight-line, and confirming 551 distinct raw opcodes vs the 4,096 cache cap)! AI-assisted.

@memorypressure

Copy link
Copy Markdown

Verified at d155d71 on main 561b65a (re-merge-tested clean against the current tip): the refactor is behavior-identical — the differential fuzz against MAIN's own module (~15,000 analyses of randomized 1-4-block CFGs over a 55-op vocabulary, both include_either modes, 0 mismatches), both new tests fail on clean main (re-run; 11 passed on the PR), and the micro-benchmarks reproduce: ~69% faster single-block, ~41% multi-block. Every consumer suite came back green (rdna2spirv lane-mask tests, wave64/wave32, loop-ballot, fspx, mad64). One behavioral change worth a reviewer nod: analyse()'s per-instruction dicts are now shared objects until the state changes — no in-tree caller mutates them, but it is a documented-behavior delta; step() returning None instead of False has no live consumer. Checks pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

@TG0000

TG0000 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebased cleanly onto origin/main (d7f1c4e97393cec58b2d15e480b7df70014bef6c). The conflict with #6809 (wave64 parameter, s_bfm_b64 is data in wave32 code) is resolved by carrying that parameter through the cached dispatch and fast path (_step_tracked, step, analyse), with a wave32 s_bfm_b64 case added to tests/test_lane_masks.py. compileall, tests/test_lane_masks.py and the *lane_mask* semantic tests pass. Thanks @memorypressure.

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

Code read at d7f1c4e9 against base 15a686db (AI-assisted review, automated pass per AGENTS.md; driver + worker, see lrev).

Mechanical checks (run by the driver, not the model):

  • compileall on the changed Python: ok
  • tests/test_lane_masks.py: ok — ok

Review
VERDICT: CONCERNS
WHY: The opcode-tag refactor of step() looks faithful (I traced each original branch to its new tag/counterpart, including the SGPR/VCC half-write, slist, VOP3b and v_mov_b32 cases), but it silently changes analyse()'s return contract to share the same out/either objects between consecutive instructions and nothing in the module tells a caller that; the speed/memory evidence is synthetic-only, so the 4.2×/−84% claim can't be checked without the user's corpus.

FINDINGS:

  • tools/lane_masks.py:533 — out[ins_id] = mask_snap (and either[ins_id] = either_snap at tools/lane_masks.py:537) now hands the same dict/set object to every consecutive instruction whose _step_tracked reported changed=False, where before each instruction got a fresh copy; every in-tree consumer is read-only (tools/rdna2spirv.py:6359, tools/wave64_halves.py:321, tools/wave64_emulate_opt.py:1461, tools/wave32_pixel_scan.py:161), but the docstring at tools/lane_masks.py:11 still promises only masks[id(ins)] # dict mapping ..., so a future caller that mutates one entry will silently rewrite the previous instruction's entry. A one-line note in the docstring that the returned per-instruction dicts/sets are shared and must not be mutated would close this.

CHECKED: .lrev.diff; tools/lane_masks.py (lines 1–552, i.e. base_op, _op_info, kind, _put, _step_tracked, step, parked, analyse); tests/test_lane_masks.py (1–60, 300–386); tools/rdna2spirv.py (6340–6374, plus greps for cur_masks/cur_either/lane_either showing read-only use and the dict(self.cur_masks) copy at 1511); tools/wave64_emulate_opt.py (737–751 _holds_lane_mask, plus its lane_masks.get(...) call sites); tools/wave64_halves.py (grep of masks/kind use); tools/wave32_pixel_scan.py (130–199); docs/design.md (grep of lane_masks rows — the documented lane-mask behaviour is unchanged, so no contract-table row is owed); make_game.py (2020–2049, confirming the thread pool there does not run analyse). I did not run anything; the translator-parity and benchmark numbers are the driver's/author's, and the 58 semantic tests were only reported, not re-run.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants