Skip to content

Large mesh stage memory in a device slice: foliage mesh pass 2.86 -> 2.01 ms in Ocarina of Time on M3 Pro - #2308

Closed
AmateurWizrd wants to merge 2 commits into
seedds:mainfrom
AmateurWizrd:feat-mesh-stage-slice
Closed

AmateurWizrd wants to merge 2 commits into
seedds:mainfrom
AmateurWizrd:feat-mesh-stage-slice

Conversation

@AmateurWizrd

@AmateurWizrd AmateurWizrd commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What and why

In Ocarina of Time (0400486024DEC000) the foliage mesh pass took a large share of a Kokiri Forest frame on an M3 Pro. Each 32-thread mesh group declares its whole stage array as threadgroup memory, 5 to 16 KB in the foliage meshes, so few groups fit on a GPU core at once: about 0.09 ms per KB per 16,384 groups.

dmsh_meshstage.py to_stage now takes the array from a device scratch buffer for a mesh shader of 32 threads and 6,000 to 16,384 bytes of stage memory. Lane 0 takes a ticket with a relaxed atomic add and claims the slice at that ticket modulo 8,192 by changing its flag word from 0 to 1 (an atomic exchange; a slice still owned costs a new ticket). The slice is 16 KiB, zeroed as the threadgroup array was, and lane 0 clears the flag after the group's last read, so a slice is reused only after its group finished. The host binds the buffer at DMSH_MESH_SCRATCH_SLOT for shaders whose reflection has mesh_spill. Below about 5.3 KB the device form gained nothing, so those keep threadgroup memory. The chain changes (dmsh_abi.h), so it needs a shader rebuild. The finding is in docs/reference/shaders.md.

Checked

  • Tests: make -C dm/host/tests GAME=0400486024DEC000 run, make -C dm/gfx/tests GAME=0400486024DEC000 run (Apple silicon, Metal), test_dmsh_meshstage.py, DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_meshstage.py OnGpu (one long group among 24,575 short ones a draw: the ticket-modulo rule failed in the first draw, the claimed slice passed 24 draws), python -m unittest discover -s dm/tools/tests. The last has the same failures on main 7c384e7 without this change: test_pr_areas (4 errors, mac/min_os.mk missing in its temporary tree) and test_env_switches (DM_NVN_VCONV_KEEP has no row).
  • Games run: Ocarina of Time v131072, Kokiri Forest. main 7c384e7 against main plus this change, both apps built by build_ipa_from_nsp.py --platform mac-app --show-fps --seen-shaders from the same logs, each with its own prewarmed pipeline files, 0 missing-shader lines in every run. Frames unpaced with the game step fixed, 3 rounds standing (2,000 frames each) and 3 rounds of a route replayed pad read for pad read (1,110 frames each), the two builds alternating.
frame p50, ms round 1 round 2 round 3 mean
standing, main 24.58 24.80 24.70 24.70
standing, this change 23.76 23.69 23.49 23.65
route, main 25.11 24.74 24.99 24.95
route, this change 23.91 23.80 23.91 23.87

GPU p50 22.89 -> 21.83 ms standing, 23.27 -> 22.06 ms on the route; frames over 33.4 ms standing 13 -> 7; frame p95 on the route 28.16 -> 26.84 ms. Screenshots after the judged frames show the same picture (fairies and leaves move). Earlier, standalone: the real translated foliage mesh bodies in a harness ran 20 to 46 % faster for stage arrays of 6.5 KB and more (73dc0b90, 10.3 KB: 0.568 -> 0.332 ms).

  • Devices and OS: MacBook Pro M3 Pro (14-core GPU, 18 GB), macOS 27.3.
  • regress.py impact upstream/main..HEAD: every NVN game through dmsh_abi.h and the chain; Breath of the Wild, Pokémon Scarlet and Tears of the Kingdom by their manifests. Only Ocarina of Time is available here.
  • regress.py check --baseline upstream/main --games 0400486024DEC000 (full): CHANGED, explained: all 204 changed shaders (200 keys) are mesh shaders (by shader_map.tsv), the ones this change moves to a device slice; MSL and reflection change together; 0 newly failing, 0 interface changes, all 42,848 build on both sides. Ocarina of Time has no smoke.tsv route upstream, so the report has no boot runs; the game runs above stand in for them.
report.md

regress.py check (full): CHANGED

Baseline upstream/main 7c384e7, candidate worktree 21cadb9; Apple M3 Pro, macOS 27.3, Xcode 27.2; 1175.1 s

game status shaders (base → cand) newly failing newly building changed MSL interface (new / known) boot fps p50 frame p99 ms peak MB prepare s new RED
Ocarina 0400486024DEC000 CHANGED 42848/42848 → 42848/42848 0 0 204 0 / 0 – – – – – –

Ocarina 0400486024DEC000: CHANGED

  • CHANGED: 204 shaders changed (MSL 204, reflection 204, variants 0)
    • changed shaders: 003fa45149288240, 012ad2c75b59f3d9, 0207d3440d0e8dda, 043caef0b7f6e698, 04452448ac915259, 083017de11d5589e, 086e4404b2932452, 0a5184bfc0ebe4dc, 0aa1ff8c0ce061f8, 0aee1f5eaeb8e0b0, 0c75c8aed6290acf, 0fa5296327f206ae, 0fa8ba0f6457d989, 11174218d5ca5a69, 122faab1d05fee47, 12ab8693a32f85af, 1515d800ca824dec, 17c8ab6419068d4b, 187760e0de3b78ee, 1926f39f751f0832, 1ba45cc5e92558a0, 1d6faf01ebc05e20, 1e1dcd39c29f2e7a, 1eca6967d28032d5, 1f2fb1156a7a57f1, 220921bc1a45140c, 2297f4e480502799, 239b20dbdcb90cba, 25c3d4700ce93152, 25dbd12d550054d0, 27460d7d2e44d06c, 2b79b5950ca5b5b7, 2c806ff0d630a9ac, 2d230886d44b393b, 315ce2f58d370e9a, 321a5382ac85e119, 3439aaa071d868ae, 35785cddc971290c, 3b11d155383d0ae6, 3e5871d52354f82f …
    • time: chain 1174.8 s
- Not checked: other Macs, iOS in a game, the other games `impact` names.

Docs

  • The finding is in docs/reference/shaders.md, and python3 dm/tools/docs_symptoms.py was run
  • A chain tool changed: dmsh_chain.py --header was run and dm/gfx/nvn/dmsh_chain.h is part of the change
  • No game files, keys or data extracted from a game in the change or the attachments

@github-actions github-actions Bot added nvn NVN on Metal and its tests (dm/gfx/nvn, dm/gfx/tests) docs Documentation shader chain The shader translation chain (DMSH_CHAIN): a change rebuilds every game's shaders labels Nov 11, 2026
@akratch

akratch commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

The scratch-ticket lifetime needs a stronger invariant before this can safely become a general rewrite.

Bounding resident groups below 8,192 does not establish that live tickets have distinct residues modulo 8,192. A schedule can keep group 0 running while groups 1 through 8,191 start and finish, then start group 8,192. Only two groups need be resident at any point, yet the last group zeroes and writes group 0's slice. The same argument applies when all those groups come from one large draw. Making the slice count a power of two preserves the arithmetic at uint wrap but does not prevent this reuse.

I checked the allocation rule with this small schedule model:

slices = 8192
live = {0: 0}
for ticket in range(1, slices + 1):
    slot = ticket % slices
    assert len(live) == 1
    if slot in live.values():
        print("live tickets", tuple(live), ticket, "share slot", slot)
        break
    live[ticket] = slot
    del live[ticket]

This is a counterexample to the occupancy argument in the ABI comment. I have not reproduced the collision on an Apple GPU. Could you establish a scheduling guarantee that excludes such overtaking, or make slice reuse depend on a group's completion? A GPU stress check with one long-lived group and many short groups would help validate the ownership rule. The current source/compile tests and the foliage timing route do not exercise it.

neko973 added a commit to neko973/nxnative that referenced this pull request Nov 11, 2026
… tested area at 59-60 fps), DM_PRESENT_LINK=0, the graphics scale tier, the final sweep and soak

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@AmateurWizrd

Copy link
Copy Markdown
Contributor Author

You are right. The comment bounded how many groups are resident, not how long one of them lives, and your schedule breaks it.

It reproduces on an M3 Pro (14-core GPU). The new GPU check draws 24,576 mesh groups in one draw; group 0 keeps reading its slice until 9,216 more tickets were taken. With the ticket-modulo rule it failed in the first draw, three runs out of three: all 32 lanes of group 0 read data another group had written. In one run with a longer spin about 14,500 groups passed group 0 before the rest of the draw waited for it, so the overtaking has a limit on this GPU, but it is well past 8,192.

The new commit makes reuse depend on completion. Lane 0 takes a ticket and claims that slice by changing a per-slice flag word from 0 to 1 with an atomic exchange. A slice whose flag is already 1 belongs to a running group, so the claim takes a new ticket. After the group's last read of the slice (a barrier after the index loop) lane 0 clears the flag. The flags are in the buffer's head, which grows from 64 bytes to 32,832.

One limit is left. After 8,192 tickets with no free slice a group uses its last ticket's slice without owning it. I can only see that happen when a command buffer the GPU dropped leaves flags set, because the host keeps running after a failed command buffer. The host does not clear the flags in that case. Say if you want that in this PR.

The branch also merges current main; only the chain header conflicted.

Checked on the M3 Pro:

  • DMSH_TEST_GPU=1 python3 dm/gfx/tests/test_dmsh_meshstage.py OnGpu: 24 draws with the claimed slice, no lane read foreign data, group 0 saw 9,216 to 9,231 tickets pass in every draw, and every flag was clear afterwards. The test skips on a GPU that never lets 8,192 groups pass a running one.
  • Cost in Ocarina of Time, standing in Kokiri Forest, 3 runs each, interleaved: GPU p50 18.73, 18.77 and 18.83 ms with the ticket rule and 18.79, 18.89 and 18.92 ms with the claim, 0.12 ms between the medians. Both apps come from 0d84a3f7 plus the raw-load change; the claim build has a --seen-shaders library.

Not checked: other Macs, iOS in a game, and make -C dm/gfx/tests run.

lint-python is red on main too: dmsh_entry.py imports dmsh_fetch and no longer uses it. #2266 removes the import.

AmateurWizrd added a commit to AmateurWizrd/nxnative that referenced this pull request Nov 11, 2026
…hain c0dc6a32a147)

Review of seedds#2308: a spilled mesh group took its slice at its ticket modulo
the slice count, so the group that drew ticket + 8192 zeroed and rewrote
the slice of a group still running. Bounding the resident groups does not
bound how far later groups overtake a long one.

Lane 0 now claims a slice: it takes a ticket and changes that slice's
flag word (new in the head, DMSH_MESH_SCRATCH_FLAGS) from 0 to 1 with an
atomic exchange; a slice still owned costs a new ticket. After the last
read of the slice lane 0 clears the flag, so a slice is reused only after
its group finished. After 8192 tickets with no free slice (only flags a
dropped command buffer left set) the group uses the last slice unowned.
The head grows from 64 bytes to 32,832.

test_dmsh_meshstage.py OnGpu (DMSH_TEST_GPU=1) draws 24,576 groups 8
times; group 0 keeps reading its slice until 9,216 more tickets were
taken. On an M3 Pro the old rule failed in the first draw (all 32 lanes
of the long group read another group's data, three runs out of three);
the claimed slice passed 24 draws with no lane wrong and every flag clear.
@AmateurWizrd
AmateurWizrd marked this pull request as draft November 11, 2026 18:33
@AmateurWizrd

Copy link
Copy Markdown
Contributor Author

Converting to draft. I merged main into this branch, which CONTRIBUTING.md says not to do, and the cost measurement compared a full shader library with a partial one. I will rebase it and measure it again with both builds made the same way, then mark it ready or close it.

…ddfd622)

A mesh shader's stage array of 6-16 KB of threadgroup memory limited how many 32-thread mesh groups an Apple GPU
core runs at once. Mesh shaders of that size now take a ticketed 16 KiB slice of one private scratch buffer (8192
slices, above the 96 resident groups per core of an 80-core part), bound at DMSH_MESH_SCRATCH_SLOT for shaders whose
reflection has mesh_spill. Ocarina of Time, Kokiri Forest, M3 Pro: foliage pass 2.86 -> 2.01 ms.

(cherry picked from commit 2bb6796)
…hain c0dc6a32a147)

Review of seedds#2308: a spilled mesh group took its slice at its ticket modulo
the slice count, so the group that drew ticket + 8192 zeroed and rewrote
the slice of a group still running. Bounding the resident groups does not
bound how far later groups overtake a long one.

Lane 0 now claims a slice: it takes a ticket and changes that slice's
flag word (new in the head, DMSH_MESH_SCRATCH_FLAGS) from 0 to 1 with an
atomic exchange; a slice still owned costs a new ticket. After the last
read of the slice lane 0 clears the flag, so a slice is reused only after
its group finished. After 8192 tickets with no free slice (only flags a
dropped command buffer left set) the group uses the last slice unowned.
The head grows from 64 bytes to 32,832.

test_dmsh_meshstage.py OnGpu (DMSH_TEST_GPU=1) draws 24,576 groups 8
times; group 0 keeps reading its slice until 9,216 more tickets were
taken. On an M3 Pro the old rule failed in the first draw (all 32 lanes
of the long group read another group's data, three runs out of three);
the claimed slice passed 24 draws with no lane wrong and every flag clear.

(cherry picked from commit 1111004)
@AmateurWizrd
AmateurWizrd marked this pull request as ready for review November 12, 2026 04:42
seedds added a commit that referenced this pull request Nov 15, 2026
…e slice (PR #2308)

A mesh stage whose threadgroup arrays reach 6,000 bytes keeps them in a 16 KiB slice of a
device pool instead, so more groups fit on a GPU core. A group's lane 0 claims a slice with a
compare-and-swap of the slice's flag to its submission's tag, only when the flag is 0 or names
a submission the host has seen finish (DONE, written from post_complete); it tries up to 64
tickets. A group that finds none draws nothing and is counted (red line 173), so no group ever
uses a slice it does not own. The pool is sized from the GPU core count (4096 slices on a
20-core M4 Pro, 2048 on iOS).

Checked: test_dmsh_meshstage.py OnGpu on an M4 Pro (a long-lived group, stale and live tags
across the 32-bit wrap, a 32-slice pool); Ocarina of Time: all 42,848 shaders build, 204 mesh
shaders change; Kokiri Forest bench: slices used, none missing, no red line, shots alike.
Mario Kart World: one changed shader, not drawn on its route.

Co-authored-by: AmateurWizrd <196495025+AmateurWizrd@users.noreply.github.com>
@seedds

seedds commented Nov 15, 2026

Copy link
Copy Markdown
Owner

Landed on main as d7877c5, with you as co-author. Thanks for the measurements; they are in the reference entry.

Your slice layout, the 6,000-byte threshold, the buffer slot and the reflection flag are kept. What changed is how a group gets its slice. In this PR, after 8,192 failed claims a group fell back to the last slice without owning it, so two groups could share one.

  • Claim: each slice's flag holds its owner's tag, the submission's fence. Lane 0 swaps the flag to its own tag with a compare-and-swap, and only when the flag is 0 or names a submission the host has seen finish (DONE, written from post_complete). It tries up to 64 tickets. Device-scope fences sit after the claim and before the release.
  • No free slice: the group draws nothing and returns, and is counted under red line 173. It never touches a slice it doesn't own.
  • Pool: sized from the GPU core count, at least 2 × cores × 96 slices: 4,096 slices (64 MiB) on a 20-core M4 Pro, 2,048 on iOS.

Checks on an M4 Pro:

  • DMSH_TEST_GPU=1 test_dmsh_meshstage.py OnGpu: a long-lived group while 2,714–5,131 tickets passed it; stale and live tags across the 32-bit wrap; a 32-slice pool (23,817 groups ran and 759 drew nothing, with no foreign reads).
  • regress.py, Ocarina: 42,848 of 42,848 shaders build on both sides; 204 changed, all of them the moved mesh shaders.
  • bench.py kokiri-deck, 3 runs a side against the same base: slices used, no group without one, no red line, matching shots. GPU p50 in the warm runs was 14.58 / 14.60 ms on main against 13.87 / 15.10 ms with slices, too close to call on this Mac. Main's frame step held 2 vsyncs and the slices side mostly 1 (40 vs 43–59 fps).

Not run: an iPhone, other Macs. If you rerun your M3 Pro rounds on main, I'd like to know whether the gain still holds with the lease.

@Ayymeric

Ayymeric commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Measured on a base M4 Mac mini (10-core GPU, 16 GB, macOS 27.2): this PR merged onto main 0def324 (conflicts in dmsh_build.py and dmsh_meshstage.py with main's newer pb primitive path; resolved by keeping both, and test_dmsh_meshstage.py passes, 50 tests), Ocarina of Time v131072's shaders rebuilt (chain 95d349694d04) with their own pipeline archive warmed by a first run. scripts/bench.py route kokiri-deck, window, docked, Dynamic resolution off, three runs each. GPU = median @gpu_ms over the standing part of the window (85–104 s):

GPU p50, standing
main 24.73 / 24.72 / 24.84 ms
this PR 23.76 / 23.78 / 23.76 ms

About −1.0 ms a frame, no red lines. A Mac app with this PR and #2573 was played by the owner for about 40 minutes (Kokiri Forest, the Deku Tree) with no rendering problem reported.

A frame from that build (16:9, Kokiri Forest, DM_CTL shot):

Kokiri Forest, 16:9, main + #2308 + #2573

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

Labels

docs Documentation nvn NVN on Metal and its tests (dm/gfx/nvn, dm/gfx/tests) shader chain The shader translation chain (DMSH_CHAIN): a change rebuilds every game's shaders

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants