WIP: perf(vk): CRC-32 in hand-written x86-64 (lsasm_crc32: PCLMULQDQ folding, else slice-by-8) #2131
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
3 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2131
Loading…
Reference in a new issue
No description provided.
Delete branch "siantm/Longshot:perf/asm-crc32"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
CRC-32 is computed a byte at a time through one table in two places of the renderer: the pipeline list's zip
(
gpu/vk/pipeline_share.h) and the screenshots' PNG chunks (write_pngingpu/vk/vk_replay.cpp).This adds
gpu/asm/crc32.Son the asm kit:lsasm_crc32, CRC-32's reflected update (polynomial 0xEDB88320) withoutthe inversions. With PCLMULQDQ (
__PCLMUL__:-march=nativeon most PCs; x86-64-v3 does not include it) 64 bytes andup are folded four 16-byte lanes at a time, then one, and Barrett-reduced; otherwise, and for what is left, slice-by-8
through eight tables, then a byte at a time. SSE4.2's
crc32instruction is CRC-32C, another polynomial, so it is notused. The zip and
write_pngcall it with the inversions they had: the zips and PNGs are the same bytes as before.The result expected: those CRCs faster; the files the same.
No switch: the values are the C's, bit for bit.
From 971f8074 on
exp/x86-asm-sync. Depends on #1947 (the asm kit, which now carries the GPU-visible ranges' sort,lsasm_sort_ranges): its commits show in this diff until #1947 merges.Read first:
gpu/asm/crc32.S, then the zip ingpu/vk/pipeline_share.handwrite_pngingpu/vk/vk_replay.cpp.Testing
Tested: Windows 11, i7-9700, RTX 4060, the builder's llvm-mingw clang 23 (
CC/CXX,RX_CPMset); headab72ffc3on #1947's head
cffa2f46(the asm kit, on main9dd41326). Through the PC's job queue, each run in a hidden console,tests/run_all.py --strict --exact --jobs 2 --timeout 1200: the change's own checks (light jobpr-tb-AsmCut5-light,log
t-AsmCut5-asm-crc32):test_asm_crc32.py,test_capture_dimensions.py,test_pipeline_share.py,test_png_publication.pypass (4 of 4).--changed cffa2f46(build jobpr-tb-AsmCut5-build, logt-AsmCut5-chg-asm-crc32): 136 checks, 111 pass, 25 fail, each of which fails on #1947's head @cffa2f46too (aworktree at
cffa2f46in the queue's jobs, logst-AsmCut5-base-kit-changedandt-AsmCut5-base-kit-more):test_capture_readback_visibility.py,test_crash_record.py,test_dev_packs.py,test_device_lost_exit.py,test_draw_stream_visibility.py,test_flush_nothing_held.py,test_frame_overlap.py,test_fsr_image_retirement.py,test_fsr_uniform_ownership.py,test_gpu_wait_stats.py,test_input_background.py,test_menu_keys.py,test_mesh_conv.py,test_perf_report.py,test_present_queue_default.py,test_present_source_crop.py,test_profiling_mode.py,test_recorder_own_idle.py,test_renderer_new_handler.py,test_replay_write_order.py,test_slow_frames.py,test_sparse_mirror.py,test_ub_update_batch.py,test_upscaler_rows.py,test_vk_occlusion_queries.py.It has NOT run in the game on this PC yet.
Still to test:
at least three interleaved runs of each (AB AB AB), each taking twenty screenshots and "Save my pipeline list" (the
Insert menu's Debug tab) three times with
HOS_PROFILE=1(python -I scripts/perf.py reporton its folder: theshare of
write_pngand of the zip's writing on their threads), expecting PNGs and zips that open and check(
python -m zipfile -t) as the base's do and that share lower on this PR; a difference within the runs' spread isno difference measured (by hand)
head and on this PR, expecting the screenshots to open as the base's do (@Beanstalk linux+nvidia, linux+amd,
windows+amd, windows+intel, steamdeck: Kokiri Forest a minute, three screenshots, #1947's head against this PR)
python3 -I -B tests/test_asm_crc32.py --cxx g++and--cxx clang++, expecting PASS (by hand)Measurements
Verdict: a gain everywhere: on 4 KB and more
lsasm_crc32takes 5.7-5.8× less time per byte than the Ctable loop in the SSE2 and AVX2 builds (slice-by-8) and 34-50× less with PCLMULQDQ (the folding body:
-march=nativeon this PC, the game's own build); 3.5× (7.7× with PCLMULQDQ) on 64-byte buffers; 1.20-1.23× on a PNG's small IHDR and
IEND chunks. A screenshot's or a zip's CRC is a small part of writing it: no claim on the whole. A micro-benchmark on authored input; not measured in play.
Baseline: the C this PR replaces, as #1947's head
cffa2f46has it (the asm kit on main9dd41326, which this PR depends on), not main itself.The micro-benchmark: CRC-32 as
cffa2f46computes it (the byte-at-a-time table loops ofgpu/vk/pipeline_share.handgpu/vk/vk_replay.cpp, cut from them) againstlsasm_crc32called as this PR's zip andwrite_pngcall it, over 4 MB of authored bytes. A script on this PC, not in this PR (asm_crc32_bench.py, PrTrials'trials/tools/bench), run alone in the PC's job queue on 2026-11-22: 3 rounds of 201 repetitions per case and arm, i7-9700, llvm-mingw clang 23.1.5-O2 -ffp-contract=off, arms SSE2 (-march=x86-64) and AVX2 (-march=x86-64-v3, what the release builds the back end for), and PCLMUL (-march=x86-64-v3 -mpclmul). The arms take turns at going first; their outputs were compared at every repetition and were equal. Each cell: the median of the three rounds' medians, [lowest–highest round median], in ns per byte. Change: before ÷ after (above 1: this PR faster).cffa2f46ab72ffc3Risks
What could break: a wrong CRC would make a screenshot or the shared pipeline list unreadable to other programs; the
test checks the kernel against the C for every length 0-4096 at 8 alignments, chained, in pieces, against the known
answer and between guard pages, with and without PCLMULQDQ, and the PNG checks verify the files' CRCs with Python's
zlib. A revert is enough. Renderer files: the runtime is rebuilt; nothing changes for players' saves, options or caches.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.@Beanstalk This computes the screenshot PNGs' CRCs and the pipeline list zip's checksums with hand-written x86-64 kernels (host), when a screenshot is taken or pipelines are shared. It sits on #1947 (
cffa2f46, the asm kit), so its diff against its merge base includes that PR's commits; the farm cannot take it as the comparison, so please compare with main. No switch: a revert gives back main's code. Please start from the kokiri-start save and take the picture right after it loads and settles, before any input, with a main-against-itself picture on the same PC at that point; then take one more screenshot after Kokiri Forest has played for a minute; at least two starts a side, interleaved, the PR against main on the same PC, on Windows with a Ryzen 9 7900X, Windows with a Core i9-12900K and Linux with a Ryzen 5 5600X. The same picture as main within main's own difference from itself; frame time p99 equal to main's or better, within the run-to-run spread. The log must have no FATAL, device lost or validation error line. Every PNG must open as a valid file.@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.Measurements: the micro-benchmark (trials script, run alone on this PC 2026-11-22, 3 rounds, SSE2 and AVX2): figures and Verdict (PCLMUL too)
@Beanstalk One correction to my request 69748 above, for its picture point: please take each picture 5 s (300 frames at 60 fps) after the first frame whose picture is not a single uniform colour, with no input in between, and take the main-against-itself picture from the same point. A picture taken during the load's fade-in from black is not comparable: run 70269 on #2156 caught the fade in 3 of 4 starts.
@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.@Beanstalk
Beanstalk test farm · ⛔ can't be tested as asked
Commit
ab72ffc· approved by HumanBean (untrusted) · dashboardNot run: the farm can't test this as asked, so nothing is built or run:
⚠️ Note: The farm cannot measure the CRC microbenchmark or the write_png and ZIP thread shares, and cannot run the requested standalone compiler tests.
⚠️ Note: The fixed five-second wait starts after the map event, not after the first non-uniform picture; the later picture is uploaded without comparison because the scene may change.
⚠️ Note: The native and x86-64 builds exercise different CPU-level paths, but the native build does not guarantee PCLMUL on every tester; main also includes differences from the dependency.
What it could test instead: The alternative plan compares main and the PR in Kokiri Forest, using two starts per side and both native and x86-64 builds. It captures a settled picture and another after a minute, and measures frame-time p99; a crash, forbidden error log, excessive picture difference or p99 regression fails the plan. Windows Intel and the specifically requested Core i9-12900K target must wait for matching testers. No tester online now matches windows+intel, windows+cpu-i9-12900k: those targets wait for one.
A member of
BigBeanscan comment@Beanstalk <new words>to ask for something else, or@Beanstalk test it anywayto run the plan regardless.@Beanstalk This replaces my request 69748 on this head and the correction under it with the alternative the farm offered when it could not run it as asked (it cannot time a picture from the first frame that is not a uniform colour, nor check the files). This computes the screenshot PNGs' CRCs and the pipeline list zip's checksums with hand-written x86-64 kernels (host), when a screenshot is taken or pipelines are shared. It sits on #1947 (
cffa2f46, the asm kit), so its diff against its merge base includes that PR's commits; the farm cannot take it as the comparison, so please compare with main. No switch: a revert gives back main's code. That the CRCs and the files are right is covered by the pull request's own tests (tests/test_asm_crc32.py, test_png_publication.py, test_pipeline_share.py) and is not asked of the farm; no micro-benchmark, thread share or compiler test is asked either. Please run the alternative the farm offered: main against the PR in Kokiri Forest from the kokiri-start save, two starts a side, the native and the x86-64 build; a settled picture after the fixed wait after the map event, with main against itself beside it, and one more picture a minute later (uploaded, not compared); frame time p99; on Windows with a Ryzen 9 7900X, Windows with a Core i9-12900K and Linux with a Ryzen 5 5600X. A crash, a FATAL, device lost or validation error line, a picture difference beyond main's own or a p99 regression fails it.@siantm only members of
BigBeanscan start the farm. One of them can approve this request by reacting 👍 to it or to this comment.Recommendation: Request changes. The kernel looks correct and well tested, but every CRC it speeds up is computed off the frame (each
write_pngruns on a detached thread, the zip on a Debug-menu click), so players gain nothing they can feel, and the price is 420 lines of hand-written assembly plus 8 KB of tables built into both modules. As it stands it also fails the guide-screenshot source review in CI.For a player: a screenshot's PNG and a saved pipeline list are written a few milliseconds sooner on a background thread. Nothing changes in frame time, latency or what the files contain. That doesn't make the code better on net: 15 lines of plain C become a kernel only someone who knows PCLMULQDQ folding can maintain, on a path that isn't hot.
Does it help: Yes for the CRC itself, but unproven for anyone playing. The micro-benchmark is sound: 3 rounds × 201 repetitions, tight spreads, the arms alternating, outputs compared. It shows 5.7× (slice-by-8) and 34–50× (PCLMULQDQ) on 4 KB and up. On a 1280×720 screenshot's IDAT that is about 6.7 ms → 1.2 ms, or → 0.2 ms with PCLMULQDQ, saved on a detached writer thread. There's no in-game measurement, and the PR says so itself ("no claim on the whole").
Other systems: Windows (COFF/SEH) and Linux (ELF/CFI) both go through the kit's macros, and the test runs both conventions. A CPU without PCLMULQDQ gets the slice-by-8 body, which the release's x86-64-v3 builds also take. GPU vendors, drivers, frame pacing, saves and audio are untouched, because the path doesn't reach them. The build gains one
.Sper module, which is negligible next to the renderer.Switches: none, and none needed (the output is the same bytes).
Reviewed:
ab72ffc3againstcffa2f46(#1947's head when this was cut). The diff has no main merge, and the PR's own commit is the only one pastcffa2f46. Read in full:gpu/asm/crc32.S(the folding, the Barrett reduction, slice-by-8 and the byte loop; the constants checked against the standard bit-reflected CRC-32 set, as Linux'scrc32-pclmuluses),gpu/asm/crc32.h, both callers,tests/test_asm_crc32.py, and the edits totest_pipeline_share.py,test_png_publication.py,test_capture_dimensions.pyand their fixtures. I readlsasm.h'sLSASM_ARGS/LSASM_RODATAandnx2/build.py'sasm_jobsonly where this kernel relies on them. I didn't check the eight tables entry by entry; the test's random input over every length 0–4096 covers them. Nothing was run (a code review).Fixed in this review: nothing.
Checked and fine: register use (rax, rcx, rdx, rsi, rdi, r8–r11, xmm0–5) is all volatile on SysV, and on Win64
LSASM_ARGS 3saves rdi/rsi and moves r8 into rdx. xmm6+ is never touched. Themovdqaconstants are 16-byte aligned under.p2align 6. The fold immediates match the reference (0x01= k4·lo,0x10= lo·mu).psrldq 4+movdstands in correctly for SSE4.1'spextrd. The slice-by-8 step pairs T7..T4 with the CRC-xored word and T3..T0 with the second word, which is correct. Both callers keep their inversions, so the zip's and the PNG chunks' bytes are unchanged. The test compares every length 0–4096 at 8 alignments chained, big buffers, pieces and the known answer, with guard pages on both sides, at both levels and conventions, and with PCLMULQDQ where the CPU has it. A wrong constant or table entry would fail it.Blocking (to change before merge)
gpu/asm/crc32.S:11: the gain doesn't earn the code. Everywrite_pngcaller invk_replay.cpp(around lines 5056, 5622, 5717 and 5733) is inside a detachedstd::thread, andpipeline_share::zipruns once per "Save my pipeline list". So a few ms of CRC on a background thread never reaches a frame. Unless there is a case where this CRC sits on something a player or the farm waits for (if so, measure that), I would close this rather than rework it. If a faster CRC is still wanted, a ~20-line C slice-by-8 shared by both callers would get the same 5.7× without assembly.gpu/vk/pipeline_share.h:16:gpu/vk/pipeline_share.his a recorded source of two guide screenshots (docs/user/images/guide/manifest.json).guide-screenshots.ymlrunscheck_guide_screenshots.py --review-sources, which will exit nonzero withREVIEW REQUIRED. Per standards and the guide README's "Implementation-only change" row, the review record needs the new revision and hash plus a note on why the capture is kept, not a bare hash refresh.cffa2f46, while #1947 is now at186fdb85, and the forge reports this PR as not mergeable. It needs a rebase on #1947's current head (and on main once that merges).Suggestions (the author may take or leave)
.Lcrc_k1k2saying the constants are the standard bit-reflected CRC-32 set (the same values as Linux'sarch/x86/crypto/crc32-pclmul_asm.S). A reader can then check them against a known source instead of deriving them.Testing: the author ran the four checks this touches (pass) and
--changed(its 25 failures fail on #1947's head too) on Windows 11, i7-9700, with llvm-mingw clang 23. It hasn't run in the game. Beanstalk declined the request as written (it can't detect the first non-uniform frame or check PNG/zip integrity). Linuxg++/clang++runs oftest_asm_crc32.pyare still to do. None of this changes the recommendation.Overlaps and merge order: it stacks on #1947 (the kit), which merges first, beside its siblings on the same kit: #2133 (FNV-1a 64, the same question of hot path against code), #2130, #2129, #2128 and #2099. #1709 (a Screenshot control) may call
write_pngtoo. Its writes would also be off the frame, but rebase whichever merges second.@ -0,0 +8,4 @@four 16-byte lanes at a time, then one, and Barrett-reduced to 32 bits (Intel's "Fast CRC Computation for GenericPolynomials Using PCLMULQDQ", the bit-reflected form); the under-16 bytes left go on below;- otherwise, and for what is left, slice-by-8: eight bytes a step through eight tables, then a byte at a time */LSASM_FUNC lsasm_crc32Every CRC this speeds up runs off the frame: write_png is always inside a detached std::thread, and the zip runs once per Save my pipeline list. ~5 ms on a background thread doesn't earn 420 lines of asm in both modules. A C slice-by-8 would give 5.7× if speed is still wanted.
@ -13,6 +13,8 @@#include <string>#include <vector>#include "../asm/crc32.h"This file is a recorded source of two guide screenshots (docs/user/images/guide/manifest.json). The CI's --review-sources will report REVIEW REQUIRED. Record the new reviewed revision and hash, with a note that the visible UI is unchanged.
@HumanBean on your review (74201): you are right, so this is withdrawn and I am closing it. Your blocking points 2 and 3 (the guide-screenshot record and the stale base) fall with it.
I read the callers at
ab72ffc3and on current main:write_pnga player or the farm reaches runs on a detached thread.share_zipruns once per "Save my pipeline list".write_pngcalls are synchronous,RX_VK_SHOT_MADE's made-frame picture on the present path andRX_VK_DUMP's dumps, but both are diagnostic switches that no player or farm run sets.So the micro-benchmark's gain reaches no frame. Thank you for reading the kernel in full. I won't open the C slice-by-8 unless you want it; that is your call. The branch
perf/asm-crc32stays on my fork.Pull request closed