From af8832950348942548cfa084e4c60c1e5277c63a Mon Sep 17 00:00:00 2001 From: seedds Date: Tue, 3 Nov 2026 21:59:46 +0400 Subject: [PATCH] The offline archive builder compiles optional batches and merges a complete archive A 32,864-base Odyssey archive exhausted paging space inside Apple GPU compilation on an 8 GB M2 even after the Python memory fix. --batch-size limits each sequential compiler invocation, then metal-pack combines every successful group into the existing archive format. Keep the default and full-input archive key compatible. Cache each group independently and keep compiler or merge failures fatal. Add resume/failure tests and a synthetic Metal 4 merge check; document the complete archive validation and physical-footprint measurements. --- dm/games/0100000000010000/README.md | 2 + dm/gfx/tests/t_pso_bundle.m | 18 ++++++- dm/gfx/tools/pso_offline.py | 79 ++++++++++++++++++++++++----- dm/tools/tests/test_pso_offline.py | 76 +++++++++++++++++++++++++++ docs/agents/symptoms.md | 1 + docs/development.md | 2 + docs/reference/shaders.md | 8 +++ 7 files changed, 173 insertions(+), 13 deletions(-) diff --git a/dm/games/0100000000010000/README.md b/dm/games/0100000000010000/README.md index 3b5c14496b..8c17766db1 100644 --- a/dm/games/0100000000010000/README.md +++ b/dm/games/0100000000010000/README.md @@ -45,6 +45,8 @@ No `patches.py`. `op_mode` stays docked: Odyssey only takes its motion moves in ## Files and shaders +- **Offline archive with optional batching (1.4.1, M2 8 GB, macOS 26.6.1, Metal 32023.922).** On `b64a5ff` with the Python memory fix `db8acc5` and chain `b2197aa0df0c`, all 27,984 shader libraries compiled but the 32,864-base archive failed: the kernel reported no paging space and killed `air-nt` at 33,856 MB. With `--batch-size 1000`, all 33 groups compiled and merged into a 1,018,501,792-byte archive; direct `MTL4Archive` lookups found all 32,864 bases without a compiler fallback. The compiler's largest recorded lifetime physical footprint was 2.065 GiB (`proc_pid_rusage`, sampled once a second; short-lived processes can be missed). The pilot took 20.5 s; the complete batched pass, reusing that first group, took 507.2 s; full archive lookups took 18.2 s. The standard Mac app packer reused the archive and the bundle passed resource and signature checks. The resource-kill number and sampled footprint are different measurements, not a memory cap. Mechanism and open limits: [Bounded groups for the offline pipeline compiler](../../../docs/reference/shaders.md#bounded-groups-for-the-offline-pipeline-compiler-experimental). + - **Resolved in the shader builder (#276): BAHS pipeline interfaces.** The local 1.4.1 libraries have 290 pairs with missing vertex outputs, involving 29 vertex shaders. All are among the split's 12,124 BAHS pairs; the profile's 20,740 other pairs have no missing outputs. The shared fix makes padding read both tables; see [Pixel shader inputs the vertex shader does not write](../../../docs/reference/shaders.md#pixel-shader-inputs-the-vertex-shader-does-not-write). The report's `Max Unstruct ID 758 ... exceeds supported limit` lines did not fail the build: see the next item. Targeted validation: the affected vertex sources compile for Mac and iOS, and all 290 pairs build into `g13s` and `g16s` Metal archives with both depth entry points (Metal 32023.921). Full Mac rebuild: 27,984 of 27,984 shaders successful, no binding or pulling-library failures, no regressions, and no interface mismatches across all 32,864 pairs. The Mac host also rebuilt with the regenerated uniform tables. No new gameplay or iPhone run. - **Resolved in the shader builder (#276): the 25-minute pipeline.** `Max Unstruct ID 758` is a note from Apple's GPU compiler, which then lowers the function a slower way; left to finish, `metal-tt` exits 0 with the pipeline in the archive. The report's exit 1 came from the BAHS link errors above. The function is the float body of `alRenderMaterialUber` (fragment `007d7e411ef14ebd`, BNSH variation 0, paired with vertex `3c3435a62e05975b`): alone on `applegpu_g13s` it took 24.6 minutes and 17.3 MB of code, which is also what held the reporter's startup prebuild at 7,008 of 32,864. With the front end at `-O1` ([Front end at -O1](../../../docs/reference/shaders.md#front-end-at--o1-apples-control-flow-lowering)) it takes 31 s and 1.3 MB; the note remains, at 642. Full Mac app pack with that chain (Metal 32023.921): 27,984 of 27,984 shaders in 32:50, the `g18g` archive in 10:50 with no note, and the reporter's `g13s` archive of 32,864 bases in 15.6 minutes (exit 0, 912 MB). From `save_new1`, frames 4,200 to 6,600 (every 300) against an `-O2` build of the same commit: six identical or within one pixel, frame 5,700 differs by the same 4,191 pixels between two `-O2` runs too, and frames 4,800 and 6,300 by 1,140 and 2,059 grass pixels of at most 3 of 255. GPU time per frame over the same frames (one in 150, three runs each, alternating order): medians 5.05, 4.79 and 4.76 ms at `-O1` (the 5.05 ms run was the first of the series), 4.76, 4.75 and 4.83 ms at `-O2`. No iPhone run. - **Resolved (#294): the prebuild that stopped at 6,000 or 7,000.** With the `-O2` libraries, the same base (pair 5641 of the prebuild's 20,740) cannot be built at run time: on an M6 with 16 GB, `MTLCompilerService` aborted four times in `llvm::report_bad_alloc_error` and Metal returned an error after 33.7 minutes. Its compile held the pipeline archive's lock, so the prebuild and every draw stopped behind it. The host now writes the archive in flush periods that no compile waits for, and the prepare step no longer waits for a compile that does not return: [A compile that does not return stalls every flush and draw](../../../docs/reference/shaders.md#a-compile-that-does-not-return-stalls-every-flush-and-draw). With the `-O1` front end the base builds in 11.4 s. On an M6 with the `-O2` library the prebuild now goes on past that pair: 18,739 of the other 20,739 bases were written within 7 minutes. diff --git a/dm/gfx/tests/t_pso_bundle.m b/dm/gfx/tests/t_pso_bundle.m index 2c1891850e..9559a6d46d 100644 --- a/dm/gfx/tests/t_pso_bundle.m +++ b/dm/gfx/tests/t_pso_bundle.m @@ -24,7 +24,7 @@ static int lib(NSString *dir, NSString *name, NSString *src) { // / static void reset_counts(void) { g_pre_done = g_pre_built = g_pre_archived = g_pre_skipped = g_pre_failed = 0; } int main(void) { @autoreleasepool { - char tmp[] = "/tmp/t_pso_bundle.XXXXXX"; if (!mkdtemp(tmp)) abort(); + char tmp[PATH_MAX]; snprintf(tmp, sizeof tmp, "%s/t_pso_bundle.XXXXXX", getenv("TMPDIR") ?: "/tmp"); if (!mkdtemp(tmp)) abort(); NSString *root = @(tmp), *msl = [root stringByAppendingFormat:@"/msl/b-%s", DMSH_CHAIN], *tables = [root stringByAppendingPathComponent:@"tables"]; NSString *bundle = [root stringByAppendingPathComponent:@"bundle"], *arch = [root stringByAppendingPathComponent:@"archive"]; // A magic number alone cannot establish an archive: these are the known crash inputs, checked without calling Metal. @@ -98,6 +98,22 @@ int main(void) { @autoreleasepool { shmap_load(); pso4_init(); EXPECT("bundle: opened", 1, g_arch_bundle != nil); EXPECT("bundle: first among the files without a vertex layout", 1, g_arch4p.count && g_arch4p[0] == g_arch_bundle); + // A separate output forces one base per compiler invocation, then metal-pack merges both for this GPU. + NSString *batched = [root stringByAppendingPathComponent:@"batched"]; + if (sh([NSString stringWithFormat:@"python3 %@ --platform macos --gpu %@ --msl %@ --pairs %@/shader_pairs.tsv --out %@ --work %@/batch-work --batch-size 1 > %@/pso_batched.log 2>&1", + tool, gpu, msl, tables, batched, root, root])) { + NSString *log = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"pso_batched.log"] encoding:NSUTF8StringEncoding error:nil]; + fprintf(stderr, "batched pso_offline.py failed:\n%s\n", log.UTF8String); return 1; + } + NSString *batchPath = [batched stringByAppendingFormat:@"/%@.mtl4a", gpu]; + EXPECT("batched archive: container accepted", 1, arch_file_ok(batchPath)); + id batchArchive = arch_file_ok(batchPath) ? [g_dev newArchiveWithURL:[NSURL fileURLWithPath:batchPath] error:nil] : nil; + EXPECT("batched archive: opened", 1, batchArchive != nil); + EXPECT("batched archive: first group's base", 1, [batchArchive newRenderPipelineStateWithDescriptor:pre_desc(@"v1", @"f1", 0) error:nil] != nil); + EXPECT("batched archive: second group's base", 1, [batchArchive newRenderPipelineStateWithDescriptor:pre_desc(@"v1", @"f2", 0) error:nil] != nil); + EXPECT("batched archive: absent depth entry stays absent", 0, [batchArchive newRenderPipelineStateWithDescriptor:pre_desc(@"v1", @"f1", 1) error:nil] != nil); + EXPECT("batched archive: full coverage stamp preserved", 1, [[NSString stringWithContentsOfFile:[batched stringByAppendingPathComponent:@"prebuilt.tsv"] encoding:NSUTF8StringEncoding error:nil] + isEqualToString:[NSString stringWithContentsOfFile:[bundle stringByAppendingPathComponent:@"prebuilt.tsv"] encoding:NSUTF8StringEncoding error:nil]]); // its stamp matches: only the pair with function constants is built here reset_counts(); EXPECT("covered: one pair built on the device", 1, pso_prebuild(1, 1, QOS_CLASS_USER_INITIATED)); diff --git a/dm/gfx/tools/pso_offline.py b/dm/gfx/tools/pso_offline.py index 5a74859db9..d839603cf7 100644 --- a/dm/gfx/tools/pso_offline.py +++ b/dm/gfx/tools/pso_offline.py @@ -19,7 +19,7 @@ # Each archive is made again only when its compiler inputs change (key. in the work folder): the complete pipeline configuration without library locations, # the referenced libraries' bytes, architecture, platform, minimum OS and metal-tt version. Chain/profile stamps are validated and refreshed independently. # Usage: pso_offline.py --msl folder> --out --work [--game ] [--pairs [--pairs ]] [--gpu g18p[,g17p]] -# [--depth gl|zero] [--platform ios|macos] [--os-min 27.0] [--script-only] +# [--depth gl|zero] [--platform ios|macos] [--os-min 27.0] [--script-only] [--batch-size N] # --game: the profile (DM_GAMES_DIR as for game.py) whose shader_pairs.tsv and pso_pairs.tsv are the pairs, and whose depth_mode key the depth mode, unless --pairs / --depth say; # --gpu: architectures, with or without the applegpu_ prefix (default g18p); --depth: the game's NVN depth mode (gl = near -w, NVN's default; zero = near 0, which the game sets # with nvnDeviceSetDepthMode: the host knows it only at run time, so the profile says it; a wrong one costs the device its own prebuild, as without the archive); @@ -198,6 +198,66 @@ def os_min_default(platform): return v.split('.')[0] + '.0' +def compile_archive(js, part, work, arch, platform, osmin, count): + """One compiler invocation, with its temporaries on the work volume. Never publish a failed output.""" + part.unlink(missing_ok=True) + clear_temporaries(work) + need, free = space_needed(count), shutil.disk_usage(work).free + if free < need: sys.exit(f'[RED] pso_offline: {free / 2**30:.1f} GB free on the volume of {work}, metal-tt needs about {need / 2**30:.0f} GB for {count} bases: free some space and run again') + cmd = ['xcrun', '-sdk', sdk(platform), 'metal-tt', '-arch', arch, f'-{platform}-version-min', osmin, str(js), '-o', str(part)] + log_path = work / f'metal-tt.{arch}.log' + with log_path.open('w') as log: + r = subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, TMPDIR=str(work))) + if r.returncode or not part.is_file() or not part.stat().st_size: + free = shutil.disk_usage(work).free + clear_temporaries(work); part.unlink(missing_ok=True) + full = f' ({free / 2**30:.1f} GB free on the volume of {work} when it failed: likely out of disk space)' if free < 1 << 30 else '' + sys.exit(f'[RED] pso_offline: metal-tt failed for {arch} (exit {r.returncode}){full}: {log_path.read_text()[-2000:]}') + + +def compile_batch(lib_dir, bases, work, arch, platform, osmin, toolchain): + """Cache one bounded group by its actual libraries and descriptors; also used for an isolated pilot.""" + work.mkdir(parents=True, exist_ok=True) + configuration = script(lib_dir, bases) + js = work / 'bases.mtl4-json'; write_script(js, configuration) + key = archive_key(configuration, library_digest(lib_dir, bases), arch, platform, osmin, toolchain) + del configuration + dst, kf = work / f'{arch}.mtl4a', work / f'key.{arch}' + if dst.is_file() and dst.stat().st_size and kf.is_file() and kf.read_text().strip() == key: return dst, True + kf.unlink(missing_ok=True) + part = work / f'{arch}.mtl4a.partial' + compile_archive(js, part, work, arch, platform, osmin, len(bases)) + os.replace(part, dst); kf.write_text(key + '\n') + return dst, False + + +def compile_batches(lib_dir, bases, work, part, arch, platform, osmin, toolchain, batch_size): + """Limit compiler input size, then combine every completed group into the usual single archive. + + This bounds input count, not memory: a single pipeline can still exceed Apple's compiler resources. + On M2, merged archives passed archive-only lookups of two synthetic pipelines and all 32,864 Odyssey bases. + Other workloads and compiler versions can have different resource use. + """ + pieces = []; total = (len(bases) + batch_size - 1) // batch_size + for index, start in enumerate(range(0, len(bases), batch_size), 1): + group = bases[start:start + batch_size] + print(f'pso_offline: {arch}: batch {index}/{total}: {len(group)} bases, compiling or checking cache', flush=True) + piece, reused = compile_batch(lib_dir, group, work / f'batches.{arch}' / f'{index:05d}', arch, platform, osmin, toolchain) + pieces.append(piece) + print(f'pso_offline: {arch}: batch {index}/{total}: ready ({"reused" if reused else "compiled"})', flush=True) + part.unlink(missing_ok=True) + need, free = max(2 << 30, sum(p.stat().st_size for p in pieces)), shutil.disk_usage(work).free + if free < need: sys.exit(f'[RED] pso_offline: {free / 2**30:.1f} GB free before merging; need at least {need / 2**30:.1f} GB') + print(f'pso_offline: {arch}: merging {total} batches', flush=True) + cmd = ['xcrun', '-sdk', sdk(platform), 'metal-pack', '-nthreads', '1', *map(str, pieces), '-o', str(part)] + log_path = work / f'metal-pack.{arch}.log' + with log_path.open('w') as log: + r = subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, TMPDIR=str(work))) + if r.returncode or not part.is_file() or not part.stat().st_size: + part.unlink(missing_ok=True) + sys.exit(f'[RED] pso_offline: metal-pack failed for {arch} (exit {r.returncode}): {log_path.read_text()[-2000:]}') + + def main(argv=None): ap = argparse.ArgumentParser(description='Build the pipeline archive of a game\'s shader pairs offline (metal-tt)') ap.add_argument('--msl', required=True, help='the shader libraries, b- (with their reflection _b.json)') @@ -210,7 +270,9 @@ def main(argv=None): ap.add_argument('--platform', choices=('ios', 'macos'), default='ios') ap.add_argument('--os-min', help='minimum OS of the archives (default: iOS, the SDK\'s major version; macOS, this Mac\'s)') ap.add_argument('--script-only', action='store_true', help='write the script and the stamp, run no metal-tt') + ap.add_argument('--batch-size', type=int, default=0, help='experimental: compile sequential groups of at most N bases and merge with metal-pack (0: one compiler invocation)') a = ap.parse_args(argv) + if a.batch_size < 0: ap.error('--batch-size must be zero or positive') if a.game: sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'games')); import game g = game.load(a.game) @@ -249,18 +311,11 @@ def main(argv=None): if dst.is_file() and kf.is_file() and kf.read_text().strip() == key: print(f'pso_offline: {arch}: reused ({dst.stat().st_size / 2**20:.0f} MB)'); continue kf.unlink(missing_ok=True); dst.unlink(missing_ok=True) part = work / f'{arch}.mtl4a.partial'; part.unlink(missing_ok=True) - cmd = ['xcrun', '-sdk', sdk(a.platform), 'metal-tt', '-arch', arch, f'-{a.platform}-version-min', osmin, str(js), '-o', str(part)] - clear_temporaries(work) - need, free = space_needed(len(bases)), shutil.disk_usage(work).free - if free < need: sys.exit(f'[RED] pso_offline: {free / 2**30:.1f} GB free on the volume of {work}, metal-tt needs about {need / 2**30:.0f} GB for {len(bases)} bases: free some space and run again') t1 = time.time(); print(f'pso_offline: {arch}: metal-tt, {len(bases)} bases (minutes) ...', flush=True) - with open(work / f'metal-tt.{arch}.log', 'w') as log: - r = subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, TMPDIR=str(work))) # its temporary files on the work folder's volume - if r.returncode or not part.is_file(): - free = shutil.disk_usage(work).free # metal-tt says only "applegpu-nt command failed" when the volume fills up. Read before clearing: its temporaries are what filled it - clear_temporaries(work); part.unlink(missing_ok=True) - full = f' ({free / 2**30:.1f} GB free on the volume of {work} when it failed: likely out of disk space)' if free < 1 << 30 else '' - sys.exit(f'[RED] pso_offline: metal-tt failed for {arch} (exit {r.returncode}){full}: {(work / f"metal-tt.{arch}.log").read_text()[-2000:]}') + if a.batch_size: + compile_batches(lib_dir, bases, work, part, arch, a.platform, osmin, tv, a.batch_size) + else: + compile_archive(js, part, work, arch, a.platform, osmin, len(bases)) os.replace(part, dst); kf.write_text(key + '\n') print(f'pso_offline: {arch}: {dst.stat().st_size / 2**20:.0f} MB in {time.time() - t1:.0f} s') for f in out.glob('*.mtl4a'): # architectures no longer asked for diff --git a/dm/tools/tests/test_pso_offline.py b/dm/tools/tests/test_pso_offline.py index 84fb437943..69d5de3e74 100644 --- a/dm/tools/tests/test_pso_offline.py +++ b/dm/tools/tests/test_pso_offline.py @@ -363,6 +363,82 @@ def fail(cmd, **kw): po.main(['--game', '0100000000001000', '--msl', str(self.lib), '--out', str(self.out), '--work', str(self.work)]) self.assertEqual(list(self.out.glob('*.mtl4a')), []) + def batched_runner(self, fail_compile=None, fail_merge=False): + original = self.fake_run + observed = [] + def run(cmd, **kw): + cmd = [str(c) for c in cmd] + if 'metal-pack' in cmd: + pieces = [Path(p) for p in cmd if p.endswith('.mtl4a')] + observed.append(('merge', len(pieces))) + Path(cmd[cmd.index('-o') + 1]).write_bytes(b''.join(p.read_bytes() for p in pieces)) + return subprocess.CompletedProcess(cmd, 1 if fail_merge else 0) + if 'metal-tt' in cmd and '-o' in cmd: + js = next(Path(p) for p in cmd if p.endswith('.mtl4-json')) + config = json.loads(js.read_text()) + names = [f['name'] for f in config['function_descriptors']['library_function_descriptors'] if f['library'] == 'lib:v_bp'] + observed.append(('compile', names)) + if fail_compile in names: + Path(cmd[cmd.index('-o') + 1]).write_bytes(b'partial') + return subprocess.CompletedProcess(cmd, 1) + return original(cmd, **kw) + return run, observed + + def test_batched_archive_reuses_pilot_and_normal_archive_key(self): + bases = [('v_bp', f'vertex{i}', 'f_b', 'main0') for i in range(5)] + runner, observed = self.batched_runner() + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})): + # An isolated pilot is the exact cache entry the complete build will consume. + with mock.patch.object(po.subprocess, 'run', runner), contextlib.redirect_stdout(io.StringIO()): + po.compile_batch(self.lib, bases[:2], self.work/'batches.applegpu_g18p/00001', 'applegpu_g18p', 'ios', '27.0', self.compiler) + self.main('--batch-size', '2', '--os-min', '27.0') + self.assertEqual(observed, [('compile',['vertex0','vertex1']),('compile',['vertex2','vertex3']),('compile',['vertex4']),('merge',3)]) + before = list(observed) + self.main('--os-min', '27.0') + self.assertEqual(observed, before, 'the normal packer must reuse the complete merged archive') + self.assertIn('bases\t5\n', (self.out/'archive.tsv').read_text()) + + def test_batch_failure_preserves_completed_work_and_publishes_nothing(self): + bases = [('v_bp', f'vertex{i}', 'f_b', 'main0') for i in range(5)] + runner, observed = self.batched_runner(fail_compile='vertex2') + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})), self.assertRaises(SystemExit): + self.main('--batch-size','2','--os-min','27.0') + self.assertEqual(observed, [('compile',['vertex0','vertex1']),('compile',['vertex2','vertex3'])]) + self.assertFalse((self.out/'prebuilt.tsv').exists()) + self.assertFalse((self.work/'key.applegpu_g18p').exists()) + self.assertFalse(list(self.out.glob('*.mtl4a'))) + self.assertFalse(list(self.work.rglob('*.partial'))) + first = self.work/'batches.applegpu_g18p/00001/applegpu_g18p.mtl4a' + self.assertTrue(first.is_file()); identity = first.stat().st_mtime_ns + runner, observed = self.batched_runner() + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})): + self.main('--batch-size','2','--os-min','27.0') + self.assertEqual(first.stat().st_mtime_ns, identity) + self.assertEqual(observed, [('compile',['vertex2','vertex3']),('compile',['vertex4']),('merge',3)]) + + def test_merge_failure_never_publishes_partial_archive(self): + bases = [('v_bp', f'vertex{i}', 'f_b', 'main0') for i in range(3)] + runner, _ = self.batched_runner(fail_merge=True) + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})), self.assertRaises(SystemExit): + self.main('--batch-size','2','--os-min','27.0') + self.assertFalse(list(self.out.glob('*.mtl4a'))) + self.assertFalse((self.out/'prebuilt.tsv').exists()) + self.assertFalse((self.work/'key.applegpu_g18p').exists()) + self.assertFalse(list(self.work.rglob('*.partial'))) + runner, observed = self.batched_runner() + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})): + self.main('--batch-size','2','--os-min','27.0') + self.assertEqual(observed, [('merge',2)]) + + def test_only_changed_batch_is_recompiled(self): + bases = [('v_bp', f'vertex{i}', 'f_b', 'main0') for i in range(5)] + runner, observed = self.batched_runner() + with mock.patch.object(self, 'fake_run', runner), mock.patch.object(po, 'plan', return_value=(bases, [], {})): + self.main('--batch-size','2','--os-min','27.0') + observed.clear(); bases[0] = ('v_bp','changed','f_b','main0') + self.main('--batch-size','2','--os-min','27.0') + self.assertEqual(observed, [('compile',['changed','vertex1']),('merge',3)]) + def test_low_disk_space_stops_before_metal_tt(self): # Cruis'n Blast: a full volume made metal-tt fail with only "applegpu-nt command failed" self.work.mkdir(parents=True); (self.work / 'translate-0001').write_bytes(b'x'); (self.work / 'a.airp').write_bytes(b'x') with mock.patch.object(po.shutil, 'disk_usage', return_value=shutil._ntuple_diskusage(1 << 40, 1 << 40, 300 << 20)), self.assertRaises(SystemExit) as e: self.main() diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index aa4e47d7b2..9cbbed0ac9 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -757,6 +757,7 @@ One line per symptom in the [subsystem references](../reference/): what you see - the host logs `pipeline archive bundled with the app: made for ... this run needs ...`, naming different depths, and pipeline bases compile during play despite a successful archive build. There need not be a `[RED]` line. → [Offline pipeline archive and profile depth disagree](../reference/shaders.md#offline-pipeline-archive-and-profile-depth-disagree) - `pipeline archive bundled with the app: this system cannot open …/applegpu_.mtl4a (deployment target for architecture … found in archive … is not compatible with current OS …): the bases are built on the device`. On macOS 26.6 with Xcode 27.1, `t_pso_bundle` failed 10 checks, from `bundle: opened` on, and a Mac app packed there compiled every base on its first start, as without the archive. → [Offline pipeline archive made for another major version](../reference/shaders.md#offline-pipeline-archive-made-for-another-major-version) - `pso_offline.py` holds about 1.8 GB while `metal-tt` builds an archive of 140,036 bases, and the system's memory view shows the build far larger than that (180.5 GB) before `metal-tt` fails or is stopped. → [Python memory during offline pipeline archive preparation](../reference/shaders.md#python-memory-during-offline-pipeline-archive-preparation) +- the offline archive stops with only `applegpu-nt command failed`; the macOS kernel log reports `no paging space action` and kills `air-nt` as the largest compressed process. → [Bounded groups for the offline pipeline compiler (experimental)](../reference/shaders.md#bounded-groups-for-the-offline-pipeline-compiler-experimental) - `[RED] pso_offline: metal-tt failed for applegpu_ (exit 1)` with only `applegpu-nt command failed` in `metal-tt..log`. → [Offline pipeline archive on a full disk](../reference/shaders.md#offline-pipeline-archive-on-a-full-disk) - `[RED] pipeline prewarm: seed list does not exist: …/pso_manifest.tsv` at every start, no `pipeline prewarm list …/pso_user.tsv` line, and the same compile stalls every session in places already visited, while `pso_user.tsv` keeps growing; the pipeline archive gains files every start and is never compacted (Donkey Kong Bananza: 88 files, 7 s to open them). → [The device's prewarm list unread without a seed list](../reference/shaders.md#the-devices-prewarm-list-unread-without-a-seed-list) - the first frame that draws with new programs loads their shader libraries on the submit thread (`[longframe] ... shader libraries N, X ms`): tens of milliseconds with the files cached, seconds when the drive is slow. → [Shader libraries loaded when the program is made](../reference/shaders.md#shader-libraries-loaded-when-the-program-is-made) diff --git a/docs/development.md b/docs/development.md index e65f627e8a..790e24affe 100644 --- a/docs/development.md +++ b/docs/development.md @@ -791,6 +791,8 @@ Breath of the Wild's cold starts with and without the prebuild and `pso_pairs.ts ### The pipeline archive made offline +For experimental bounded compiler inputs, run `dm/gfx/tools/pso_offline.py` directly with `--batch-size N` and the same game, library, output, work, GPU and platform options. It caches sequential groups under `batches.//` and combines them with `metal-pack` into the normal single archive. The NSP packer can then reuse that archive's compatible full-input key. This is not a hard memory limit; see [Bounded groups for the offline pipeline compiler](reference/shaders.md#bounded-groups-for-the-offline-pipeline-compiler-experimental) for validation scope and open limits. + On iOS the standard is the pipeline archive made on the Mac and shipped in the app. Otherwise the device builds the bases on first start behind the "Preparing pipelines" screen; [Breath of the Wild's note](../dm/games/01007EF00011E000/README.md#pipelines-on-a-cold-start) records the build times, sizes and startup measurements. `build_ipa.sh` makes them on the Mac and puts them into the app (`dm/gfx/tools/pso_offline.py`). Only the Metal 4 path reads them, so by default it does this for a game whose profile sets `pso_mtl4 on` (the path is on for it on iOS), and for no other: 1. It writes a Metal 4 pipelines script (`metal4-pipelines-script(5)`) with the base of every pair in `shader_pairs.tsv` and `pso_pairs.tsv`, by the prebuild's rules (`pre_desc` in `nvn_mtl.m`): the pulling vertex library `_bp` (a vertex shader without stage inputs: its own `_b`), the vertex entry for the depth mode, the pixel shader's entry, no vertex descriptor, one sample, every colour attachment unspecialized. Pairs the prebuild leaves to the draws are left out the same way. A pair whose functions declare function constants is left to the device (`rest_pairs.tsv`): `metal-tt` makes no specialized function from a library ("cannot find private metadata"), and the host specializes such functions with an empty set. If every eligible pair needs this specialization, the tool writes the remainder list without running `metal-tt` or shipping an archive, and the device builds them all. 2. `metal-tt` compiles the script into one archive per GPU architecture: `xcrun -sdk iphoneos metal-tt -arch applegpu_g18p -ios-version-min 27.0 bases.mtl4-json -o applegpu_g18p.mtl4a`. The script needs the `.mtl4-json` extension, from which `metal-tt` takes the format: as `.mtlp-json` (Metal 3's format) it rejected even the Metal 4 serializer's own capture ("expecting [ instead got {"), which it compiles under the right extension. The archive refers to the libraries by content, not by path, so the app's own copies (`msl/b-`) find their bases. diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index 83641ab51b..a041f3fb5d 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -1321,6 +1321,14 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b - **Found on:** [Mario Party Superstars](../../dm/games/01006FE013472000/README.md) ([GitHub issue #1022](https://github.com/seedds/nxnative/issues/1022), [PR #1024](https://github.com/seedds/nxnative/pull/1024)). Open: why `metal-tt` failed after 76 minutes there, and how its memory grows with the number of bases. - **Check:** `dm/tools/tests/test_pso_offline.py` (`test_large_script_memory_and_compatible_archive_key`). +### Bounded groups for the offline pipeline compiler (experimental) + +- **Symptom:** the offline archive stops with only `applegpu-nt command failed`; the macOS kernel log reports `no paging space action` and kills `air-nt` as the largest compressed process. +- **Cause:** Apple's GPU compiler can exhaust memory while compiling the complete pipeline list. Lowering the Python builder's memory does not bound the compiler's. RSS excludes compressed and swapped allocations: use kernel resource-kill diagnostics and physical-footprint measurements to distinguish this failure from a compiler rejection or a full disk. +- **Fix (experimental):** `pso_offline.py --batch-size N` compiles sequential groups of at most N bases, each script referencing only its libraries, then merges all results with `metal-pack -nthreads 1`. The normal single-file output, full-input archive key and runtime stamp stay compatible. Successful groups are cached by their own descriptors, library bytes, GPU, OS and compiler. A failed group or merge publishes neither a new complete archive key nor coverage stamp. The default remains one compiler invocation. This bounds input count, not compiler memory; an individual pipeline or the final merge may still exhaust resources. +- **Found on:** [Super Mario Odyssey](../../dm/games/0100000000010000/README.md#files-and-shaders), which records the resource-kill evidence, before/after measurements and complete archive validation. [Issue #1022](https://github.com/seedds/nxnative/issues/1022) requests archive partitioning for another game's resource-heavy build; that workload remains unverified. +- **Check:** `dm/tools/tests/test_pso_offline.py` covers pilot reuse, compatible full-archive reuse, partial final batches, changed-group invalidation, compile failure and merge failure. `t_pso_bundle` compiles one base per group, opens the merged result, retrieves a base from each group, rejects an absent depth entry and compares the complete coverage stamp with the ordinary build. + ### Offline pipeline archive on a full disk - **Symptom:** `[RED] pso_offline: metal-tt failed for applegpu_ (exit 1)` with only `applegpu-nt command failed` in `metal-tt..log`.