mirror of
https://github.com/seedds/nxnative.git
synced 2026-11-23 11:39:42 -10:00
Shader compiles read their source from standard input: a library with function constants no longer depends on its file's name, so a build's bytes no longer depend on the order of its compiles (#1036)
Clang names a source's static initializer after its file (_GLOBAL__sub_I_<key>_bl.metal), and any function constant brings one, so the same MSL under two base names gave two libraries, 46 bytes apart. The MSL-keyed Metal cache takes the same text for the same bytes, so shaders sharing a source took the library of whichever compiled first, or their own when they compiled at once: 3,936 of Breath of the Wild's 10,560 pixel shaders share their _bl source and 1,710 their _bf source. A byte comparison of two library folders reported them, and regress.py's variant hash can. dmsh_pch.compile, which every shader library compile goes through, now passes the source with -x metal -. Metal's messages say <stdin>, and a failed compile also prints the source's path. The compile records and the chain version did not change, and neither did _b or _ba libraries. Libraries already in a Metal cache keep their bytes, so a cold build differs from them once, in _bl and _bf. _check in dmsh_mtlcache.py samples only _b and the offline pipeline archive leaves function constants to the device, so neither saw the difference. regress.py's chain key now covers dmsh_pch.py. Measured: cold builds at J=4 and J=14 of 471 Breath of the Wild shaders chosen from shared sources: 15 of 2,595 Mac files and 13 of 2,123 iOS files differed, all _bl; with this change none did. Pokopia's 1,001 at J=6 and J=14: none of 4,581 Mac and 3,579 iOS files. Checked: test_shader_pch, test_docs, test_shader_toolchain_cache, test_nsp_chain, test_pr_areas, test_regress. regress.py check not run: the host and the chain version did not change, and the whole-tree comparisons above test this change directly.
This commit is contained in:
1 parent
a27d684b1e
commit
f2a50f3522
8 files changed
+63
-10
No files matched your search
@@ -207,6 +207,7 @@ Before publishing, the fixes were integrated with main's pipeline archive and GP
|
||||
|
||||
## Found on this game
|
||||
|
||||
- [A library that depends on its source's file name](../../../docs/reference/shaders.md#a-library-that-depends-on-its-sources-file-name): 3,936 of its 10,560 pixel shaders share their `_bl` source.
|
||||
- **Resolved in the host: the taller picture was drawn smaller than the 16:9 one on the phone** (`DM_SCREEN_ASPECT=1.43`, Fit): [The picture laid out in the shape the game presents](../../../docs/reference/rendering.md#the-picture-laid-out-in-the-shape-the-game-presents).
|
||||
- **Resolved in the host: the encode thread stopped at a depth plane copy** (PR #930, on the Mac with `DM_NVN_ENC_THREAD=1`; not run here): [Depth plane copies on the encode thread](../../../docs/reference/rendering.md#depth-plane-copies-on-the-encode-thread).
|
||||
- [Same-pass feedback read from the tile](../../../docs/reference/rendering.md#same-pass-feedback-read-from-the-tile) (2026-11-03): the decals' G-buffer reads, about 320 draws a frame outdoors.
|
||||
|
||||
@@ -48,6 +48,7 @@ The first boot shows the language list: `A`, `LUp`, `A` picks English. The chara
|
||||
- [Ampere instructions new in Pokémon Pokopia](../../../docs/reference/shaders.md#ampere-instructions-new-in-pokémon-pokopia).
|
||||
- [A shader build that keeps its packages in memory runs one worker at a time](../../../docs/reference/shaders.md#a-shader-build-that-keeps-its-packages-in-memory-runs-one-worker-at-a-time): the full build at one or two shaders a second (resolved).
|
||||
- [Each Metal compile instantiates Metal's texture classes again](../../../docs/reference/shaders.md#each-metal-compile-instantiates-metals-texture-classes-again): the full build's remaining hours.
|
||||
- [A library that depends on its source's file name](../../../docs/reference/shaders.md#a-library-that-depends-on-its-sources-file-name): two `_bl` files differed between cold builds of the same code.
|
||||
- [Integer buffer textures read through float slots](../../../docs/reference/rendering.md#integer-buffer-textures-read-through-float-slots).
|
||||
- [The Joy-Con mouse pointer](../../../docs/reference/services.md#the-joy-con-mouse-pointer) and [GameShare guest displays](../../../docs/reference/services.md#gameshare-guest-displays): boot aborts.
|
||||
- [Block-compressed storage the CPU wrote before first use](../../../docs/reference/nvn-objects.md#block-compressed-storage-the-cpu-wrote-before-first-use): its `IMAGE` BC1 / BC7 icons showed other items' pictures once their storage was reused (resolved).
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
# Compiled-shader cache keyed by the Metal source (dmsh_build.py): a library is compiled once per (MSL text, compile convention, compiler), so a chain change
|
||||
# that leaves a shader's MSL as it was (a translator fix, a new rule for other shaders) costs that shader no Metal compile. The Metal compiler is deterministic:
|
||||
# the same MSL with the same flags gives a byte-identical metallib (checked for macOS and iOS), which is what makes reuse safe.
|
||||
# the same MSL with the same flags gives a byte-identical metallib (checked for macOS and iOS), which is what makes reuse safe. Its input is the text alone: dmsh_pch.compile passes the source on
|
||||
# standard input, as a file's name reaches the library of a source with function constants.
|
||||
# Layout: <cache>/<target>/<2 hex>/<digest>.metallib, digest = sha256 over FORMAT, the target's compile convention (the record written into json chain_metal),
|
||||
# the compiler's identity (metal / metallib --version without the install path, the SDK version and build) and the MSL bytes.
|
||||
# Filling from earlier builds: every imported library must record the current compiler identity and flags in its reflection. Legacy libraries without that identity are not imported.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# The module cache holds those templates, not their instantiations; this header holds the instantiations, so a compile reads them instead of making them.
|
||||
# The translated source stays as it was: the header only adds the two includes the sources start with and completes classes, and declares no name. A class left out of CLASSES costs only its
|
||||
# time. The output is byte-identical (checked on a shader of every kind in make(), so a compiler that behaves otherwise builds without the header), so -include-pch is not in the compile records
|
||||
# (dmsh_build.py MAC_RECORD, ios_metal.RECORD), and like dmsh_mtlcache.py this file is not part of the chain version: it never changes an output, it only makes one faster.
|
||||
# (dmsh_build.py MAC_RECORD, ios_metal.RECORD), and like dmsh_mtlcache.py this file is not part of the chain version: it never changes the code in an output, it only makes one faster and keeps the source's name out of it (_run).
|
||||
# One header per compile convention, made at the first compile of a process (about 2 s) and removed when it ends. Environment: DMSH_PCH=0 compiles without it.
|
||||
import atexit, os, shutil, subprocess, sys, tempfile, threading
|
||||
|
||||
@@ -55,12 +55,19 @@ def header(metal): # the path of the convention's header, None when it is not
|
||||
return _headers[tuple(metal)]
|
||||
|
||||
|
||||
def _run(metal, msl, air, **kw):
|
||||
# The source on standard input, so no file name reaches the compiler: clang names a source's static initializer after its file (_GLOBAL__sub_I_<name>, which any function constant brings),
|
||||
# so the same text under two names gave two libraries, and shaders sharing a source (3,936 of Breath of the Wild's 10,560 pixel shaders, in their _bl) took the bytes of whichever compiled first
|
||||
with open(msl, 'rb') as f: return subprocess.run([*metal, '-x', 'metal', '-', '-o', air], stdin=f, **kw)
|
||||
|
||||
|
||||
def compile(metal, msl, air):
|
||||
"""metal (the command up to its source, with -c) on msl → air. A compile that fails with the header runs again without it, so what a failure reports and raises (CalledProcessError) is the plain compile's"""
|
||||
pch = header(metal)
|
||||
if pch:
|
||||
r = subprocess.run([*metal, '-include-pch', pch, msl, '-o', air], capture_output=True)
|
||||
r = _run([*metal, '-include-pch', pch], msl, air, capture_output=True)
|
||||
if not r.returncode:
|
||||
sys.stderr.buffer.write(r.stderr); sys.stderr.flush()
|
||||
return
|
||||
subprocess.run([*metal, msl, '-o', air], check=True)
|
||||
try: _run(metal, msl, air, check=True)
|
||||
except subprocess.CalledProcessError: print(f'{msl}: does not compile (the messages above say <stdin>)', file=sys.stderr, flush=True); raise
|
||||
@@ -1,6 +1,7 @@
|
||||
"""The shader libraries' precompiled Metal header (dm/gfx/tools/dmsh_pch.py, GitHub issue #1036): a compile uses it when it builds and gives the same bytes on a test shader, runs
|
||||
again without it when it fails, so what a failure reports is the plain compile's, and DMSH_PCH=0 turns it off. With a Metal compiler (each SDK skipped without one), synthetic shaders
|
||||
compile to byte-identical output with and without it, in the flags of the real builds; a shader with an error raises as a plain compile does. No game files."""
|
||||
compile to byte-identical output with and without it, in the flags of the real builds; a shader with an error raises as a plain compile does. The source goes on standard input, so a
|
||||
library does not depend on its file's name. No game files."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
@@ -39,6 +40,11 @@ class Tmp(unittest.TestCase):
|
||||
|
||||
|
||||
class Choice(Tmp):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
for n in 'ab': (self.tmp / f'{n}.metal').write_text(n)
|
||||
cwd = os.getcwd(); os.chdir(self.tmp); self.addCleanup(os.chdir, cwd)
|
||||
|
||||
def result(self, code=0, err=b''):
|
||||
return subprocess.CompletedProcess([], code, b'', err)
|
||||
|
||||
@@ -46,12 +52,12 @@ class Choice(Tmp):
|
||||
with mock.patch.object(dmsh_pch, 'make', return_value=('/p.pch', None)) as make, mock.patch.object(subprocess, 'run', return_value=self.result()) as run:
|
||||
dmsh_pch.compile(['metal', '-c'], 'a.metal', 'a.air'); dmsh_pch.compile(['metal', '-c'], 'b.metal', 'b.air')
|
||||
make.assert_called_once() # one header per convention
|
||||
self.assertEqual([c.args[0] for c in run.call_args_list], [['metal', '-c', '-include-pch', '/p.pch', n + '.metal', '-o', n + '.air'] for n in 'ab'])
|
||||
self.assertEqual([c.args[0] for c in run.call_args_list], [['metal', '-c', '-include-pch', '/p.pch', '-x', 'metal', '-', '-o', n + '.air'] for n in 'ab'])
|
||||
|
||||
def test_a_failure_with_the_header_runs_the_plain_compile(self):
|
||||
with mock.patch.object(dmsh_pch, 'make', return_value=('/p.pch', None)), mock.patch.object(subprocess, 'run', side_effect=[self.result(1), self.result()]) as run:
|
||||
dmsh_pch.compile(['metal', '-c'], 'a.metal', 'a.air')
|
||||
self.assertEqual(run.call_args_list[1].args[0], ['metal', '-c', 'a.metal', '-o', 'a.air'])
|
||||
self.assertEqual(run.call_args_list[1].args[0], ['metal', '-c', '-x', 'metal', '-', '-o', 'a.air'])
|
||||
self.assertTrue(run.call_args_list[1].kwargs.get('check'))
|
||||
|
||||
def test_a_header_that_cannot_be_used_is_said_once_and_compiles_stay_plain(self):
|
||||
@@ -65,7 +71,15 @@ class Choice(Tmp):
|
||||
with mock.patch.dict(os.environ, {'DMSH_PCH': '0'}), mock.patch.object(dmsh_pch, 'make') as make, mock.patch.object(subprocess, 'run', return_value=self.result()) as run:
|
||||
dmsh_pch.compile(['metal', '-c'], 'a.metal', 'a.air')
|
||||
make.assert_not_called()
|
||||
self.assertEqual(run.call_args.args[0], ['metal', '-c', 'a.metal', '-o', 'a.air'])
|
||||
self.assertEqual(run.call_args.args[0], ['metal', '-c', '-x', 'metal', '-', '-o', 'a.air'])
|
||||
|
||||
def test_each_run_reads_the_source_from_its_start(self):
|
||||
read = []
|
||||
def run(cmd, stdin=None, **kw):
|
||||
read.append(stdin.read()); return self.result(len(read) == 1) # the first run fails, having read the whole source
|
||||
with mock.patch.object(dmsh_pch, 'make', return_value=('/p.pch', None)), mock.patch.object(subprocess, 'run', side_effect=run):
|
||||
dmsh_pch.compile(['metal', '-c'], 'a.metal', 'a.air')
|
||||
self.assertEqual(read, [b'a', b'a'])
|
||||
|
||||
def test_make_refuses_a_header_whose_test_shader_differs(self):
|
||||
def run(cmd, **kw):
|
||||
@@ -87,7 +101,7 @@ class RealCompiler(Tmp):
|
||||
for name, body in SHADERS.items():
|
||||
src = self.tmp / f'{name}.metal'; src.write_text('#pragma clang diagnostic ignored "-Wmissing-prototypes"\n\n#include <metal_stdlib>\n#include <simd/simd.h>\n\nusing namespace metal;\n\n' + body)
|
||||
plain, used = self.tmp / f'{name}.plain.air', self.tmp / f'{name}.air'
|
||||
subprocess.run([*metal, src, '-o', plain], check=True, capture_output=True)
|
||||
with open(src, 'rb') as f: subprocess.run([*metal, '-x', 'metal', '-', '-o', plain], stdin=f, check=True, capture_output=True) # as compile runs it: an .air records a named source's path
|
||||
with mock.patch.dict(dmsh_pch._headers, {tuple(metal): pch}), mock.patch.object(subprocess, 'run', wraps=subprocess.run) as run:
|
||||
dmsh_pch.compile(metal, str(src), str(used))
|
||||
self.assertIn('-include-pch', run.call_args_list[0].args[0]); self.assertEqual(run.call_count, 1, f'{name}: the compile with the header failed')
|
||||
@@ -101,6 +115,25 @@ class RealCompiler(Tmp):
|
||||
def test_ios_output_is_byte_identical(self):
|
||||
self.check_identical(ios_metal.METAL)
|
||||
|
||||
def check_no_name(self, metal, header):
|
||||
pch = dmsh_pch.make(metal)[0] if header else None
|
||||
if header: self.assertTrue(pch)
|
||||
out = []
|
||||
for name in ('0123456789abcdef_bl', 'fedcba9876543210_bl'): # a function constant brings a static initializer, which clang names after the file
|
||||
d = self.tmp / name; d.mkdir(exist_ok=True); src = d / f'{name}.metal'; air = d / f'{name}.{header}.air'
|
||||
src.write_text('#include <metal_stdlib>\nusing namespace metal;\nconstant bool fc [[function_constant(0)]];\nfragment float4 main0(float4 d [[color(0), function_constant(fc)]]) { return fc ? d : float4(1); }\n')
|
||||
with mock.patch.dict(dmsh_pch._headers, {tuple(metal): pch}): dmsh_pch.compile(metal, str(src), str(air))
|
||||
out.append(air.read_bytes())
|
||||
self.assertEqual(out[0], out[1])
|
||||
|
||||
@unittest.skipUnless(has_sdk('macosx'), 'no macOS Metal compiler')
|
||||
def test_a_mac_library_does_not_depend_on_the_source_name(self):
|
||||
self.check_no_name(MAC, True); self.check_no_name(MAC, False)
|
||||
|
||||
@unittest.skipUnless(has_sdk('iphoneos'), 'no iOS Metal compiler')
|
||||
def test_an_ios_library_does_not_depend_on_the_source_name(self):
|
||||
self.check_no_name(ios_metal.METAL, True); self.check_no_name(ios_metal.METAL, False)
|
||||
|
||||
@unittest.skipUnless(has_sdk('macosx'), 'no macOS Metal compiler')
|
||||
def test_a_shader_with_an_error_raises_as_a_plain_compile_does(self):
|
||||
src = self.tmp / 'bad.metal'; src.write_text('#include <metal_stdlib>\nfragment float4 main0() { return undeclared; }\n')
|
||||
|
||||
@@ -818,6 +818,7 @@ One line per symptom in the [subsystem references](../reference/): what you see
|
||||
- `<id>_build/shader/cache/cas/shader/` holds several entries for each shader, and grows by a full set with every upstream update that changes the shader chain. Tears of the Kingdom (seedds/nxnative#1033): 172,014 entries after six builds for 28,669 shaders, 11.85 GB of `.metal` and `.json` that no build read; the test Mac's copy held 934,955, of which the prune (dry run) found 906,286 unused: 70.2 GB of sources and reflection, scanned in 18 minutes on an external SSD. → [Old per-shader cache entries grew a game's build folder with each chain change](../reference/shaders.md#old-per-shader-cache-entries-grew-a-games-build-folder-with-each-chain-change)
|
||||
- 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)
|
||||
- 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)
|
||||
- startup tasks can prepare the same shader more than once, even though only one object enters the warm dictionary. A measured Tears of the Kingdom startup avoided 320 duplicate preparations; this is not a steady-frame-rate claim. → [Concurrent warm tasks prepare each shader once](../reference/shaders.md#concurrent-warm-tasks-prepare-each-shader-once)
|
||||
- `fragmentFunction main0 cannot be used to build a pipeline state` (a Metal validation assertion). → [Function constants specialized at load](../reference/shaders.md#function-constants-specialized-at-load)
|
||||
- with Metal 4 pipelines on (the Mac; on iOS `pso_mtl4 on` or `DM_PSO_MTL4=1`), Apple's performance HUD says `Compiled 2 shaders. Total compilation time is 102.70ms. Consider adopting MTL4Compiler for more fine grained compilations` during play, when a shader with function constants loads. → [Functions with function constants specialized by the pipeline, not the library](../reference/shaders.md#functions-with-function-constants-specialized-by-the-pipeline-not-the-library)
|
||||
|
||||
@@ -1521,6 +1521,15 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b
|
||||
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md#found-on-this-game).
|
||||
- **Check:** `test_shader_pch.py`.
|
||||
|
||||
### 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.
|
||||
- **Cause:** clang names a source's static initializer after its file (`_GLOBAL__sub_I_<key>_bl.metal`), and any function constant brings one, so the name and the library's stored hash change with the file's base name (its folder does not matter). Sources without function constants do not depend on it. The MSL-keyed Metal cache takes the same text for the same bytes, so shaders that share a source took the library of whichever compiled first, or their own when they compiled at once. In Breath of the Wild 3,936 of 10,560 pixel shaders share their `_bl` source and 1,710 their `_bf` source.
|
||||
- **Fix:** `dmsh_pch.compile`, which every compile of a shader library goes through, passes the source on standard input (`-x metal -`), so no file name reaches the compiler. Metal's messages then say `<stdin>`, and a failed compile also prints the source's path. Libraries from an earlier compile keep their bytes in the Metal cache: a cold build differs from them once, in `_bl` and `_bf`. The compile records and the chain version did not change, as the code the libraries hold did not. `_check` in `dmsh_mtlcache.py` samples only `_b`, and the offline pipeline archive leaves function constants to the device, so neither ever saw the difference.
|
||||
- **Measurement:** cold builds at `J=4` and `J=14` of 471 Breath of the Wild shaders chosen from shared sources: 15 of 2,595 Mac files and 13 of 2,123 iOS files differed, all `_bl`; with the source on standard input none did. Pokopia's 1,001 at `J=6` and `J=14`: none of 4,581 Mac and 3,579 iOS files.
|
||||
- **Found on:** [Pokémon Pokopia](../../dm/games/0400A3A01EE4C000/README.md#found-on-this-game) (resolved), [The Legend of Zelda: Breath of the Wild](../../dm/games/01007EF00011E000/README.md#found-on-this-game) (resolved).
|
||||
- **Check:** `test_shader_pch.py` (`test_a_mac_library_does_not_depend_on_the_source_name`, `test_each_run_reads_the_source_from_its_start`).
|
||||
|
||||
### Concurrent warm tasks prepare each shader once
|
||||
|
||||
- **Symptom:** startup tasks can prepare the same shader more than once, even though only one object enters the warm dictionary. A measured Tears of the Kingdom startup avoided 320 duplicate preparations; this is not a steady-frame-rate claim.
|
||||
|
||||
+1
-1
@@ -337,7 +337,7 @@ def toolchain_fp():
|
||||
def chain_key(tree, g, tools):
|
||||
if g.kind == 'nvn':
|
||||
v, inp = json.loads(tree.py("import sys, json; sys.path.insert(0, 'dm/gfx/tools'); import dmsh_chain as c; g = c.load_game(); print(json.dumps([c.version(), c.inputs(g)]))", g.env(tree)))
|
||||
side = digest([tree.path / 'dm/gfx/tools' / f for f in ('c1_guard.py', 'cb_extent.py', 'dmsh_mtlcache.py', 'own_compilers.py', 'tool_lock.py')] + [tree.path / 'dm/games/game.py'])
|
||||
side = digest([tree.path / 'dm/gfx/tools' / f for f in ('c1_guard.py', 'cb_extent.py', 'dmsh_mtlcache.py', 'dmsh_pch.py', 'own_compilers.py', 'tool_lock.py')] + [tree.path / 'dm/games/game.py'])
|
||||
pkg = g.build / 'shader/pkg'
|
||||
sources = digest(sorted(p for p in pkg.rglob('*') if p.is_file()), root=pkg)
|
||||
pairs = g.profile_dir(tree) / 'pso_pairs.tsv'
|
||||
|
||||
Reference in new issue
Block a user