Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions dm/games/0100000000010000/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 17 additions & 1 deletion dm/gfx/tests/t_pso_bundle.m
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static int lib(NSString *dir, NSString *name, NSString *src) { // <dir>/<name>
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.
Expand Down Expand Up @@ -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<MTL4Archive> 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));
Expand Down
79 changes: 67 additions & 12 deletions dm/gfx/tools/pso_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
# Each archive is made again only when its compiler inputs change (key.<arch> 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 <b-<chain> folder> --out <folder> --work <folder> [--game <id>] [--pairs <shader_pairs.tsv> [--pairs <pso_pairs.tsv>]] [--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);
Expand Down Expand Up @@ -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-<chain version> (with their reflection <key>_b.json)')
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading