The shader build finishes its shaders in worker processes, so a cold build uses the cores it has: finishing a shader (the MSL rewrites, its reflection, its outputs and the cache) is Python, and the threads that did it share one GIL, so one core finished every shader while the Metal compiles they waited on left the others idle. Ocarina of Time's whole Mac map (0400486024DEC000, 42,848 shaders) on an M3 Max with 16 cores, J=16: 3,506 s with the build at 104 % CPU and 4 to 5 cores busy, 1,826 s with 16 workers; every shader restored from the cache 888 to 191 s (the PR author's runs). dmsh_build.py now finishes them in DMSH_PROCS worker processes (default J; 0 = threads, as before): forks of the build made once, after the cache check and before its first thread, so they have every table and fingerprint it read (spawned workers would run the script again, and its start clears the outputs), each with its own connection to cas.db (shader_cache.Store.forked). The build translates the batches itself and hands each shader's job to a worker; results and counts come back in batch order, so the summary, the progress file and every output are those of the threads. The next batch is handed out before this one is done (two at most), so no worker waits for a batch's slowest shader; paired vertex shaders still wait for every other shader. The workers, the batch overlap, the diagnosis and those measurements are PR #2255's. Added here: the precompiled Metal headers are made before the fork (each worker made its own, three compiles a target, in a folder nothing removed without the PR's WORK override, which is gone: Red Dead Redemption's build peaked at 1.4 GB with them, 0.8 GB now); a worker that dies stops the build with one [RED] line instead of a traceback (checked by killing one); the reference entry (A shader build's Python finishes one shader at a time), which also resolves the open note under Rewrites that try every character of a large source, Ocarina of Time's note, and the memory advice in docs/development.md. PR #2035 solved the same problem by running the build as J / 3 copies of itself (Ocarina of Time on an M5 Max 3,002 to 1,298 s; 1.41 times faster on an M3 Pro for 1.3 GB more, tobiashenn's run); side by side on one Mac it gained less (Red Dead Redemption: Mac 75 to 58 s, Mac and iOS 104 to 95 s against its own older main) and compiled about 9 % of the Metal sources twice, so it is not taken; its measurements are in the entry. Checked on an M6 (12 cores, 16 GB, J=12, empty cache, another game running beside it) against main f75ac06e: Red Dead Redemption's 3,628 shaders, Mac 54 to 35 s, Mac and iOS 84 s to 53 and 63 s, restored from the cache 11 to 13 s (the headers are made though nothing compiles); 1,920 of Metroid Prime 4: Beyond's shaders 105 to 72 s, 89 s with DMSH_PROCS=6. Peak memory (summed resident size of the process tree, which counts the forks' shared pages once each): Red Dead Redemption 0.45 to 0.8 GB, the Metroid Prime 4 shaders 1.1 to 3.4 GB, 2.0 GB with 6 workers; a worker holds about 35 MB, the rest is J compilers running at once. Identical: Red Dead Redemption's Mac library (15,542 files) apart from the chain version and _b_cas.txt, and its iOS library (11,912 files); the author's 173,316 files of Ocarina of Time. Tests: test_shader_cache (forked workers share the file), test_shader_toolchain_cache, test_shader_pch, test_nsp_chain, test_docs. The chain version changes (dmsh_build.py), so every game's shaders are translated again once, their Metal compiles reused. Not run: regress.py check (the outputs are the same bytes), a Mac with 8 GB, a whole large map with iOS libraries, a large warm build here. lint_python.py lists one finding outside its baseline, an unused import in dmsh_entry.py, which this does not touch (PR #2255)

Co-authored-by: cashcon57 <[email protected]>
This commit is contained in:
seeddsandcashcon57 committed 2026-11-11 20:30:10 +08:00
1 parent f75ac06e85
commit 8b55ebb364
9 files changed
+113 -21

No files matched your search

+1
View File
@@ -125,6 +125,7 @@ Its 37 kernels that correct samples, NDSR's network among them, gave about 0.25
## Found on this game
- [A shader build's Python finishes one shader at a time](../../../docs/reference/shaders.md#a-shader-builds-python-finishes-one-shader-at-a-time): resolved, the whole Mac map's cold build took 58 minutes on an M3 Max with 4 to 5 of its 16 cores busy; 30 minutes with worker processes.
- [Reads past a uniform binding's size](../../../docs/reference/shaders.md#reads-past-a-uniform-bindings-size): open ([GitHub issue #2218](https://github.com/seedds/nxnative/issues/2218)), long white streaks from the horses at Lon Lon Ranch and from Link's slingshot, and flickering parts of the slingshot and of the ReDeads' faces, reported with the uniform read bound on. The bound now takes the size the driver gives the GPU, rounded up to 256 bytes; the game binds sizes that are not multiples of 256. Not reproduced here before or after (the slingshot at Link's house, the ReDeads of adult Castle Town), so the reporters' retest decides.
- [The blend helper's output reference on iOS](../../../docs/reference/shaders.md#the-blend-helpers-output-reference-on-ios): resolved, 22,296 of 42,848 Mac shaders failed to compile on macOS 26 ([GitHub issue #2272](https://github.com/seedds/nxnative/issues/2272)); the Mac compile now names the host's minimum macOS.
- [A NaN colour under a zero blend weight](../../../docs/reference/shaders.md#a-nan-colour-under-a-zero-blend-weight): resolved, white clouds over the ground mist between Kokiri Forest and Hyrule Field and over the ferns at the camera in Kokiri Forest ([issue #1839](https://github.com/seedds/nxnative/issues/1839)). The mist shader `5ad65c0eefd09c7f` writes NaN at alpha 0 where its layer has density 0; NVIDIA's blender, with the option NVN's driver sets, adds nothing there, Apple's stored the NaN.
+1 -1
View File
@@ -1,3 +1,3 @@
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the B shader library translation chain version this source tree expects (default options), one for every game;
// the host loads only <library dir>/b-<V>/. Run dmsh_chain.py --header after changing the chain's tools and commit this file with the change
#define DMSH_CHAIN "1fa63cf7c7ae"
#define DMSH_CHAIN "2afd39090b76"
+66 -14
View File
@@ -7,12 +7,12 @@
# at the end (publish_library), so a build, stopped or not, leaves a few files and not one per shader output (Octopath Traveler 0, stopped in its compile: 68,230 files). The translator's
# working files go into a folder per batch of shaders, removed when the batch is done; a working folder whose build is gone is removed at the next start (sweep_work).
# A full build (no keys) also stamps both directories with the game and the digest of its profile inputs (inputs.tsv) and writes the profile's c1_full.tsv and cb_extent.tsv (c1_guard.py, cb_extent.py)
# from its Mac outputs. One output directory per game: the chain version is the same for every game Environment: DM_GAME=game profile (required, dm/games/<id>), XLATE=path to the translation tool (default the in-repo dmsh_xlate_bin), DMSH_CAS=the compile cache, one file (shader_cache.py; default <output cache dir>/cas.db), DMSH_PREFILL=Mac library root[=iOS library root] (separated by :, their b-*/ go into the MSL-keyed compile cache first; sibling b-*/ always do), J=concurrency
# from its Mac outputs. One output directory per game: the chain version is the same for every game Environment: DM_GAME=game profile (required, dm/games/<id>), XLATE=path to the translation tool (default the in-repo dmsh_xlate_bin), DMSH_CAS=the compile cache, one file (shader_cache.py; default <output cache dir>/cas.db), DMSH_PREFILL=Mac library root[=iOS library root] (separated by :, their b-*/ go into the MSL-keyed compile cache first; sibling b-*/ always do), J=concurrency, DMSH_PROCS=processes that finish shaders (default J; 0 = threads of this process, see fin_worker)
# Build output: <key>_b.metallib, <key>_b.json (replay reflection, including drv_reads, the runtime read offsets into driver segments c0 / c2), <key>_b.metal (MSL)
# Environment IOSOUT=dir: the same MSL also goes through dm/ios/tools/ios_metal.compile to produce an iphoneos metallib + reflection (chain_metal records the iOS compile convention)
# Final summary: success / failure counts and the distribution of reasons; distribution of driver segment read offsets (those outside the range the replay layer can fill are listed separately);
# a [RED] line per shader that built but lost something (shader_regressions.report_losses), which does not change the exit status
import atexit, inspect, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, time, collections, threading, concurrent.futures as cf
import atexit, inspect, multiprocessing, os, re, sys, json, mmap, struct, hashlib, shutil, subprocess, tempfile, time, collections, threading, concurrent.futures as cf
import dmsh_geometry, dmsh_atomic, dmsh_wide, dmsh_meshstage, dmsh_rewrite, dmsh_reflect, dmsh_entry, dmsh_abi as abi # abi: the driver segment layout and the binding kinds the host shares (dm/gfx/nvn/dmsh_abi.h)
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # Workspace root (game files, build outputs and run artifacts are all under it)
HOME = os.path.expanduser('~')
@@ -847,6 +847,7 @@ def finish(key, w, j, c1):
keys = build_keys(want, loc, PAIRS)
if want: want = set(keys) # dependency outputs are cleaned too, so a failed pixel build cannot leave old MSL for padding
NJ = int(os.environ.get('J', '8'))
PROCS = int(os.environ.get('DMSH_PROCS', NJ)) # processes that finish shaders (fin_worker); 0: NJ threads of this one
BATCH = 4 * NJ # shaders translated and finished together: the next batch is translated while this one is finished, and a shader's working files go when it is (fin).
# Minecraft Dungeons II, 15,826 shaders: at most 3,279 files under the build folder with batches of 256 removed whole, 68,230 before batches (Octopath Traveler 0's stopped build)
# A full build starts from no shader outputs, a partial one from none of the keys it builds, so what a run leaves is what it built: every output is restored from the cache anyway.
@@ -981,19 +982,70 @@ def fin(key, wb):
with os.scandir(wb) as it: # its working files (<key>.bin / .spv / .res.json / .metal, the geometry variants' <key>_g<n>.*, job1_<key>.json)
for e in it:
if e.name.startswith((key, 'job1_' + key)) and e.is_file(): os.unlink(e.path)
with _prog['lock']: DONE['n'] += 1; n = DONE['n']
progress('compiling', n, len(keys), cached=len(cache_hits), misses=NMISS)
# Two phases: paired vertex shaders read their pixel shaders' MSL (vs_pad), so they go last, in batches of their own. The next batch is translated while this one is finished
finished()
def finished(*_): # one more shader finished, for the progress
with _prog['lock']: DONE['n'] += 1; n = DONE['n']
progress('compiling', n, len(keys), cached=len(cache_hits), misses=NMISS)
# The shaders are finished in worker processes (PROCS of them): fin's own Python, the rules that rewrite the MSL above all, holds the GIL, and with threads one core ran it for all of them
# while the Metal compiles they waited on ran at about a third of the machine (Ocarina of Time, 16 cores: 104% CPU for this process, 4-5 cores busy in all). A worker is a fork of this
# process, made before any thread starts, so it has every table and fingerprint read above; spawn would run this script again, its start removing the outputs. Each opens its own
# database connection (SQLite's does not cross a fork), and its outputs and cache entries go into the shared file as a thread's did; what fin returns and what it counted come back here,
# in the batch's order, so the results, the summary and every file written are those of the threads (DMSH_PROCS=0). The precompiled Metal headers (dmsh_pch.py) are made here before the
# fork: a worker would make its own (three compiles for each target in each worker) in a folder that nothing removes, as a worker process ends without atexit. A worker that dies
# (killed, out of memory) stops the build with one line
COUNTERS = (PRE_STATS, VIN_STATS, PULL_STATS, SIDE_STATS, BF_STATS, MTL.stats)
def worker_start():
global PROGRESS
STORE.forked()
PROGRESS = None # this build writes it, as the workers' shaders finish
def fin_worker(key, wb, job, err):
"""fin in a worker process, given what translate left for the shader in this process (its job and c1, its translator error) → (fin's result, what it added to the counters)"""
jobs.clear(); c1s.clear(); xerr.clear()
if job: jobs[key], c1s[key] = job
if err is not None: xerr[key] = err
for c in COUNTERS: c.clear()
return fin(key, wb), [dict(c) for c in COUNTERS]
def submit(batch, wb): # a translated batch's shaders to finish → their futures
if not px: return [ex.submit(fin, k, wb) for k in batch]
fs = [px.submit(fin_worker, k, wb, (jobs.pop(k), c1s.pop(k)) if k in jobs else None, xerr.get(k)) for k in batch]
for f in fs: f.add_done_callback(finished)
return fs
def results(fs): # → what fin returned for them, in their order (a worker's counts added to this process's)
out = []
for f in fs:
r = f.result()
if px:
r, counts = r
for c, n in zip(COUNTERS, counts): c.update(n)
out.append(r)
return out
px = cf.ProcessPoolExecutor(PROCS, mp_context=multiprocessing.get_context('fork'), initializer=worker_start) if PROCS and keys else None
if px:
if 'mac' in TARGETS: dmsh_pch.header(MAC_RUN + METAL_DEPTH)
if IOSOUT: dmsh_pch.header(ios_metal.METAL + ios_metal.DEPTH)
px.submit(int).result() # forks every worker now, while this process has no other thread
# Two phases: paired vertex shaders read their pixel shaders' MSL (vs_pad), so they go last, in batches of their own, once every shader before them is finished. The next batch is
# translated while this one is finished, and handed out before this one is done, so that no worker waits for the slowest shader of a batch; a batch's working folder goes when it is done
batches = [b[i:i + BATCH] for b in ([k for k in keys if k not in PAIRS], [k for k in keys if k in PAIRS]) for i in range(0, len(b), BATCH)]
res = []
with cf.ThreadPoolExecutor(1) as tx, cf.ThreadPoolExecutor(NJ) as ex:
nxt = tx.submit(translate, batches[0]) if batches else None
for i, batch in enumerate(batches):
assert nxt is not None
wb = nxt.result()
nxt = tx.submit(translate, batches[i + 1]) if i + 1 < len(batches) else None
res += list(ex.map(lambda k, wb=wb: fin(k, wb), batch))
shutil.rmtree(wb, ignore_errors=True)
res, busy = [], [] # busy: the batches handed out, oldest first: (working folder, futures)
def collect(left): # the results of the oldest batches handed out, until left are
while len(busy) > left:
wb, fs = busy.pop(0); res.extend(results(fs)); shutil.rmtree(wb, ignore_errors=True)
try:
with cf.ThreadPoolExecutor(1) as tx, cf.ThreadPoolExecutor(NJ) as ex:
nxt = tx.submit(translate, batches[0]) if batches else None
for i, batch in enumerate(batches):
assert nxt is not None
wb = nxt.result()
nxt = tx.submit(translate, batches[i + 1]) if i + 1 < len(batches) else None
if batch[0] in PAIRS and i and batches[i - 1][0] not in PAIRS: collect(0) # the first paired batch
busy.append((wb, submit(batch, wb)))
collect(1)
collect(0)
except cf.process.BrokenProcessPool:
sys.exit(f'[RED] a shader build worker process stopped (killed, or out of memory) with {len(keys) - len(res)} of {len(keys)} shaders unfinished; run the build again, '
f'with fewer workers (DMSH_PROCS) if memory ran out: what it finished is in the cache')
if px: px.shutdown()
# Passthrough geometry as mesh shaders (dmsh_mesh.py): <vertex key>_<geometry key>_m3 for each pair in the profile's geo_mesh.tsv whose two libraries exist; the host
# draws a lean triangle-list geometry draw with it when its pair has one, and through the compute path otherwise (nvn_geometry.inc geo_mesh_draw)
MESH_STATS = collections.Counter()
+7 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
# The shader build's compile cache as one file, cas.db, read and written in place. It was a folder of a few files per shader (Metroid Dread: 84,541 files), kept as a tar between builds and unpacked
# for each build that ran. Nothing is unpacked now: an entry goes in and comes out by its name, and a file a tool needs is written only then.
# SQLite, as it is in Python and takes several writers: dmsh_build.py's threads share one connection, and regress.py's chain builds and the NSP script can share a game's file at once (the wait is SQLite's).
# SQLite, as it is in Python and takes several writers: dmsh_build.py's threads share one connection (its worker processes have one each: forked), and regress.py's chain builds and the NSP script can share a game's file at once (the wait is SQLite's).
# Two tables: entry (name, the blob it names, when it was written) and blob (the bytes, once each). A library kept under its MSL's digest and under its shader's digest was one APFS clone of the other; inside
# one file it would be two copies, so bytes are stored by their hash. A file removed from the cache gives its pages back at the next prune (incremental vacuum), with no copy of the file.
# It only saves work: a damaged file costs the work it held and is made anew, and a full drive is one [RED] line. An entry is written and read whole, so its file is never seen half written.
@@ -35,6 +35,12 @@ class Store:
except sqlite3.DatabaseError as e:
if not self._damage(e): raise
def forked(self):
"""A connection of its own in a forked process (dmsh_build.py's workers): SQLite's must not be used across a fork, not even closed, so the inherited one is only kept"""
self._inherited = self.db
self.lock = threading.RLock()
self._open()
def _damage(self, e): # True when e says the file is damaged, which is now made anew
if not any(w in str(e) for w in _DAMAGED): return False
self.say(f'[RED] the shader compile cache {self.path} is damaged, and is made anew: {e}')
+16
View File
@@ -8,6 +8,13 @@ sys.path.insert(0, str(REPO / 'dm/tools'))
import shader_cache
D1, D2, D3 = 'a' * 64, 'b' * 64, 'c' * 64
FORKED = None # the store test_forked_workers_share_it's workers inherit
def forked_work(i):
s = FORKED; assert s is not None
for j in range(300): s.put(f'f{i}/{j}', f'{i}'.encode() * 1000); assert s.get(f'f{i}/{j}') == f'{i}'.encode() * 1000
return s.get('before')
class Base(unittest.TestCase):
@@ -87,6 +94,15 @@ class Writers(Base):
self.assertEqual([p.wait() for p in ps], [0, 0, 0, 0])
self.assertEqual(len(self.store.names('p')), 1200)
def test_forked_workers_share_it(self): # dmsh_build.py's worker processes: forks of a process that has the file open, each with a connection of its own
import concurrent.futures as cf, multiprocessing
global FORKED; FORKED = self.store
self.store.put('before', b'0')
with cf.ProcessPoolExecutor(4, mp_context=multiprocessing.get_context('fork'), initializer=self.store.forked) as ex:
self.assertEqual(list(ex.map(forked_work, range(4))), [b'0'] * 4)
self.assertEqual(len(self.store.names('f')), 1200)
self.store.put('after', b'1'); self.assertEqual(self.store.get('after'), b'1') # the inherited connection still works here
def test_a_killed_writer_loses_only_what_it_had_not_committed(self):
code = ("import os, sys; sys.path.insert(0, sys.argv[1]); import shader_cache\ns = shader_cache.Store(sys.argv[2]); s.put('done', b'1')\n"
"s.db.execute('BEGIN IMMEDIATE'); s.put('half', b'2'); os.kill(os.getpid(), 9)\n")
@@ -50,7 +50,7 @@ class ShaderCache(unittest.TestCase):
STAMP_BEFORE=None, INPUTS='inputs')
(root / 'out').mkdir()
names = {'tool_fingerprint', 'shader_key', 'cache_path', 'cache_outputs', 'restore_cache', 'publish_cache', 'atomic_json', 'cache_meta_path',
'vs_pad', 'partner_inputs', 'label_dir', 'output', 'commit', 'publish_library'}
'vs_pad', 'partner_inputs', 'label_dir', 'output', 'commit', 'publish_library', 'submit', 'results'}
tree = ast.parse((TOOLS / 'dmsh_build.py').read_text())
self.tree = tree
nodes: list[ast.stmt] = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names]
@@ -232,10 +232,10 @@ class ShaderCache(unittest.TestCase):
# the batches, then the loop that translates and finishes them (the translator and fin substituted)
start = next(i for i, n in enumerate(self.tree.body) if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == 'batches' for t in n.targets))
end = next(i for i, n in enumerate(self.tree.body) if i > start and isinstance(n, ast.With)) + 1
end = next(i for i, n in enumerate(self.tree.body) if i > start and isinstance(n, ast.Try)) + 1
work = Path(self.tmp.name) / 'work'
def translate(batch): work.mkdir(exist_ok=True); return str(work)
self.ns.update(cf=cf, NJ=1, BATCH=1, keys=keys, fin=lambda key, wb: finish_key(key), translate=translate)
self.ns.update(cf=cf, NJ=1, BATCH=1, keys=keys, fin=lambda key, wb: finish_key(key), translate=translate, px=None) # finished in threads (DMSH_PROCS=0)
exec(compile(ast.Module(body=self.tree.body[start:end], type_ignores=[]), str(TOOLS / 'dmsh_build.py'), 'exec'), self.ns)
self.assertEqual(built, [pixel, vertex])
self.assertIn('dm_pad7 [[user(locn7)]]', (out / (vertex + '_b.metal')).read_text())
+1
View File
@@ -1101,6 +1101,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
- the NSP script's Mac or iOS shader step for a game with very large shader packages runs at one or two shaders a second whatever `J` is. Its Python process sits at one full core, mostly system time, while few `metal` compiles run. Pokémon Pokopia (4.4 GB of packages, 131,426 shaders): players reported ETAs of 20 to 200 hours (seedds/nxnative#1036). → [A shader build that keeps its packages in memory runs one worker at a time](../reference/shaders.md#a-shader-build-that-keeps-its-packages-in-memory-runs-one-worker-at-a-time)
- the Mac or iOS shader step of a game with a large map still takes many hours with every worker busy, and a `metal -c` of a translated shader takes about 0.7 s of CPU, nearly all in the front end. Optimising adds about 0.1 s, and an empty shader takes 0.025 s. Pokémon Pokopia's 131,426 shaders: about 9 hours on an M4 Pro (seedds/nxnative#1036). → [Each Metal compile instantiates Metal's texture classes again](../reference/shaders.md#each-metal-compile-instantiates-metals-texture-classes-again)
- the shader step of a game with large translated sources has fewer Metal compiles running than `J` asks for, and `dmsh_build.py`'s own process stays busy on one core between them. Pokémon Pokopia's sources average 220 KB, and the builder spent about 0.12 s of Python on each shader, all but its system calls under the GIL, which alone would have come to about 4.2 hours of its full build. → [Rewrites that try every character of a large source](../reference/shaders.md#rewrites-that-try-every-character-of-a-large-source)
- a cold shader step leaves about half the cores idle whatever `J` is, and `dmsh_build.py`'s own process stays at one full core from start to end. Ocarina of Time's whole Mac map, 42,848 shaders: 3,506 s on an M3 Max with 16 cores (`J=16`, the build at 104% CPU, 4 to 5 cores busy in all), 3,002 s on an M5 Max with 18 cores. → [A shader build's Python finishes one shader at a time](../reference/shaders.md#a-shader-builds-python-finishes-one-shader-at-a-time)
- two builds of the same shaders give different `_bl` or `_bf` libraries for some keys, of the same size, 46 bytes apart, while their MSL is the same. A byte comparison of two library folders reports them, and `regress.py` can report them as changed variants. → [A library that depends on its source's file name](../reference/shaders.md#a-library-that-depends-on-its-sources-file-name)
- the Mac or iOS shader step of a game with many pixel shaders spends most of its Metal compiles on libraries that few draws load: Pokémon Pokopia's whole map took 366,805 compiles, about 57% of them for `_ba` and `_bl`, and its runs opened none of the 5,775 of each. → [One compile for a pixel shader's side entry points](../reference/shaders.md#one-compile-for-a-pixel-shaders-side-entry-points)
- the first Mac shader build of a title, with an empty output directory and CAS and no keys, takes tens of minutes while `J` Metal workers stay busy. On an Apple M2 MacBook Pro at `J=8`, Mario Kart 8 Deluxe took 22:46 (1366 s) and Super Mario Odyssey 30:02 (1802 s). → [Cold Mac shader builds compile each pixel shader more than once](../reference/shaders.md#cold-mac-shader-builds-compile-each-pixel-shader-more-than-once)
+1
View File
@@ -692,6 +692,7 @@ Notes on these steps:
- After a chain change, `python3 dm/gfx/tools/shader_regressions.py $W/build/cache/metal_shader_cache` lists the shaders that translated in the previous `b-*/` there and fail in the current one (exit status 1), as the NSP script does after its shader step.
- `dmsh_build.py` compiles each shader's Metal source through a cache keyed by that source, the compile flags and the compiler (`dm/gfx/tools/dmsh_mtlcache.py`, as `metallib/` entries of `<cache>/cas.db`). A chain change that leaves a shader's MSL unchanged costs that shader no Metal compile while the cache format and compiler stay unchanged. Before building, the cache takes libraries from earlier `b-*/` folders beside its output (and beside `IOSOUT`), and from `DMSH_PREFILL=<Mac root>[=<iOS root>]` (several separated by `:`). Every imported library must record the current flags and compiler identity in its reflection; unmarked legacy libraries are rebuilt. A fresh compile of two shaders per stage also checks their bytes. The summary line `Metal cache:` shows reused, compiled and filled counts per target.
- Its Metal compiles use a precompiled header of Metal's texture classes (`dm/gfx/tools/dmsh_pch.py`), about half of a compile's CPU, with byte-identical output ([Each Metal compile instantiates Metal's texture classes again](reference/shaders.md#each-metal-compile-instantiates-metals-texture-classes-again)). `DMSH_PCH=0` compiles without it.
- It finishes the shaders (the MSL rewrites, reflection and the Metal compile each waits on) in `DMSH_PROCS` worker processes, by default as many as `J`: in threads, that Python held the GIL and the build kept 4-5 of an M3 Max's 16 cores busy. The workers are forked after the cache check, before any thread starts, and each opens its own connection to `<cache>/cas.db`; their results come back in batch order, so every output is the same bytes as with threads. `DMSH_PROCS=0` finishes them in threads, and a count below `J` lowers the build's peak memory (about `J` Metal compilers run at once with the default) for some of the gain. Ocarina of Time's 42,848 shaders with an empty cache on an M3 Max: 3,506 s in threads, 1,826 s with 16 workers ([A shader build's Python finishes one shader at a time](reference/shaders.md#a-shader-builds-python-finishes-one-shader-at-a-time)).
- Each shader's cache key (`shader_key`) includes `CODE_FP`, a hash of the *code form* (`dmsh_chain.code_form`: the AST, with docstrings and the rule functions' bodies removed) of `dmsh_build.py` and its helper modules. An edit that cannot change the output (a comment, a docstring, blank lines, formatting) keeps every shader's key, so the next build restores them all instead of translating them again; any change to code, a constant, a string literal or a default argument still rebuilds all of them. The chain version is not touched by this: it still hashes whole files.
- `build_ipa.sh` takes the rewritten modules from `$W/build/patched_<package>` and the RomFS image from `$W/data/<package>/RomFS.img` (legacy folders are also accepted); `PATCHED` and `ROMFS` override them. In unsigned IPA mode, `pack_ipa.py` packs the shader libraries, RomFS and add-on content beside the app Xcode built, as `DmIOS.app/msl/b-<chain version>`, `romfs` and `aoc`. An NVN game's libraries go in as the one file `msl/b-<chain version>.img`; with `DM_SHADER_FILES=1` (the NSP script's `--shader-files`) they go in as its separate files, `msl/b-<chain version>/`, whatever its size, for install tools that cannot copy a large file ([AltServer](reference/packing.md#altserver-cannot-install-a-file-of-2-gib-or-more)). Prepared Xcode projects instead sync these resources into the app before signing.
- It also bundles a standard font (macOS's Arial Unicode, `STD_FONT=` overrides it) and the generated `nintendo_ext.ttf`.
+17 -2
View File
@@ -2192,7 +2192,7 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
- **Symptom:** the Mac or iOS shader step of a game with a large map still takes many hours with every worker busy, and a `metal -c` of a translated shader takes about 0.7 s of CPU, nearly all in the front end. Optimising adds about 0.1 s, and an empty shader takes 0.025 s. Pokémon Pokopia's 131,426 shaders: about 9 hours on an M4 Pro ([seedds/nxnative#1036](https://github.com/seedds/nxnative/issues/1036)).
- **Cause:** a translated shader's argument buffer names several texture types, and Metal's texture classes are large templates. The compiler's module cache holds the templates but not their instantiations, and each shader is a new `metal` process, so it instantiates them again, along with a `memory_coherence_device` copy of each it uses: 722 of a typical shader's 902 ms of front end by `-ftime-trace`, against about 180 ms for the shader's own text. Declaring the argument buffer alone took 0.37 s of that shader's compile.
- **Fix:** `dm/gfx/tools/dmsh_pch.py` makes one precompiled header per compile convention at a process's first compile, holding those instantiations, and `dmsh_build.py` and `ios_metal.py` compile with `-include-pch`. The header adds only the two includes the sources start with and declares no name, and a class left out of it costs only time. The output is byte-identical, so the compile records and the Metal compile cache's keys stay as they were. `make` checks this on a test shader and builds without the header if a compiler differs, and a compile that fails with the header runs again without it, so a failure reports what a plain compile reports. `DMSH_PCH=0` turns it off. The Vulkan and OpenGL shader tools (`vk_shaders.py`, `gl_shaders.py`) do not use it.
- **Fix:** `dm/gfx/tools/dmsh_pch.py` makes one precompiled header per compile convention at a process's first compile (`dmsh_build.py` asks for them before it forks its workers), holding those instantiations, and `dmsh_build.py` and `ios_metal.py` compile with `-include-pch`. The header adds only the two includes the sources start with and declares no name, and a class left out of it costs only time. The output is byte-identical, so the compile records and the Metal compile cache's keys stay as they were. `make` checks this on a test shader and builds without the header if a compiler differs, and a compile that fails with the header runs again without it, so a failure reports what a plain compile reports. `DMSH_PCH=0` turns it off. The Vulkan and OpenGL shader tools (`vk_shaders.py`, `gl_shaders.py`) do not use it.
- **Measurement:** cold builds of 1,019 Pokopia shaders on an M4 Pro (`J=10`, with other jobs on the Mac): Mac child processes 2,343 to 975 s of CPU, wall 253–263 s to 176–182 s; iOS child processes 981–1,077 to 574–605 s, wall 179–233 s to 130–153 s. At that rate the whole Mac map would take about 6.4 hours instead of about 9 (not run). All 37,611 Mac files of 8,157 Pokopia shaders and all 3,675 iOS files of 1,020 came out byte-identical with and without the header, as did 1,600 compiles of eight games' shaders.
- **Open:** wall time fell less than CPU, as the builder's Python took about 0.12 s a shader under the GIL ([Rewrites that try every character of a large source](#rewrites-that-try-every-character-of-a-large-source) lowered that).
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md#found-on-this-game).
@@ -2204,10 +2204,25 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
- **Cause:** patterns with no literal start, which `re` can only try at every character: `_once` in `dmsh_fetch.py` began with a lookbehind and ran 24 times a pixel shader at about 4 ms (38% of the Python, on shaders that mostly make no variant), the attribute pattern ran on every shader though only vertex shaders have attributes, and patterns beginning `\b` or an alternation did the same in `reflect`, `fs_uint` and `check_msl`. `dmsh_side.py` `_close` looped in Python over each character of a function body, and `uses_image_atomics` over each SPIR-V instruction.
- **Fix:** the same questions, answered from the text: `str.find` and a look at the character before it (`_once`, `has_word`), one pass over a shader's stores instead of one for each output (`fs_uint`), the lines that hold attributes (`attributes`), bracket to bracket (`_close`), and a test for a word every match must hold before the pattern runs (`check_msl`, `uses_image_atomics`). The outputs are byte-identical.
- **Measurement:** cold builds on an M4 Pro, old and new taking turns, never on a quiet Mac. Pokopia's 8,157 `shader_seen.tsv` shaders, Mac and iOS (`J=14`, load 9 to 19): wall 1,426 to 607 s, the builder's Python 1,121 to 463 s of CPU. 1,001 of them, Mac only: `J=14` at load 5 to 8, wall 141 to 68 s, Python 116 to 52 s; `J=14` at load 26 to 39, wall 194 to 94 s; `J=10` at load 31 to 64, wall 177 and 173 s to 92 and 93 s, Python 150 to 160 s to about 49 s. The child processes' CPU stayed about the same (4,842 to 4,789 s on the 8,157; 2 to 13% more on the 1,001, with more compiles running at once). At those rates the whole Mac map at the NSP script's `J=14` would take about 2.5 hours instead of about 5 (not run). Identical: all 31,836 Mac and 23,678 iOS files of those 8,157, and `regress.py chain` on all of Breath of the Wild's 19,592 shaders (0 changed); old against new, step by step, 0 differences on 27,325 sources of seven games, 8,197 of their fetch variants among them.
- **Open:** a pool of worker processes for the finish step gained only 6 to 8% more on top of this (1,001 shaders, `J=10` and `J=14`, also with half the compiles modelled), for counters returned from its workers and locks across them, so it was not built; measure again on a machine with many more cores. `posix_spawn` (`close_fds=False`) takes `Popen` from 13 to 3 s, but without `pipe2` on macOS another thread's child can inherit a pipe and hold up its reader, so it would need a lock around every launch. The reflections a full build keeps (about 2.5 GB for Pokopia) raise the cost of each fork; a micro-benchmark gives 0.7 ms at 176 MB and 1.8 ms at 2 GB, and no full map has been timed.
- **Open:** a pool of worker processes for the finish step gained only 6 to 8% more on top of this here (1,001 shaders, `J=10` and `J=14`, also with half the compiles modelled) and was not built then; on Macs with more cores it gained much more, and the build now has one ([A shader build's Python finishes one shader at a time](#a-shader-builds-python-finishes-one-shader-at-a-time)). `posix_spawn` (`close_fds=False`) takes `Popen` from 13 to 3 s, but without `pipe2` on macOS another thread's child can inherit a pipe and hold up its reader, so it would need a lock around every launch. The reflections a full build keeps (about 2.5 GB for Pokopia) raise the cost of each fork (of each child the build launches; its worker processes are forked once, before the first result); a micro-benchmark gives 0.7 ms at 176 MB and 1.8 ms at 2 GB, and no full map has been timed.
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md#found-on-this-game) (resolved).
- **Check:** `test_shader_rewrites.py`, which also holds each replacement to the pattern or loop it replaced on random text.
### A shader build's Python finishes one shader at a time
- **Symptom:** a cold shader step leaves about half the cores idle whatever `J` is, and `dmsh_build.py`'s own process stays at one full core from start to end. Ocarina of Time's whole Mac map, 42,848 shaders: 3,506 s on an M3 Max with 16 cores (`J=16`, the build at 104% CPU, 4 to 5 cores busy in all), 3,002 s on an M5 Max with 18 cores.
- **Cause:** two. Finishing a shader (the MSL rewrites, its reflection, its outputs and the cache) is Python, about 40 ms a shader on Ocarina of Time, and the threads that did it share one GIL, so one core finished every shader while the Metal compiles the threads waited on left the others idle ([Rewrites that try every character of a large source](#rewrites-that-try-every-character-of-a-large-source) lowered that cost; free-threaded Python 3.14t was slower, not faster). And the shaders went in batches of `4 × J`: the next batch started when the slowest shader of this one was done, with every other thread idle.
- **Fix:** `dmsh_build.py` finishes the shaders in `DMSH_PROCS` worker processes (default `J`; 0 finishes them in threads, as before). The workers are forks of the build, made once, after the cache check and before its first thread, so they have every table and fingerprint it read; spawned workers would run the script again, and its start clears the outputs. Each opens its own connection to `cas.db` (`shader_cache.Store.forked`: SQLite's does not cross a fork). The precompiled Metal headers are made before the fork, or each worker would make its own. The build still translates the batches itself and hands a worker each shader's job; the worker's result and counts come back and are added in batch order, so the summary, the progress file and every output are those of the threads. The next batch is handed out before this one is done (two at most), so no worker waits for a batch's slowest shader; paired vertex shaders still wait for every other shader (`vs_pad` reads their pixel shaders' MSL). A worker that dies stops the build with one `[RED]` line. The outputs are byte-identical; the change is to the chain's code, so it changes the chain version once.
- **Measurement:** cold builds, empty cache, each against the main it was written on.
- Ocarina of Time's whole Mac map on the M3 Max (`J=16`): 3,506 to 1,826 s; with every shader restored from the cache 888 to 191 s. Every 8th key (9,133 shaders): 544 to 292 s, 6.4 to 13.4 cores busy; 417 s in threads with the batch overlap alone; 403, 400 and 388 s with 12, 16 and 20 workers.
- An M6 with 12 cores and 16 GB (`J=12`, another game running beside it). Red Dead Redemption's 3,628 shaders: Mac 54 to 35 s, Mac and iOS 84 s to 53 and 63 s; with every shader restored from the cache 11 to 13 s (the headers are made though nothing compiles). 1,920 of Metroid Prime 4: Beyond's shaders, whose compiles are much longer: 105 to 72 s, and 89 s with `DMSH_PROCS=6`.
- Memory, the summed resident size of the build and everything it runs, sampled every 0.5 s on the M6 (it counts the pages the forks share once for each): Red Dead Redemption 0.45 to 0.8 GB, the Metroid Prime 4 shaders 1.1 to 3.4 GB, and 2.0 GB with `DMSH_PROCS=6`. A worker itself held about 35 MB; the rest is `J` compilers running at once, which the threads never reached. With a header made in each worker, as first written, Red Dead Redemption's build peaked at 1.4 GB.
- Identical apart from the chain version and `_b_cas.txt`: all 173,316 files of Ocarina of Time's map, and Red Dead Redemption's Mac and iOS libraries (15,542 and 11,912 files).
- Another design, measured and not taken ([PR #2035](https://github.com/seedds/nxnative/pull/2035)): the build as `J / 3` copies of itself, each with a share of the shaders. Ocarina of Time's map on the M5 Max 3,002 to 1,298 s, and 1.41 times faster on an M3 Pro with 11 cores for 1.3 GB more; on the M6 it gained less than the forked workers (Red Dead Redemption: Mac 75 to 58 s, Mac and iOS 104 to 95 s, against its own older main) and compiled about 9% of the Metal sources twice.
- **Open:** not measured on a Mac with 8 GB, where `DMSH_PROCS` below `J` trades the gain for memory, nor a whole large map with iOS libraries. Two workers can compile the same Metal source at once (about 10 of Red Dead Redemption's 2,159 compiles), which costs time only.
- **Found on:** [The Legend of Zelda: Ocarina of Time](../../dm/games/0400486024DEC000/README.md#found-on-this-game).
- **Check:** `test_shader_cache.py` (`test_forked_workers_share_it`), `test_shader_toolchain_cache.py` (the batch loop with a substituted translator).
### A library that depends on its source's file name
- **Symptom:** two builds of the same shaders give different `_bl` or `_bf` libraries for some keys, of the same size, 46 bytes apart, while their MSL is the same. A byte comparison of two library folders reports them, and `regress.py` can report them as changed variants.