diff --git a/dm/games/0400E88025B1A000/README.md b/dm/games/0400E88025B1A000/README.md index a989a64894..3ab9c521e8 100644 --- a/dm/games/0400E88025B1A000/README.md +++ b/dm/games/0400E88025B1A000/README.md @@ -44,6 +44,8 @@ Every 3D target is 768x432 from the first frame of the title to the tutorial: Me - [A handle pair ORed sampler word first](../../../docs/reference/shaders.md#a-handle-pair-ored-sampler-word-first): 62 pixel shaders. - [NVN2 compute's separate handles in c\[0\]](../../../docs/reference/shaders.md#nvn2-computes-separate-handles-in-c0): `1002069a331ceded`, dispatched in the prologue. - [Ampere BMSK and the read of a covered pixel](../../../docs/reference/shaders.md#ampere-bmsk-and-the-read-of-a-covered-pixel): the last 3 shaders, `58046f286de779e1`, `46040940ce0fd49b` and `826168691af2e211`, none asked for in play so far. +- [Compute pipelines compiled at first use](../../../docs/reference/shaders.md#compute-pipelines-compiled-at-first-use): 233 compute pipelines in the app's archive, none built at the title. +- [Compute pipelines outside the bundled archive built at every start](../../../docs/reference/shaders.md#compute-pipelines-outside-the-bundled-archive-built-at-every-start): the second headless start took its 8 from the device's archive. ## Open diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index eb8b266e4b..4064c1d44a 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -4857,6 +4857,7 @@ @implementation FnDev @end return dev->fn; } } +static id cps_new(id f, NSError **e); // a compute shader's pipeline: from the archive bundled with the app, else built // layer: a vertex shader's layer entry points (entry_layer / entry_layer_z, which also write the layer) instead of main0 / main0_z, for a program whose geometry shader is a slice writer (prog_fold_gs) static NvShader *shader_load(NSString *pc, int stage, int layer) { NSError *e = nil; @@ -4933,7 +4934,7 @@ @implementation FnDev @end if (stage == 1 && j[@"entry_m"]) { o->fn_m = fn4_note([lib newFunctionWithName:j[@"entry_m"]], lib, j[@"entry_m"], nil); o->mask_m = (uint8_t)[j[@"uint_mask_m"] unsignedIntValue]; if (!o->fn_m) MLOG("[RED] shader %s: no mixed integer-output entry point %s in its library", pc.UTF8String, [j[@"entry_m"] UTF8String]); } if (stage == 1 && j[@"entry_d"]) { o->fn_d = fn4_note([lib newFunctionWithName:j[@"entry_d"]], lib, j[@"entry_d"], nil); if (!o->fn_d) MLOG("[RED] shader %s: no dual-source entry point %s in its library", pc.UTF8String, [j[@"entry_d"] UTF8String]); } - if (o->fn.functionConstantsDictionary.count) { // a compute shader's pipelines are MTLDevice ones: it is specialized through its library (fn_spec otherwise) + if (o->fn.functionConstantsDictionary.count) { // a compute shader with constants has MTLDevice pipelines (cps_new): it is specialized through its library (fn_spec otherwise) NSError *fe = nil; MTLFunctionConstantValues *cv = [MTLFunctionConstantValues new]; id (*spec)(id, NSString *, MTLFunctionConstantValues *, NSError **) = stage == 5 ? fn_lib_spec : fn_spec; id f = spec(lib, entry, cv, &fe); if (f) o->fn = f; else MLOG("[RED] shader %s: specializing its function constants failed: %s", pc.UTF8String, fe.localizedDescription.UTF8String); @@ -6834,8 +6835,8 @@ static int arch_compact_allowed(void) { // pipeline found in the files. The flush used to hold a lock against every such compile instead, and one compile that did not return (Super Mario Odyssey's alRenderMaterialUber // with the front end at -O2: 33.7 minutes until Metal gave up, GitHub issue #294) held the flush, and the flush every compile and draw that came after it. Now such a compile // holds back the file of its own period and nothing else -@interface ArchEpoch : NSObject { @public id comp; id ser; dispatch_group_t busy; _Atomic int active, n, vd; int compacting; } @end -// n, vd: bases captured, those with a vertex layout +@interface ArchEpoch : NSObject { @public id comp; id ser; dispatch_group_t busy; _Atomic int active, n, vd, cs; int compacting; } @end +// n: pipelines captured; vd, cs: those of them that are bases with a vertex layout, compute pipelines @implementation ArchEpoch @end static ArchEpoch *g_ep; static os_unfair_lock g_ep_lock = OS_UNFAIR_LOCK_INIT; // the current period static int g_arch_cap; // compiles are captured (an archive folder, a serializer): immutable after pso4_init @@ -6978,6 +6979,15 @@ static void pso_bundle_open(NSMutableArray> *archp) { ep_leave(ep); return ps; } +// The same for a compute pipeline (cps_new). It counts as a base with a vertex layout does: its file is a plain one, never a p file, so its lookups skip the prebuild's files +static id arch_capture_cs(MTL4ComputePipelineDescriptor *d, NSError **e) { + if (!g_arch_cap) return [g_comp4 newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e]; + ArchEpoch *ep = ep_enter(); + id ps = [ep->comp newComputePipelineStateWithDescriptor:d compilerTaskOptions:nil error:e]; + if (ps) { atomic_fetch_add(&ep->n, 1); atomic_fetch_add(&g_arch_new, 1); atomic_fetch_add(&ep->cs, 1); } + ep_leave(ep); + return ps; +} // Metal opens a pipeline archive through NSData with "mapped if safe", and Foundation takes a file on an external drive as not safe: it reads it into memory, whole and for the whole run (docs/reference/memory.md). newArchiveWithURL has no option for this, so while the host // opens its archives the read of a .mtl4a asks for a mapping, as the internal disk gets. The game already runs from that drive; a drive pulled out ends it either way. If a system has no such method, the files are read as before typedef id (*ns_read_fn)(id, SEL, NSString *, NSUInteger, NSUInteger, NSError **); @@ -7035,16 +7045,62 @@ static void pso4_init(void) { }); } static int pso4_compiler(void) { pso4_init(); return g_comp4 != nil; } // render pipelines go through the Metal 4 compiler (fn_spec) +// Compute pipelines from the archive bundled with the app: it holds one per compute shader of the shader map and of the prewarm list's C rows (pso_offline.py), made from _b's +// function alone. A compute pipeline depends on nothing else here: the MTLDevice builds it from the function (newComputePipelineStateWithFunction, no threadgroup size or other +// option; the dispatch gives the threadgroup size), so the lookup names the function alone too, by the descriptor shader_load noted (fn4_note). One the bundle does not hold +// (no bundle, a shader outside the map, an OS update that dropped the bundle's binaries) is looked up in this device's own archive files; on a miss it is built through the +// MTLDevice as before, and compiled again through the Metal 4 compiler into the current flush period on a background queue (cps_harvest), so the next start takes it from the +// file that period writes: the MTLDevice's build is the one the system's shader cache serves, the capture compiles it whole (Star Fox's first 5 at its title: 1.2 ms in all +// through the MTLDevice, 95 ms through the capture), so the dispatch never waits for the capture. Before, such a pipeline was built again at every start, and in full at each +// one after the system's shader cache dropped it. Not looked up and not captured: a function with constants (fn_lib_spec specializes it through its library) and the embedded +// kernels, which have no note. A miss costs a lookup of a fraction of a millisecond per file. g_cps_arch, g_cps_run, g_cps_built: compute pipelines taken from the +// bundle, from this device's files, built (the prewarm's last lines); g_cps_look_ns, g_cps_build_ns: the time looking up, building +static _Atomic uint64_t g_cps_arch, g_cps_run, g_cps_built, g_cps_look_ns, g_cps_build_ns; +static void arch_note_new(void); +static dispatch_queue_t cps_harvest_q(void) { // one capture at a time, at utility QoS: a network shader's compile can take seconds, beside the game's frames + static dispatch_queue_t q; static dispatch_once_t once; + dispatch_once(&once, ^{ q = dispatch_queue_create("dm.nvn.cps-harvest", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)); }); + return q; +} +// d into the flush period, in the background; compact: a compaction's capture of a pipeline the prewarm took from an old file (as pso_build's bases) +static void cps_harvest(MTL4ComputePipelineDescriptor *d, int compact) { + if (!g_arch_cap || !d) return; + dispatch_async(cps_harvest_q(), ^{ @autoreleasepool { + NSError *ce = nil; + if (arch_capture_cs(d, &ce)) { if (compact) g_compacted++; arch_note_new(); } + else MLOG("[RED] compute pipeline %s: the Metal 4 compiler refused it (%s): not kept in the pipeline archive", d.computeFunctionDescriptor ? [(MTL4LibraryFunctionDescriptor *)d.computeFunctionDescriptor name].UTF8String : "(unnamed)", + ce ? ce.localizedDescription.UTF8String : "no error given"); + } }); +} +static id cps_new(id f, NSError **e) { + pso4_init(); + MTL4FunctionDescriptor *fd = fn4_of(f); MTL4ComputePipelineDescriptor *d = nil; id ps = nil; uint64_t t0 = bp_now(); + if ([fd isKindOfClass:MTL4LibraryFunctionDescriptor.class]) { + d = [MTL4ComputePipelineDescriptor new]; d.computeFunctionDescriptor = fd; + if (g_arch_bundle && (ps = [g_arch_bundle newComputePipelineStateWithDescriptor:d error:nil])) atomic_fetch_add(&g_cps_arch, 1); + else for (id a in g_arch4) if ((ps = [a newComputePipelineStateWithDescriptor:d error:nil])) { // arch_capture_cs writes them to plain files only + atomic_fetch_add(&g_cps_run, 1); + if (g_compact_enabled && atomic_load(&g_warm_running)) cps_harvest(d, 1); + break; + } + atomic_fetch_add(&g_cps_look_ns, bp_now() - t0); + if (ps) return ps; + } + uint64_t t1 = bp_now(); + ps = [g_dev newComputePipelineStateWithFunction:f error:e]; + if (ps) { atomic_fetch_add(&g_cps_built, 1); atomic_fetch_add(&g_cps_build_ns, bp_now() - t1); cps_harvest(d, 0); } + return ps; +} // Writes one flush period's captures as the next file of the archive, on g_arch_q once every compile in the period has returned; g_arch_flush_ok: the last one wrote its file static int g_arch_flush_ok; static void arch_compact_finish(void); static void arch_write(ArchEpoch *ep) { - int n = atomic_load(&ep->n), vd = atomic_load(&ep->vd); // exact: no compile of the period is under way + int n = atomic_load(&ep->n), vd = atomic_load(&ep->vd), cs = atomic_load(&ep->cs); // exact: no compile of the period is under way if (!n) return; g_arch_flush_ok = 0; [NSFileManager.defaultManager createDirectoryAtPath:g_arch_dir withIntermediateDirectories:YES attributes:nil error:nil]; uint64_t t0 = bp_now(); NSError *e = nil; - NSString *path = [g_arch_dir stringByAppendingPathComponent:[NSString stringWithFormat:vd ? @"%05d.mtl4a" : @"p%05d.mtl4a", g_arch_seq++]], *tmp = [path stringByAppendingString:@".tmp"]; + NSString *path = [g_arch_dir stringByAppendingPathComponent:[NSString stringWithFormat:vd || cs ? @"%05d.mtl4a" : @"p%05d.mtl4a", g_arch_seq++]], *tmp = [path stringByAppendingString:@".tmp"]; if (ep->compacting) [arch_compact_stamp() writeToFile:arch_compact_marker() atomically:YES encoding:NSUTF8StringEncoding error:nil]; BOOL ok = [ep->ser serializeAsArchiveAndFlushToURL:[NSURL fileURLWithPath:tmp] error:&e]; if (ep->compacting) unlink(arch_compact_marker().fileSystemRepresentation); @@ -7053,7 +7109,7 @@ static void arch_write(ArchEpoch *ep) { if (!ok) { MLOG("[RED] pipeline archive: writing %s failed%s%s", path.UTF8String, e ? ": " : "", e ? e.localizedDescription.UTF8String : ""); unlink(tmp.fileSystemRepresentation); } else { g_arch_flush_ok = 1; - MLOG("pipeline archive: %d new pipeline bases written to %s (%.1f MB, %.0f ms)", n, path.lastPathComponent.UTF8String, + MLOG("pipeline archive: %d new pipeline bases%s written to %s (%.1f MB, %.0f ms)", n - cs, cs ? [NSString stringWithFormat:@" and %d compute pipelines", cs].UTF8String : "", path.lastPathComponent.UTF8String, [[NSFileManager.defaultManager attributesOfItemAtPath:path error:nil] fileSize] / 1048576.0, (bp_now() - t0) / 1e6); } if (ep->compacting) arch_compact_finish(); @@ -7395,6 +7451,11 @@ void mtl_pso_line(char *o, size_t n) { o2 += snprintf(o + o2, n > o2 ? n - o2 : 0, "; draws that waited:"); for (int i = 0; i < 5; i++) if (g_pw_n[i] > pn[i]) o2 += snprintf(o + o2, n > o2 ? n - o2 : 0, " %s %llu / %.1f ms,", g_pw_why[i], (unsigned long long)(g_pw_n[i] - pn[i]), (g_pw_ns[i] - pns[i]) / 1e6); memcpy(pn, g_pw_n, sizeof pn); memcpy(pns, g_pw_ns, sizeof pns); + static uint64_t pca, pcr, pcb, pcl, pcn; uint64_t ca = g_cps_arch, cr = g_cps_run, cb = g_cps_built, cl = g_cps_look_ns, cn = g_cps_build_ns; // compute pipelines (cps_new) + if (ca > pca || cr > pcr || cb > pcb) + snprintf(o + o2, n > o2 ? n - o2 : 0, "; compute pipelines from the archive bundled with the app %llu, from this device's archive %llu, built %llu (%.1f ms looking up, %.1f ms building)", + (unsigned long long)(ca - pca), (unsigned long long)(cr - pcr), (unsigned long long)(cb - pcb), (cl - pcl) / 1e6, (cn - pcn) / 1e6); + pca = ca; pcr = cr; pcb = cb; pcl = cl; pcn = cn; } // ---- Prebuild: the base of every shader pair of the game, into the pipeline archive ---- @@ -7811,7 +7872,7 @@ static void warm_task(WarmTask *t) { g_warm_done++; return; } if (t->kind == 2) { - NvShader *cs = warm_shader(t->key, 5); NSError *e = nil; id ps = cs ? [g_dev newComputePipelineStateWithFunction:cs->fn error:&e] : nil; + NvShader *cs = warm_shader(t->key, 5); NSError *e = nil; id ps = cs ? cps_new(cs->fn, &e) : nil; if (cs && !ps) MLOG("[RED] background compute pipeline creation failed: %s", e.localizedDescription.UTF8String); if (ps) { WarmItem *item = [WarmItem new]; item->kind = 2; item->key = t->key; item->shader = cs; item->object = ps; warm_enqueue(item); g_warm_cps++; } g_warm_done++; return; @@ -7843,6 +7904,8 @@ static void warm_finish(void) { if (g_comp4) MLOG("pipeline bases so far: %llu compiled, %llu from the archive, %llu reused (%.1f ms for the bases); %llu specializations (their descriptors %s), %llu pipelines without a base (MTLDevice)", (unsigned long long)g_pb_built, (unsigned long long)g_pb_archived, (unsigned long long)g_pb_reused, g_pb_base_ns / 1e6, (unsigned long long)g_pb_spec, (const char *[]){"not asked for yet", "returned retained", "returned autoreleased"}[atomic_load(&g_spec_own) % 3], (unsigned long long)g_pb_legacy); + if (g_arch_bundle || g_arch_cap) MLOG("compute pipelines so far: %llu from the archive bundled with the app, %llu from this device's archive, %llu built (%.1f ms looking up, %.1f ms building)", + (unsigned long long)g_cps_arch, (unsigned long long)g_cps_run, (unsigned long long)g_cps_built, g_cps_look_ns / 1e6, g_cps_build_ns / 1e6); // All warm tasks have joined. WarmItems retain published shaders until the submit thread claims them. // Drop negative results too: demand loading keeps its existing retry behavior, independent of the warm dictionary. g_warm_dict = nil; g_warm_loads = nil; @@ -11819,7 +11882,7 @@ static void dispatch(const p_dispatch *dp) { id ps = hm_get_id(&g_cps, &k); if (!ps) { if (cs->cps_failed) return; // the same function fails the same way: asked again at every dispatch, Mario Kart World's refused shaders took 3,138 pipeline builds in 60 s - NSError *e = nil; uint64_t bt = bp_now(); ps = [g_dev newComputePipelineStateWithFunction:cs->fn error:&e]; + NSError *e = nil; uint64_t bt = bp_now(); ps = cps_new(cs->fn, &e); g_bp_pso_n++; g_bp_pso_ns += bp_now() - bt; if (!ps) { cs->cps_failed = 1; MLOG("[RED] failed to create compute pipeline for %s: %s (its dispatches are skipped)", cs->key, e.localizedDescription.UTF8String); return; } pso_record("C\t%s\n", cs->key); diff --git a/dm/gfx/tests/t_pso_archive.m b/dm/gfx/tests/t_pso_archive.m index e9f6484f79..5bcb2f98d4 100644 --- a/dm/gfx/tests/t_pso_archive.m +++ b/dm/gfx/tests/t_pso_archive.m @@ -4,7 +4,7 @@ // Metal 4 descriptor keeps the MTLDevice path; pso_key_norm drops what no pipeline depends on; compaction merges the files the prewarm took bases from into one despite a // mid-prewarm flush, and a compaction that did not finish is not tried again on the same system build; depth-only draws write depth; concurrent colour variants compile // one base; archive flushes preserve unrelated compiler state; a function with function constants is specialized by its pipeline's descriptor, not through its library, -// and an MTLDevice pipeline gets it specialized; the descriptor for a specialization is the caller's whether the driver returns it retained or autoreleased +// and an MTLDevice pipeline gets it specialized; the descriptor for a specialization is the caller's whether the driver returns it retained or autoreleased; a compute pipeline is captured into a plain file and taken from it later, one without a Metal 4 descriptor never looked up #include #include #include @@ -93,6 +93,76 @@ - (id)forwardingTargetForSelector:(SEL)selector { return compiler; } return [compiler newRenderPipelineStateWithDescriptor:d compilerTaskOptions:opts error:error]; } @end +// Counts the compute pipeline lookups in an archive file +@interface LookupCountArchive : NSObject { @public id archive; _Atomic int lookups; } @end +@implementation LookupCountArchive +- (id)forwardingTargetForSelector:(SEL)selector { return archive; } +- (id)newComputePipelineStateWithDescriptor:(MTL4ComputePipelineDescriptor *)d error:(NSError **)error { + atomic_fetch_add(&lookups, 1); return [archive newComputePipelineStateWithDescriptor:d error:error]; +} +@end +// Runs kernel k of compute_pipelines over 64 threads: 1 when every o[i] is i * 3 + 1 +static int run_kernel(id ps) { + if (!ps) return 0; + id b = [g_dev newBufferWithLength:64 * 4 options:MTLResourceStorageModeShared]; memset(b.contents, 0, 64 * 4); + id cb = [g_q commandBuffer]; id ce = [cb computeCommandEncoder]; + [ce setComputePipelineState:ps]; [ce setBuffer:b offset:0 atIndex:0]; [ce dispatchThreads:MTLSizeMake(64, 1, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)]; [ce endEncoding]; + [cb commit]; [cb waitUntilCompleted]; + const uint32_t *o = b.contents; for (uint32_t i = 0; i < 64; i++) if (o[i] != i * 3 + 1) return 0; + return 1; +} +// Compute pipelines (cps_new) beside the bases: one the bundle does not hold is built through the MTLDevice and compiled into the flush period in the background, written to a +// plain file (never a p one), and a later start takes it from that file without building it; compaction captures it again; a function without a Metal 4 descriptor +// (constants, the embedded kernels) is built through the MTLDevice, not captured and never looked up +static void compute_pipelines(void) { + char kdir[] = "/tmp/t_pso_compute.XXXXXX"; if (!mkdtemp(kdir)) abort(); + NSString *saved = g_arch_dir; g_arch_dir = @(kdir); g_arch4 = @[]; g_arch4p = @[]; NSError *err = nil; + arch_flush_wait(); // from an empty period + NSString *src = @"#include \nusing namespace metal;\nkernel void k(device uint *o [[buffer(0)]], uint i [[thread_position_in_grid]]) { o[i] = i * 3 + 1; }\n"; + id kl = [g_dev newLibraryWithSource:src options:nil error:&err], ul = [g_dev newLibraryWithSource:[src stringByAppendingString:@"// unregistered\n"] options:nil error:&err]; + id kf = fn4_note([kl newFunctionWithName:@"k"], kl, @"k", nil), uf = [ul newFunctionWithName:@"k"]; + uint64_t built = g_cps_built, run = g_cps_run, arch = g_cps_arch; int pending = g_arch_new; + id kp = cps_new(kf, &err); + EXPECT("compute: a pipeline", 1, kp != nil); + EXPECT("compute: built", built + 1, g_cps_built); + dispatch_sync(cps_harvest_q(), ^{}); // its capture, in the background + EXPECT("compute: captured for the archive", pending + 1, g_arch_new); + EXPECT("compute: its dispatch writes", 1, run_kernel(kp)); + arch_flush_wait(); + NSArray *names = [NSFileManager.defaultManager contentsOfDirectoryAtPath:@(kdir) error:nil]; + EXPECT("compute: one file written", 1, names.count); + EXPECT("compute: a plain file, not a p file", 1, names.count == 1 && ![names[0] hasPrefix:@"p"]); + EXPECT("compute: nothing left to write", 0, g_arch_new); + LookupCountArchive *la = [LookupCountArchive new]; + la->archive = names.count ? [g_dev newArchiveWithURL:[NSURL fileURLWithPath:[@(kdir) stringByAppendingPathComponent:names[0]]] error:&err] : nil; + g_arch4 = @[(id)la]; // as a new start with that file + built = g_cps_built; pending = g_arch_new; + id kp2 = cps_new(kf, &err); + EXPECT("compute again: from this device's archive", run + 1, g_cps_run); + EXPECT("compute again: not built", built, g_cps_built); + EXPECT("compute again: not from a bundle", arch, g_cps_arch); + EXPECT("compute again: nothing captured", pending, g_arch_new); + EXPECT("compute again: its dispatch writes", 1, run_kernel(kp2)); + // compaction during the prewarm: captured again from its function, for the file that replaces the old ones + g_compact_enabled = 1; g_compacted = 0; atomic_store(&g_warm_running, 1); + EXPECT("compute, compaction: a pipeline", 1, cps_new(kf, &err) != nil); + EXPECT("compute, compaction: from the archive", run + 2, g_cps_run); + dispatch_sync(cps_harvest_q(), ^{}); + EXPECT("compute, compaction: captured again", 1, g_compacted); + EXPECT("compute, compaction: waits for the flush", pending + 1, g_arch_new); + atomic_store(&g_warm_running, 0); g_compact_enabled = 0; g_compacted = 0; + arch_flush_wait(); + // no Metal 4 descriptor: built through the MTLDevice, no lookup, nothing captured + int looked = la->lookups; built = g_cps_built; pending = g_arch_new; + id up = cps_new(uf, &err); + EXPECT("compute without a descriptor: a pipeline", 1, up != nil); + EXPECT("compute without a descriptor: never looked up", looked, la->lookups); + EXPECT("compute without a descriptor: built", built + 1, g_cps_built); + dispatch_sync(cps_harvest_q(), ^{}); + EXPECT("compute without a descriptor: not captured", pending, g_arch_new); + EXPECT("compute without a descriptor: its dispatch writes", 1, run_kernel(up)); + [NSFileManager.defaultManager removeItemAtPath:@(kdir) error:nil]; g_arch_dir = saved; g_arch4 = @[]; +} // Notes whether the compaction marker exists while the serializer writes (issue #342: a flush that does not return leaves it) @interface MarkerSerializer : NSObject { @public id ser; int calls, marked; } @end @implementation MarkerSerializer @@ -444,6 +514,7 @@ int main(int argc, char **argv) { @autoreleasepool { EXPECT("compaction: none compiled from the new file", built0, g_pb_built); [NSFileManager.defaultManager removeItemAtPath:@(cdir) error:nil]; g_arch_dir = saved; g_arch4 = @[]; } + compute_pipelines(); // a function with no Metal 4 descriptor: the MTLDevice path uint64_t legacy = g_pb_legacy; id l = pso_build(desc(MTLPixelFormatRGBA8Unorm, 0, MTLPixelFormatRGBA8Unorm, MTLColorWriteMaskAll, 0), &err); diff --git a/dm/gfx/tests/t_pso_bundle.m b/dm/gfx/tests/t_pso_bundle.m index 9559a6d46d..396219a583 100644 --- a/dm/gfx/tests/t_pso_bundle.m +++ b/dm/gfx/tests/t_pso_bundle.m @@ -3,7 +3,9 @@ // bases without a vertex layout; with a matching stamp the prebuild builds only the pairs left to the device (a function with constants) and takes nothing from the compiler otherwise, // and a draw of a covered pair takes its base from the bundle and captures nothing for the device's own archive; // a stamp of another depth mode or other pairs runs the device's prebuild, which still takes the bundled bases it finds; an archive whose bases the probe does not find is not trusted; -// a folder without this GPU's file and a file that is no archive leave no archive. Without metal-tt (no Metal toolchain) it says so and passes +// a folder without this GPU's file and a file that is no archive leave no archive; the compute shaders of the shader map have their pipelines in the archive (cps_new: nothing +// built), and a shader with function constants or not in the map is built as before. +// Without metal-tt (no Metal toolchain) it says so and passes #include "../nvn/nvn_mtl.m" uint64_t g_t0_ns; int dm_guest_as_contains(uintptr_t address) { (void)address; return 0; } @@ -41,12 +43,19 @@ int main(void) { @autoreleasepool { "vertex V main0_z(uint id [[vertex_id]]) { V o; float2 uv = float2((id << 1) & 2, id & 2); o.p = float4(uv * 2 - 1, 0.5, 1); return o; }\n"; NSString *f = @"#include \nusing namespace metal;\nfragment float4 main0() { return float4(%d, %d, 0, 1); }\n"; NSString *fc = @"#include \nusing namespace metal;\nconstant bool k [[function_constant(0)]];\nfragment float4 main0() { return is_function_constant_defined(k) ? float4(1) : float4(0); }\n"; + NSString *k = @"#include \nusing namespace metal;\nkernel void main0(device uint *o [[buffer(0)]], uint i [[thread_position_in_grid]]) { o[i] = i * %d; }\n"; + NSString *kc = @"#include \nusing namespace metal;\nconstant uint m [[function_constant(0)]];\n" + "kernel void main0(device uint *o [[buffer(0)]], uint i [[thread_position_in_grid]]) { o[i] = is_function_constant_defined(m) ? m : i; }\n"; [NSFileManager.defaultManager createDirectoryAtPath:msl withIntermediateDirectories:YES attributes:nil error:nil]; - if (lib(msl, @"v1_bp", v) || lib(msl, @"f1_b", [NSString stringWithFormat:f, 1, 0]) || lib(msl, @"f2_b", [NSString stringWithFormat:f, 0, 1]) || lib(msl, @"fc_b", fc)) { + if (lib(msl, @"v1_bp", v) || lib(msl, @"f1_b", [NSString stringWithFormat:f, 1, 0]) || lib(msl, @"f2_b", [NSString stringWithFormat:f, 0, 1]) || lib(msl, @"fc_b", fc) || + lib(msl, @"c1_b", [NSString stringWithFormat:k, 2]) || lib(msl, @"c2_b", [NSString stringWithFormat:k, 4]) || + lib(msl, @"c3_b", [NSString stringWithFormat:k, 5]) || lib(msl, @"cc_b", kc)) { printf("t_pso_bundle: no Metal compiler (xcrun metal), GPU checks not run; %d file checks failed\n", failed); return failed != 0; } put([msl stringByAppendingPathComponent:@"v1_b.json"], [NSString stringWithFormat:@"{\"chain\": \"%s\", \"entry\": \"main0\", \"entry_z\": \"main0_z\", \"pull\": {}, \"vertex_inputs\": []}", DMSH_CHAIN]); for (NSString *k in @[@"f1", @"f2", @"fc"]) put([msl stringByAppendingFormat:@"/%@_b.json", k], [NSString stringWithFormat:@"{\"chain\": \"%s\", \"entry\": \"main0\"}", DMSH_CHAIN]); - put([tables stringByAppendingPathComponent:@"shader_map.tsv"], @"# empty\n"); + for (NSString *c in @[@"c1", @"c2", @"c3", @"cc"]) put([msl stringByAppendingFormat:@"/%@_b.json", c], [NSString stringWithFormat:@"{\"chain\": \"%s\", \"route\": \"B\", \"bindings\": [], \"stage\": \"cs\", \"entry\": \"main0\"%@}", + DMSH_CHAIN, @""]); + put([tables stringByAppendingPathComponent:@"shader_map.tsv"], @"package\tindex\tstage\tdm_ctl_sha16\tsource\ncs.bin\t0\tcompute\tc1\tx\ncs.bin\t1\tcompute\tc2\tx\ncs.bin\t2\tcompute\tcc\tx\n"); put([tables stringByAppendingPathComponent:@"shader_pairs.tsv"], @"# pairs\nv1\tf1\nv1\tf2\nv1\tfc\n"); setenv("DM_NVN_SHMAP", [tables stringByAppendingPathComponent:@"shader_map.tsv"].UTF8String, 1); setenv("DM_MSL_DIR", [root stringByAppendingPathComponent:@"msl"].UTF8String, 1); @@ -55,8 +64,8 @@ int main(void) { @autoreleasepool { NSString *gpu = g_dev.architecture.name; // the archive as build_ipa.sh makes it (the tool's own folder: this file is dm/gfx/tests/t_pso_bundle.m) NSString *tool = [[@(__FILE__) stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"../tools/pso_offline.py"]; - if (sh([NSString stringWithFormat:@"python3 %@ --platform macos --gpu %@ --msl %@ --pairs %@/shader_pairs.tsv --out %@ --work %@/work > %@/pso_offline.log 2>&1", - tool, gpu, msl, tables, bundle, root, root])) { + if (sh([NSString stringWithFormat:@"python3 %@ --platform macos --gpu %@ --msl %@ --pairs %@/shader_pairs.tsv --shader-map %@/shader_map.tsv --out %@ --work %@/work > %@/pso_offline.log 2>&1", + tool, gpu, msl, tables, tables, bundle, root, root])) { NSString *log = [NSString stringWithContentsOfFile:[root stringByAppendingPathComponent:@"pso_offline.log"] encoding:NSUTF8StringEncoding error:nil]; if ([log containsString:@"metal-tt is not available"]) { printf("t_pso_bundle: no metal-tt (xcodebuild -downloadComponent MetalToolchain), GPU checks not run; %d file checks failed\n", failed); return failed != 0; } fprintf(stderr, "pso_offline.py failed:\n%s\n", log.UTF8String); return 1; @@ -98,6 +107,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); + // compute pipelines: the shader map's compute shaders come from the bundle; a shader with function constants and one the map does not have are built + @autoreleasepool { + NvShader *c1 = shader_load(@"c1_b", 5, 0), *c2 = shader_load(@"c2_b", 5, 0), *c3 = shader_load(@"c3_b", 5, 0), *cc = shader_load(@"cc_b", 5, 0); NSError *err = nil; + EXPECT("compute: shaders loaded", 1, c1 && c2 && c3 && cc); + uint64_t a0 = g_cps_arch, b0 = g_cps_built; int n0 = g_arch_new; + EXPECT("compute: a pipeline", 1, c1 && cps_new(c1->fn, &err) != nil); + EXPECT("compute: a second pipeline", 1, c2 && cps_new(c2->fn, &err) != nil); + EXPECT("compute: both from the bundle", a0 + 2, g_cps_arch); + EXPECT("compute: nothing built", b0, g_cps_built); + EXPECT("compute with constants: a pipeline", 1, cc && cps_new(cc->fn, &err) != nil); + EXPECT("compute not in the map: a pipeline", 1, c3 && cps_new(c3->fn, &err) != nil); + EXPECT("compute with constants, not in the map: built", b0 + 2, g_cps_built); + EXPECT("compute with constants, not in the map: not from the bundle", a0 + 2, g_cps_arch); + dispatch_sync(cps_harvest_q(), ^{}); + EXPECT("compute not in the map: captured into this device's archive, the one with constants not", n0 + 1, g_arch_new); + } // 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", diff --git a/dm/gfx/tools/pso_offline.py b/dm/gfx/tools/pso_offline.py index 5279de1f54..abf810aa56 100644 --- a/dm/gfx/tools/pso_offline.py +++ b/dm/gfx/tools/pso_offline.py @@ -10,25 +10,32 @@ # through a base every primitive reads 0), a missing library or entry point # · a pair whose functions declare function constants is left to the device (rest_pairs.tsv): the host specializes such functions with an empty set of values, and metal-tt makes # no specialized function from a library (applegpu-nt: "cannot find private metadata"), nor the function unspecialized ("cannot lower module with unresolved function constants") +# And a compute pipeline per compute shader, which depends on its function alone (the host makes it from the function, cps_new in nvn_mtl.m; the threadgroup size is the dispatch's): +# the C rows of the profile's prewarm list (pso_manifest.tsv, recorded, in order), then every compute shader of its shader map (shader_map.tsv, stage compute), so a game whose list +# names none (a provisional profile) still has them; per shader _b, entry `entry`. Left out as the host would not find them: a reflection of another chain version or none, a +# missing library or entry point, a function with function constants (the host specializes it through its library, fn_lib_spec, and builds that pipeline through the MTLDevice) # Output folder (what the app bundles as pso/, the host's DM_PSO_BUNDLE): # .mtl4a one archive per GPU architecture (applegpu_g18p = A19 / A19 Pro); the host opens the one named after its device's architecture # prebuilt.tsv what the archives cover, in the host's stamp format (pso_prebuild): chain version, depth mode, the pair lists' size and SHA-256. The host skips its prebuild when # it matches and a probe of a few bases finds them in the archive # rest_pairs.tsv the pairs the device still builds (only when there are any) -# archive.tsv what was built: architectures, OS minimum, toolchain, bases (for people and logs; the host does not read it) +# archive.tsv what was built: architectures, OS minimum, toolchain, bases, compute pipelines (for people and logs; the host does not read it) # 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. # More bases than --batch-size are compiled in sequential groups (batches.// in the work folder, each cached by its own inputs) and merged with metal-pack: one metal-tt on # Super Mario Odyssey's 32,864 bases runs an 8 GB Mac out of paging space (docs/reference/shaders.md, Bounded groups for the offline pipeline compiler). The output is the same single file. +# With compute pipelines, they and the bases are separate groups (batches./c/ and /) merged the same way, so new pairs leave the compute pipelines compiled, and the +# reverse. The compute groups are small (COMPUTE_BATCH) and run --jobs at a time: one metal-tt keeps about three cores busy. # 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] [--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; +# [--depth gl|zero] [--platform ios|macos] [--os-min 27.0] [--script-only] [--batch-size N] [--shader-map ] [--manifest ] [--no-compute] [--jobs N] +# --game: the profile (DM_GAMES_DIR as for game.py) whose shader_pairs.tsv and pso_pairs.tsv are the pairs, whose shader_map.tsv and pso_manifest.tsv name the compute shaders, and +# whose depth_mode key the depth mode, unless --pairs / --shader-map / --manifest / --depth say; --no-compute: bases only; --jobs: metal-tt runs at a time for compute groups; # --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); # --os-min: the archives' system (default: for iOS the SDK's major version, e.g. 27.0; for macOS the major version this Mac runs, since the Mac app is built for the Mac that builds it). # A device opens only an archive of its own major version (macOS 27.2 refused archives made for 26.0 and 26.6 and opened those for 27.0 and 27.2), and builds the bases itself # otherwise: the SDK's version on a Mac whose system is older than its Xcode's SDK (macOS 26.6 with Xcode 27.1) left that Mac without them (GitHub issue #673) -import argparse, filecmp, hashlib, json, os, shutil, struct, subprocess, sys, time +import argparse, concurrent.futures, filecmp, hashlib, json, os, shutil, struct, subprocess, sys, time from pathlib import Path sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'tools')) @@ -36,6 +43,8 @@ LAYER = b'render_target_array_index' BATCH = 1000 # bases per metal-tt run: Odyssey's largest compiler lifetime footprint at this size was 2.065 GiB on an 8 GB M2 +COMPUTE_BATCH = 16 # compute pipelines per metal-tt run, JOBS runs at a time: one metal-tt keeps about 2-3 cores busy: Star Fox's 233 took 268 s in 16 groups against 453 s in one run (M5 Pro, background priority, a loaded Mac) +JOBS = max(1, (os.cpu_count() or 2) // 2) COLOUR = ('pixel_format', 'write_mask', 'blending_state', 'alpha_blend_operation', 'rgb_blend_operation', 'destination_alpha_blend_factor', 'destination_rgb_blend_factor', 'source_alpha_blend_factor', 'source_rgb_blend_factor') @@ -60,6 +69,19 @@ def read_pairs(text): return out +def read_computes(maps, manifests): + """The compute shaders by the library the host loads each from (_b, as shader_load names it): the prewarm lists' C rows in their order, then the shader maps' rows of stage + compute (column 3; the key is column 4, as shmap_load reads it), each once. Missing files are skipped""" + out = {} + for path, kind in [*((p, 'C') for p in manifests or ()), *((p, 'map') for p in maps or ())]: + if not path or not Path(path).is_file(): continue + for line in Path(path).read_text(encoding='utf-8').split('\n'): + c = line.rstrip('\r').split('\t') + if kind == 'C' and len(c) >= 2 and c[0] == 'C' and c[1]: out.setdefault(c[1], None) + elif kind == 'map' and len(c) > 3 and c[2] == 'compute' and c[3]: out.setdefault(c[3] + '_b', None) + return list(out) + + def stamp(chain, zero, text): """The host's prebuild stamp (pso_prebuild in nvn_mtl.m): chain version, depth mode, and the pair lists' length in bytes and SHA-256 (first 16 hex digits)""" return f'chain\t{chain}\ndepth\t{"near=0" if zero else "near=-w"}\npairs\t{len(text)}\t{hashlib.sha256(text).hexdigest()[:16]}\n' @@ -125,8 +147,26 @@ def writes_layer(lib): return bases, rest, left -def script(lib_dir, bases): - """A Metal 4 pipelines script (metal4-pipelines-script(5), the .mtl4-json format metal-tt reads) with one render pipeline descriptor per base""" +def plan_compute(lib_dir, chain, shaders): + """The compute pipelines the archive holds, [(library, entry)]: each of shaders (_b) with its reflection's entry; and counts of + the shaders left out as the host would not find their pipeline (reflection, library, entry point, function constants)""" + lib_dir = Path(lib_dir); pipes, seen = [], set(); left = dict.fromkeys(('reflection', 'library', 'entry', 'constants'), 0) + for pc in shaders: + try: j = json.loads((lib_dir / f'{pc}.json').read_bytes()) + except (OSError, ValueError): j = None + if not isinstance(j, dict) or j.get('chain') != chain or j.get('stage', 'cs') != 'cs': left['reflection'] += 1; continue + entry = j.get('entry') or 'main0' + try: fs = functions(lib_dir / f'{pc}.metallib') + except (OSError, ValueError): left['library'] += 1; continue + if entry not in fs: left['entry'] += 1; continue + if fs[entry]: left['constants'] += 1; continue + if (pc, entry) not in seen: seen.add((pc, entry)); pipes.append((pc, entry)) + return pipes, left + + +def script(lib_dir, bases, computes=()): + """A Metal 4 pipelines script (metal4-pipelines-script(5), the .mtl4-json format metal-tt reads) with one render pipeline descriptor per base, and one compute pipeline descriptor per + compute pipeline (library, entry) that names the function alone, as the host's lookup does (cps_bundle in nvn_mtl.m: no threadgroup size, no indirect command buffers)""" libs, fns, pipes = {}, {}, [] def fd(lib, entry): if lib not in libs: libs[lib] = {'label': lib, 'path': str(Path(lib_dir).resolve() / f'{lib}.metallib')} @@ -136,8 +176,10 @@ def fd(lib, entry): for vl, ve, fl, fe in bases: pipes.append({'vertex_function_descriptor': fd(vl, ve), 'fragment_function_descriptor': fd(fl, fe), 'color_attachments': [dict.fromkeys(COLOUR, 'Unspecialized') for _ in range(8)]}) + descriptors = {'render_pipeline_descriptors': pipes} + if computes: descriptors['compute_pipeline_descriptors'] = [{'compute_function_descriptor': fd(lib, entry)} for lib, entry in computes] # none: the script of bases alone, as before return {'libraries': list(libs.values()), 'function_descriptors': {'library_function_descriptors': list(fns.values())}, - 'pipeline_descriptors': {'render_pipeline_descriptors': pipes}} + 'pipeline_descriptors': descriptors} def write_script(path, configuration): @@ -149,10 +191,10 @@ def write_script(path, configuration): finally: part.unlink(missing_ok=True) -def library_digest(lib_dir, bases): +def library_digest(lib_dir, bases, computes=()): """The bytes metal-tt consumes: a profile/chain stamp does not change when the same shaders are rebuilt by another Metal compiler.""" h = hashlib.sha256() - for name in sorted({lib for vl, _, fl, _ in bases for lib in (vl, fl)}): + for name in sorted({lib for vl, _, fl, _ in bases for lib in (vl, fl)} | {lib for lib, _ in computes}): h.update(name.encode() + b'\0') lib = hashlib.sha256() with romfs.open(os.path.join(lib_dir, f'{name}.metallib'), 'rb') as f: @@ -221,12 +263,12 @@ def compile_archive(js, part, work, arch, platform, osmin, count): sys.exit(f'[RED] pso_offline: metal-tt failed for {arch} (exit {r.returncode}){full}: {log_path.read_text()[-2000:]}') -def real_libraries(lib_dir, bases, work): +def real_libraries(lib_dir, bases, work, computes=()): """Where metal-tt finds the bases' libraries: it takes file paths, so the libraries of one file get a temporary folder of what this compile reads, which clear_real_libraries removes after it. An archive whose key still holds compiles nothing and gets none""" if os.path.isdir(lib_dir): return lib_dir real = Path(work) / 'libraries'; shutil.rmtree(real, ignore_errors=True); real.mkdir(parents=True) - for name in sorted({lib for vl, _, fl, _ in bases for lib in (vl, fl)}): + for name in sorted({lib for vl, _, fl, _ in bases for lib in (vl, fl)} | {lib for lib, _ in computes}): with romfs.open(os.path.join(lib_dir, f'{name}.metallib'), 'rb') as f, open(real / f'{name}.metallib', 'wb') as o: shutil.copyfileobj(f, o) return real @@ -234,40 +276,56 @@ def real_libraries(lib_dir, bases, work): def clear_real_libraries(work): shutil.rmtree(Path(work) / 'libraries', ignore_errors=True) -def compile_batch(lib_dir, bases, work, arch, platform, osmin, toolchain): +def compile_batch(lib_dir, bases, work, arch, platform, osmin, toolchain, computes=()): """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) + configuration = script(lib_dir, bases, computes) js = work / 'bases.mtl4-json'; write_script(js, configuration) - key = archive_key(configuration, library_digest(lib_dir, bases), arch, platform, osmin, toolchain) + key = archive_key(configuration, library_digest(lib_dir, bases, computes), 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' - write_script(js, script(real_libraries(lib_dir, bases, work), bases)) - compile_archive(js, part, work, arch, platform, osmin, len(bases)) + write_script(js, script(real_libraries(lib_dir, bases, work, computes), bases, computes)) + compile_archive(js, part, work, arch, platform, osmin, len(bases) + len(computes)) clear_real_libraries(work) 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): +def groups_of(bases, computes, batch_size, compute_size=COMPUTE_BATCH): + """The groups compile_batches compiles, [(folder name, bases, compute pipelines)]: the bases in groups of batch_size (00001, ...), then the compute pipelines in groups of compute_size + of their own (c00001, ...), so that a change to either leaves the other's groups as they are. 0: one group of each""" + groups = [] + for prefix, items, size in (('', bases, batch_size), ('c', computes, compute_size)): + size = size or len(items) or 1 + for index, start in enumerate(range(0, len(items), size), 1): + group = items[start:start + size] + groups.append((f'{prefix}{index:05d}', group if not prefix else [], group if prefix else [])) + return groups + + +def compile_batches(lib_dir, bases, work, part, arch, platform, osmin, toolchain, batch_size, computes=(), jobs=1, compute_size=COMPUTE_BATCH): """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. + The groups of bases run one after the other, as before; the compute groups, small, jobs at a time, each in its own folder (its TMPDIR). """ - pieces = []; total = (len(bases) + batch_size - 1) // batch_size - for old in (work / f'batches.{arch}').glob('[0-9]*'): # the groups of a longer list than this one - if int(old.name) > total: shutil.rmtree(old) - 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) + groups = groups_of(bases, computes, batch_size, compute_size); total = len(groups); names = {name for name, _, _ in groups} + for old in [*(work / f'batches.{arch}').glob('[0-9]*'), *(work / f'batches.{arch}').glob('c[0-9]*')]: # the groups of a longer list than this one + if old.name not in names: shutil.rmtree(old) + def one(index, name, group, cgroup): + print(f'pso_offline: {arch}: batch {index}/{total}: {f"{len(group)} bases" if group else f"{len(cgroup)} compute pipelines"}, compiling or checking cache', flush=True) + piece, reused = compile_batch(lib_dir, group, work / f'batches.{arch}' / name, arch, platform, osmin, toolchain, cgroup) print(f'pso_offline: {arch}: batch {index}/{total}: ready ({"reused" if reused else "compiled"})', flush=True) + return piece + pieces = [one(i, *g) for i, g in enumerate(groups, 1) if g[1]] + with concurrent.futures.ThreadPoolExecutor(max(1, jobs)) as pool: # a failed group stops the build once the others under way have finished (their pieces stay cached) + futures = [pool.submit(one, i, *g) for i, g in enumerate(groups, 1) if not g[1]] + pieces += [f.result() for f in futures] 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') @@ -294,12 +352,17 @@ def main(argv=None): 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=BATCH, help=f'compile sequential groups of at most N bases and merge with metal-pack, when there are more (default {BATCH}; 0: one compiler invocation)') + ap.add_argument('--shader-map', action='append', help='shader_map.tsv: its compute shaders get pipelines (default: the profile\'s)') + ap.add_argument('--manifest', action='append', help='pso_manifest.tsv: its C rows first (default: the profile\'s)') + ap.add_argument('--no-compute', action='store_true', help='no compute pipelines, the bases alone') + ap.add_argument('--jobs', type=int, default=JOBS, help=f'metal-tt runs at a time for the compute pipelines (default {JOBS}, half the logical CPUs)') 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) a.pairs = a.pairs or [str(g.table('shader_pairs.tsv')), str(g.table('pso_pairs.tsv'))] + a.shader_map = a.shader_map or [str(g.table('shader_map.tsv'))]; a.manifest = a.manifest or [str(g.table('pso_manifest.tsv'))] a.depth = a.depth or g.get('depth_mode', 'gl') if a.depth not in ('gl', 'zero'): sys.exit(f'[RED] pso_offline: {g.id}: depth_mode must be gl or zero: {a.depth}') if not a.pairs: sys.exit('[RED] pso_offline: no pair lists (--pairs or --game)') @@ -314,19 +377,23 @@ def main(argv=None): t0 = time.time() pairs = read_pairs(text) bases, rest, left = plan(lib_dir, chain, pairs, zero) + shaders = [] if a.no_compute else read_computes(a.shader_map, a.manifest) + computes, cleft = plan_compute(lib_dir, chain, shaders) work.mkdir(parents=True, exist_ok=True); out.mkdir(parents=True, exist_ok=True) js = work / 'bases.mtl4-json' # metal-tt takes the format from the extension: .mtl4-json is Metal 4's (.mtlp-json is the Metal 3 format) - configuration = script(lib_dir, bases) + configuration = script(lib_dir, bases, computes) write_script(js, configuration) st = stamp(chain, zero, text) print(f'pso_offline: {len(pairs)} pairs: {len(bases)} bases, {len(rest)} left to the device (function constants), left out as the host leaves them: ' + ', '.join(f'{k} {v}' for k, v in left.items()) + f' ({time.time() - t0:.1f} s)') + if shaders: print(f'pso_offline: {len(shaders)} compute shaders: {len(computes)} compute pipelines, left out: ' + + ', '.join(f'{k} {v}' for k, v in cleft.items())) if a.script_only: (out / 'prebuilt.tsv').write_text(st); return 0 if pairs and not bases and not rest: sys.exit('[RED] pso_offline: no base to build') # pairs, but the host would leave out every one: wrong or missing libraries if not pairs: print('pso_offline: no pairs (only a header): nothing to build, no archive') # a profile whose split found no pair (GitHub issue #338) - if not bases: archs = [] # no pair, or every eligible pair needs device specialization; clear old archives and still write the stamp and the remainder list - osmin = a.os_min or os_min_default(a.platform); tv = tool_version(a.platform) if bases else 'not used (function constants only)' - libraries = library_digest(lib_dir, bases) + if not bases and not computes: archs = [] # no pair, or every eligible pair needs device specialization, and no compute pipeline; clear old archives and still write the stamp and the remainder list + osmin = a.os_min or os_min_default(a.platform); tv = tool_version(a.platform) if bases or computes else 'not used (function constants only)' + libraries = library_digest(lib_dir, bases, computes) keys = {arch: archive_key(configuration, libraries, arch, a.platform, osmin, tv) for arch in archs} del configuration # the compiler reads the script from disk for arch, key in keys.items(): @@ -334,12 +401,12 @@ 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) - t1 = time.time(); print(f'pso_offline: {arch}: metal-tt, {len(bases)} bases (minutes) ...', flush=True) - if a.batch_size and len(bases) > a.batch_size: - compile_batches(lib_dir, bases, work, part, arch, a.platform, osmin, tv, a.batch_size) + t1 = time.time(); print(f'pso_offline: {arch}: metal-tt, {len(bases)} bases, {len(computes)} compute pipelines (minutes) ...', flush=True) + if a.batch_size and len(groups_of(bases, computes, a.batch_size)) > 1: + compile_batches(lib_dir, bases, work, part, arch, a.platform, osmin, tv, a.batch_size, computes, a.jobs) else: - write_script(js, script(real_libraries(lib_dir, bases, work), bases)) - compile_archive(js, part, work, arch, a.platform, osmin, len(bases)) + write_script(js, script(real_libraries(lib_dir, bases, work, computes), bases, computes)) + compile_archive(js, part, work, arch, a.platform, osmin, len(bases) + len(computes)) clear_real_libraries(work) 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') @@ -350,7 +417,7 @@ def main(argv=None): if rest: rp.write_text(''.join(f'{v}\t{f}\n' for v, f in rest)) else: rp.unlink(missing_ok=True) (out / 'archive.tsv').write_text(f'# the pipeline archive made offline (dm/gfx/tools/pso_offline.py); the host reads prebuilt.tsv, not this file\narch\t{" ".join(archs)}\n' - f'platform\t{a.platform}\t{osmin}\ntoolchain\t{tv}\nbases\t{len(bases)}\nrest\t{len(rest)}\n') + f'platform\t{a.platform}\t{osmin}\ntoolchain\t{tv}\nbases\t{len(bases)}\nrest\t{len(rest)}\ncompute\t{len(computes)}\n') return 0 diff --git a/dm/ios/tools/build_ipa.sh b/dm/ios/tools/build_ipa.sh index 9b49ab3d35..321d573e7b 100755 --- a/dm/ios/tools/build_ipa.sh +++ b/dm/ios/tools/build_ipa.sh @@ -131,7 +131,7 @@ if [ -n "${PROGRAMS_TSV:-}" ]; then prog_back LJ=Gen/dm/p0/launcher.json else TD=Gen/dm; program_tables; LJ=Gen/dm/launcher.json; fi -# The pipeline archive made offline (dm/gfx/tools/pso_offline.py): the base of every shader pair, compiled here by metal-tt for each GPU architecture in DM_PSO_GPUS (comma-separated: +# The pipeline archive made offline (dm/gfx/tools/pso_offline.py): the base of every shader pair and a pipeline per compute shader of the shader map, compiled here by metal-tt for each GPU architecture in DM_PSO_GPUS (comma-separated: # g18p = A19 / A19 Pro; another family's device has its own architecture, applegpu_g19p = the family after the A19 (its archive compiles with the current toolchain); none = no archive), so the device # does not build them on its first start (Breath of the Wild: 15,767 bases, 7-8 minutes on an iPhone 17 Pro Max). # Only the Metal 4 path reads it, which iOS turns on for a game whose profile sets pso_mtl4 on: the default is what the profile's pso_gpu key names (whitespace-separated architectures, joined for diff --git a/dm/tools/tests/test_pso_offline.py b/dm/tools/tests/test_pso_offline.py index 06d5cf54ab..adf1ecae51 100644 --- a/dm/tools/tests/test_pso_offline.py +++ b/dm/tools/tests/test_pso_offline.py @@ -133,6 +133,45 @@ def test_script(self): self.assertEqual(len(p[0]['color_attachments'][0]), 9) +class Compute(unittest.TestCase): + """The compute pipelines: every compute shader of the shader map after the prewarm list's C rows, each from its function alone""" + d: Path # Plan.setUp's folder + setUp, shader = Plan.setUp, Plan.shader + def test_shaders_from_the_list_then_the_map(self): + m, l = self.d / 'shader_map.tsv', self.d / 'pso_manifest.tsv' + m.write_text('package\tindex\tstage\tdm_ctl_sha16\tsource\ncs\t0\tcompute\tc2\tx\nvs\t0\tvertex\tv\tx\ncs\t1\tcompute\tc1\tx\ncs\t2\tcompute\tc3\tx\n') + l.write_text('# header\nS\tv_b\t0\nC\tc1_b\nR\t00ff\nC\told_b\nC\tc1_b\n') + self.assertEqual(po.read_computes([m], [l]), ['c1_b', 'old_b', 'c2_b', 'c3_b']) # recorded order first, each once; the map's own order after + self.assertEqual(po.read_computes([m], [self.d / 'none.tsv']), ['c2_b', 'c1_b', 'c3_b']) # a provisional profile: no list, the map's alone + self.assertEqual(po.read_computes([], []), []) + + def test_pipelines_and_left_out(self): + self.shader('c1', {'stage': 'cs'}, {'_b': [('main0', False)]}) + self.shader('c2', {'stage': 'cs'}, {'_b': [('main0', False)]}) + self.shader('c3', {'stage': 'cs'}, {'_b': [('main0', True)]}) # function constants: the host specializes it, MTLDevice + self.shader('c4', {'stage': 'cs', 'entry': 'k'}, {'_b': [('main0', False)]}) + self.shader('c5', {'stage': 'cs', 'chain': 'fedcba987654'}, {'_b': [('main0', False)]}) + self.shader('c6', {'stage': 'cs'}, {}) + self.shader('v', {'stage': 'vs'}, {'_b': [('main0', False)]}) + keys = ['c1_b', 'c2_b', 'c3_b', 'c4_b', 'c5_b', 'c6_b', 'v_b', 'gone_b', 'c1_b'] + pipes, left = po.plan_compute(self.d, CHAIN, keys) + self.assertEqual(pipes, [('c1_b', 'main0'), ('c2_b', 'main0')]) # each once + self.assertEqual(left, {'reflection': 3, 'library': 1, 'entry': 1, 'constants': 1}) + + def test_script(self): + j = po.script(self.d, [('v_bp', 'main0', 'f_b', 'main0')], [('c_b', 'main0'), ('d_b', 'main0')]) + self.assertEqual([l['label'] for l in j['libraries']], ['v_bp', 'f_b', 'c_b', 'd_b']) + self.assertEqual(j['pipeline_descriptors']['compute_pipeline_descriptors'], # the function alone: what the host's lookup names (cps_bundle) + [{'compute_function_descriptor': 'fnd:c_b.main0'}, {'compute_function_descriptor': 'fnd:d_b.main0'}]) + self.assertNotIn('compute_pipeline_descriptors', po.script(self.d, [('v_bp', 'main0', 'f_b', 'main0')])['pipeline_descriptors']) # bases alone: the script as before + + def test_groups(self): + b, c = [('v', f'e{i}', 'f', 'main0') for i in range(3)], [(f'c{i}_b', 'main0') for i in range(3)] + self.assertEqual([(n, len(x), len(y)) for n, x, y in po.groups_of(b, c, 2, 2)], [('00001', 2, 0), ('00002', 1, 0), ('c00001', 0, 2), ('c00002', 0, 1)]) + self.assertEqual([(n, len(x), len(y)) for n, x, y in po.groups_of(b, [], 0, 0)], [('00001', 3, 0)]) + self.assertEqual([(n, len(x), len(y)) for n, x, y in po.groups_of([], c, 5, 0)], [('c00001', 0, 3)]) + + class Build(unittest.TestCase): """main: one archive per architecture, made again only when its key changes; the stamp, rest_pairs.tsv and archive.tsv beside them""" def setUp(self): @@ -253,8 +292,8 @@ def test_pipeline_entry_and_descriptor_changes_rebuild(self): self.main('--depth', 'gl') self.assertEqual(len(self.calls), 2) original = po.script - def changed(lib_dir, bases): - config = original(lib_dir, bases) + def changed(lib_dir, bases, computes=()): + config = original(lib_dir, bases, computes) config['pipeline_descriptors']['render_pipeline_descriptors'][0]['raster_sample_count'] = 4 return config with mock.patch.object(po, 'script', changed): @@ -456,6 +495,38 @@ def test_groups_of_a_longer_list_are_removed(self): self.main('--batch-size', '1', '--os-min', '27.0') self.assertEqual(sorted(d.name for d in groups.iterdir()), ['00001', '00002']) + def test_compute_pipelines_are_groups_of_their_own(self): + (self.prof / 'shader_map.tsv').write_text('package\tindex\tstage\tdm_ctl_sha16\tsource\ncs\t0\tcompute\tk\tx\ncs\t1\tcompute\tkc\tx\n') + (self.prof / 'pso_manifest.tsv').write_text('# list\nC\tk_b\n') + for k, const in (('k', False), ('kc', True)): + (self.lib / f'{k}_b.json').write_text(json.dumps({'chain': CHAIN, 'stage': 'cs', 'entry': 'main0'})) + (self.lib / f'{k}_b.metallib').write_bytes(metallib([('main0', const)])) + runner, observed = self.batched_runner() + def computes(): return [f['library'] for f in json.loads((self.work / 'bases.mtl4-json').read_text())['function_descriptors']['library_function_descriptors'] if f['library'].startswith('lib:k')] + with mock.patch.object(self, 'fake_run', runner): + self.main('--os-min', '27.0') + self.assertEqual(observed, [('compile', ['main0_z']), ('compile', []), ('merge', 2)]) # the bases, the compute pipelines, one archive + self.assertEqual(computes(), ['lib:k_b']) # kc has function constants: left to the host + self.assertIn('compute\t1\n', (self.out / 'archive.tsv').read_text()) + self.assertEqual(sorted(d.name for d in (self.work / 'batches.applegpu_g18p').iterdir()), ['00001', 'c00001']) + observed.clear(); self.main('--os-min', '27.0'); self.assertEqual(observed, []) # unchanged: the archive reused + (self.prof / 'shader_pairs.tsv').write_text('v\tc\nv\tf\n') # other pair lists, the same bases and compute pipelines: the archive reused + observed.clear(); self.main('--os-min', '27.0'); self.assertEqual(observed, []) + observed.clear(); self.main('--os-min', '27.0', '--depth', 'gl'); self.assertEqual(observed, [('compile', ['main0']), ('merge', 2)]) # other bases: the compute group kept + (self.lib / 'k_b.metallib').write_bytes(metallib([('main0', False), ('other', False)])) # another compute library: its group again, the bases kept + observed.clear(); self.main('--os-min', '27.0', '--depth', 'gl'); self.assertEqual(observed, [('compile', []), ('merge', 2)]) + observed.clear(); self.main('--os-min', '27.0', '--depth', 'gl', '--no-compute'); self.assertEqual(observed, [('compile', ['main0'])]) # bases alone: one compiler run + self.assertIn('compute\t0\n', (self.out / 'archive.tsv').read_text()) + + def test_compute_pipelines_alone_make_an_archive(self): # no base (every pair has function constants), but compute shaders: still an archive + (self.prof / 'shader_pairs.tsv').write_text('v\tc\n') + (self.prof / 'shader_map.tsv').write_text('p\ti\tstage\tkey\ts\ncs\t0\tcompute\tk\tx\n') + (self.lib / 'k_b.json').write_text(json.dumps({'chain': CHAIN, 'stage': 'cs', 'entry': 'main0'})); (self.lib / 'k_b.metallib').write_bytes(metallib([('main0', False)])) + self.assertEqual(self.main('--gpu', 'g18p'), 0) + self.assertEqual(len(self.calls), 1) + self.assertTrue((self.out / 'applegpu_g18p.mtl4a').is_file()) + self.assertEqual((self.out / 'rest_pairs.tsv').read_text(), 'v\tc\n') + 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() diff --git a/docs/agents/symptoms.md b/docs/agents/symptoms.md index 51c7c155a3..74c65e0f66 100644 --- a/docs/agents/symptoms.md +++ b/docs/agents/symptoms.md @@ -921,6 +921,8 @@ One line per symptom in the [subsystem references](../reference/): what you see - the offline archive stops with only `applegpu-nt command failed`, sometimes after `Max Unstruct ID` lines (a note, not the failure); 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](../reference/shaders.md#bounded-groups-for-the-offline-pipeline-compiler) - `--platform mac-app` or the iPhone build stops at its pipeline archive stage, after every earlier stage has finished: `[RED] pso_offline: metal-tt failed for applegpu_ (exit 1)`, then `pso_offline.py exit code 1`. → [A failed pipeline archive stops the whole build](../reference/shaders.md#a-failed-pipeline-archive-stops-the-whole-build) - `[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) +- a game without a recorded prewarm list (a provisional profile) stalls at its first dispatches while Metal compiles their compute pipelines. The Mac app's pipeline archive held render bases only (`archive.tsv`: `bases`), whatever the shader map listed. → [Compute pipelines compiled at first use](../reference/shaders.md#compute-pipelines-compiled-at-first-use) +- a compute pipeline the archive bundled with the app does not hold (no bundle, as in a headless boot or a build without `pso_offline.py`; a shader outside the shader map; an OS update the bundle's binaries do not survive) was compiled again at its first dispatch of every start the system's shader cache had dropped it, and the device's own pipeline archive (`pso_archive`) never held one: `compute pipelines so far: 0 from the archive bundled with the app, N built` start after start. → [Compute pipelines outside the bundled archive built at every start](../reference/shaders.md#compute-pipelines-outside-the-bundled-archive-built-at-every-start) - `[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) - at boot, `CRASH sig=5 … pc=_dispatch_once_wait.cold.1` right after the `pipeline bases so far` line, with `bt: pso_prebuild __shmap_load_block_invoke … mtl_prog_prefetch h_nvnProgramSetShaders`. → [The prepare step inside the shader map's once](../reference/shaders.md#the-prepare-step-inside-the-shader-maps-once) diff --git a/docs/development.md b/docs/development.md index 6131969ba0..0a318939d5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -585,7 +585,7 @@ The bundle holds what the IPA holds, with the Mac's shader libraries: The shader pairs are what the pipeline prebuild and the hybrid pipelines read ([Hybrid pipelines](#hybrid-pipelines)), as in the IPA; a profile without `pso_pairs.tsv` gets the shader split's copy (`--pso-pairs`). An app without them builds no base: [Shader-pair tables in a Mac app](reference/shaders.md#shader-pair-tables-in-a-mac-app). -An NVN game's app also carries its pipeline archive made offline ([The pipeline archive made offline](#the-pipeline-archive-made-offline)), built by `pso_offline.py --platform macos` for this Mac's GPU (`MTLDevice.architecture`, e.g. `applegpu_g14s` for an M2 Max; `--gpu` names others, `none` builds none) into `_build/pso/mac` and made again only when its inputs change. The launcher hands `Resources/pso` to the host as `DM_PSO_BUNDLE`, as the iOS app's `main.m` does: the first start builds no base (`pipeline archive bundled with the app: holds the bases of every shader pair (16 of 16 probed bases found …)`), and the bases (about 615 MB for Breath of the Wild) stay in the app instead of the player's `~/Library/Application Support`. On a Mac with another GPU, or after a macOS update that changed the GPU compiler, the app builds them there as before. `PSO_GPUS` is shared with the IPA, so a value that does not name this Mac's GPU (`g18p`, an iPhone's) still builds what it names, and the console says that this Mac's app will build its own bases. When every eligible pair declares function constants, `pso_offline.py` makes no archive and the app is packed without one. +An NVN game's app also carries its pipeline archive made offline ([The pipeline archive made offline](#the-pipeline-archive-made-offline)), built by `pso_offline.py --platform macos` for this Mac's GPU (`MTLDevice.architecture`, e.g. `applegpu_g14s` for an M2 Max; `--gpu` names others, `none` builds none) into `_build/pso/mac` and made again only when its inputs change, with a compute pipeline for each compute shader beside the bases. The launcher hands `Resources/pso` to the host as `DM_PSO_BUNDLE`, as the iOS app's `main.m` does: the first start builds no base (`pipeline archive bundled with the app: holds the bases of every shader pair (16 of 16 probed bases found …)`), and the bases (about 615 MB for Breath of the Wild) stay in the app instead of the player's `~/Library/Application Support`. On a Mac with another GPU, or after a macOS update that changed the GPU compiler, the app builds them there as before. `PSO_GPUS` is shared with the IPA, so a value that does not name this Mac's GPU (`g18p`, an iPhone's) still builds what it names, and the console says that this Mac's app will build its own bases. When every eligible pair declares function constants, `pso_offline.py` makes no archive and the app is packed without one. The RomFS (image or folder), the rewritten modules, the shader libraries, the pipeline archive and the DLC are APFS clones (`cp -c`) of the build's files when the app is on the same APFS volume, so they take no space of their own; each is probed with a real clone on its own, and those on another volume are copied, after a check for the free space they need. The app is written as `.partial` and replaces the old one only when it is complete. @@ -757,7 +757,7 @@ The bases are kept in a per-game pipeline archive in `pso_archive/` beside `pso_ Every start adds a file or more: Breath of the Wild wrote 5–7 per start, and each file a base is not in costs a lookup about 0.06 ms. With more than 8 files (`PSO_ARCH_COMPACT`) the archive is compacted: the bases the prewarm takes from the old files are captured again through the compiler from their original shader functions, without lookup archives; the flush after the prewarm writes them into one file, and the old files are removed (`arch_compact_finish`). Bases the prewarm did not take (no `pso_user.tsv` line names them) go with the old files and are built again when drawn. The log says `pipeline archive compacted: N files gave M bases …`. Importing bases through lookup archives could crash Metal during serialization ([issue #342](reference/shaders.md#a-compaction-flush-that-crashes-then-crashes-every-start)); capturing the original functions avoids that framework defect, at the cost of more compiler work on a compaction start. -The log shows `pipeline archive …: N files, … MB, opened in … ms` at start, `pipeline archive: N new pipeline bases written to …` after each flush, and after the prewarm a line counting the bases compiled, taken from the archive and reused. `DM_PSO_ARCHIVE=off` turns the archive off; `DM_PSO_ARCHIVE=` puts it elsewhere. `DM_PSO_MTL4=0` builds every pipeline through the `MTLDevice` as before, with no bases and no archive. The Metal 4 path, with the hybrid pipelines and the prebuild, is on by default on the Mac. On iOS it is on for a game whose profile sets `pso_mtl4 on` (Breath of the Wild, tested on an iPhone 17 Pro Max) or with `DM_PSO_MTL4=1`, and off otherwise: the archive's memory is not measured against an iPhone's limit yet. For such a game the standard on iOS is the prebuild's bases made on the Mac and shipped in the app ([The pipeline archive made offline](#the-pipeline-archive-made-offline)); the device builds them itself only as a fallback. Pipelines whose functions have no Metal 4 descriptor (the diagnostic `DM_NVN_HILITE` and `DM_NVN_MAGSCAN` overrides) always take the `MTLDevice` path. +The log shows `pipeline archive …: N files, … MB, opened in … ms` at start, `pipeline archive: N new pipeline bases written to …` after each flush (`… and M compute pipelines …` when it holds compute pipelines), and after the prewarm a line counting the bases compiled, taken from the archive and reused. `DM_PSO_ARCHIVE=off` turns the archive off; `DM_PSO_ARCHIVE=` puts it elsewhere. `DM_PSO_MTL4=0` builds every pipeline through the `MTLDevice` as before, with no bases and no archive. The Metal 4 path, with the hybrid pipelines and the prebuild, is on by default on the Mac. On iOS it is on for a game whose profile sets `pso_mtl4 on` (Breath of the Wild, tested on an iPhone 17 Pro Max) or with `DM_PSO_MTL4=1`, and off otherwise: the archive's memory is not measured against an iPhone's limit yet. For such a game the standard on iOS is the prebuild's bases made on the Mac and shipped in the app ([The pipeline archive made offline](#the-pipeline-archive-made-offline)); the device builds them itself only as a fallback. Pipelines whose functions have no Metal 4 descriptor (the diagnostic `DM_NVN_HILITE` and `DM_NVN_MAGSCAN` overrides) always take the `MTLDevice` path. During compaction, timed flushes defer while prewarm runs. Once it finishes, one archive-queue task flushes the recaptured bases and removes the old files. The pending count and serializer capture are protected by the same compile/flush lock, so a flush consumes the count for the bases it writes. @@ -801,6 +801,8 @@ On iOS the standard is the pipeline archive made on the Mac and shipped in the a 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. 3. The archives go into the app as `pso/` with `prebuilt.tsv`, the stamp the device's prebuild would write for the same chain version, depth mode and pair lists. With an archive, or for a game whose profile sets `pso_mtl4 on` (its hybrid pipelines draw with them), the IPA also packs the pulling libraries (`_bp`), which the bases are made of; an Xcode build copies them anyway. +The archive also holds a compute pipeline for every compute shader of the game, which needs no recorded play: a compute pipeline depends on its function alone (the host builds it from the function, with no threadgroup size or other option, and the dispatch gives the threadgroup size). `pso_offline.py` takes the `C` rows of the profile's `pso_manifest.tsv` in their order, then every row of stage `compute` in `shader_map.tsv` (`--shader-map`, `--manifest`; `--no-compute` leaves them out), and gives each `_b` a compute pipeline descriptor that names its entry alone. Left out: a function with function constants (the host specializes it through its library and builds it through the `MTLDevice`) ([Compute pipelines compiled at first use](reference/shaders.md#compute-pipelines-compiled-at-first-use)). The compute pipelines are groups of their own (`batches./c/`, 16 pipelines each, `--jobs` of them at a time, half the logical CPUs by default), merged with the bases by `metal-pack`, so a change to the pairs reuses them and the reverse. The host looks a compute shader's `_b` pipeline up in the bundled archive first (`cps_new` in `nvn_mtl.m`), at its first dispatch or its prewarm line, then in the device's own archive files; on a miss it builds it through the `MTLDevice` as before and compiles it again through the Metal 4 compiler into the current flush period in the background, so the next start takes it from the device's archive ([Compute pipelines outside the bundled archive built at every start](reference/shaders.md#compute-pipelines-outside-the-bundled-archive-built-at-every-start)). The prewarm's last lines count them (`compute pipelines so far: N from the archive bundled with the app, M from this device's archive, K built (… ms looking up, … ms building)`), and so does the `pipelines up to frame` line. The shipped `pso_manifest.tsv` is not changed: a first dispatch loads the shader's library and takes its pipeline from the archive. + `main.m` hands `pso/` to the host as `DM_PSO_BUNDLE` (`off` ignores it). The host opens the file named after the device's GPU architecture (`MTLDevice.architecture`, e.g. `applegpu_g18p.mtl4a`) read only and looks it up first among the files of bases without a vertex layout (`pso_bundle_open`); it never writes or compacts it. Before the prebuild, `pso_bundle_covers` compares the bundled `prebuilt.tsv` with this run's stamp, then looks up the bases of 16 pairs spread over the list. Coverage needs at least one actual lookup and no misses; ineligible sampled pairs supply no evidence. If both hold, the device builds no base, only the pairs in `rest_pairs.tsv`; otherwise it runs its own prebuild as before, which still takes from the bundle every base it finds there. An archive for another GPU, one the system cannot open (made for a newer system, or an OS update changed the GPU compiler), a probe that finds nothing, or a stamp of another depth mode each give an info line (`pipeline archive bundled with the app: …`), not a red one. The on-device prebuild is the fallback: it runs when the app has no archive for the device's GPU, when the system cannot open the archive or take its bases (an iOS update that changed the GPU compiler, a system older than its minimum), or when its stamp is not this run's (another depth mode, other pairs). The device's own archive (`pso_archive/`) gets only what the bundle lacks: a draw, the prewarm and the prebuild compile a base, which the serializer then captures, only after the bundle missed it, and bases with a vertex layout, which the bundle never holds (`t_pso_bundle` checks a covered pair's draw: no compile, nothing captured). A Mac app carries one for the Mac it was built on ([A Mac app](#a-mac-app)); a Mac-only build (`--platform mac`) builds its own archive as before, with the NSP script's prebuild tool ([Hybrid pipelines](#hybrid-pipelines)). Metal crashed (`MTL4ArchiveImpl::loadFromURL`) when handed a file that was no archive, a text file or a bare Mach-O header, so `arch_file_ok` checks the Mach-O load commands and payload ranges, universal slice bounds and the serializer's bundled Metal library ranges before opening a file; this holds for the device's own files too. It checks the container structure; the compiler's private payload remains Metal's responsibility. The settings: diff --git a/docs/reference/shaders.md b/docs/reference/shaders.md index 8ccc299d48..2b1b9b8e5f 100644 --- a/docs/reference/shaders.md +++ b/docs/reference/shaders.md @@ -1703,6 +1703,24 @@ Finding, keying and translating shaders (`dm/gfx/tools/shader_split.py`, `dmsh_b - **Found on:** Cruis'n Blast (0100B41013C82000, version 1.0.7; no profile in this repository), on a Mac with 366 MB free. - **Check:** `dm/tools/tests/test_pso_offline.py` (`test_low_disk_space_stops_before_metal_tt`). +### Compute pipelines compiled at first use + +- **Symptom:** a game without a recorded prewarm list (a provisional profile) stalls at its first dispatches while Metal compiles their compute pipelines. The Mac app's pipeline archive held render bases only (`archive.tsv`: `bases`), whatever the shader map listed. +- **Cause:** a compute pipeline was only ever built on the device, through the `MTLDevice` (`newComputePipelineStateWithFunction`), at its first dispatch or from the prewarm's `C` rows, and a provisional profile's `pso_manifest.tsv` has none. Yet such a pipeline depends on nothing but its function: the host passes no threadgroup size or other option (the dispatch gives the threadgroup size), so it can be compiled offline for every compute shader of the shader map. +- **Fix:** `pso_offline.py` adds a compute pipeline descriptor that names the function alone for the `_b` of every compute shader: the prewarm list's `C` rows first, then the map's rows of stage `compute`; shaders with function constants are left out (the host specializes them). They compile in groups of their own (`batches./c/`, 16 a group, `--jobs` groups at a time), cached by their inputs and merged with the bases. The host looks `_b` up in the bundled archive first (`cps_new`) and builds it on a miss; the prewarm's last lines count both. +- **Found on:** [Star Fox](../../dm/games/0400E88025B1A000/README.md) (v131072, with a provisional profile before this repository had one), chain `ae59da13e481`, on an M5 Pro, measured on a fork with other host changes: 233 compute shaders give 233 compute pipelines beside 3 bases, a 35 MB archive. Built in 16 groups, 7 at a time, in 268 s, against 453 s as one `metal-tt` run (842 and 829 s of CPU; both at background priority, with load averages of 19-26 from other jobs); unchanged inputs reuse it in 0.3 s. Two headless boots of 90 s to the title took all 7 of their compute pipelines from it and built none, with no watchdog stop. +- **Check:** `dm/tools/tests/test_pso_offline.py` (`Compute`, `test_compute_pipelines_are_groups_of_their_own`, `test_compute_pipelines_alone_make_an_archive`); `t_pso_bundle` builds an archive with compute shaders and checks that a map's shaders come from it and that a shader with constants or outside the map is built. +- **Open:** iOS archives get the compute pipelines too (`build_ipa.sh`), not measured on a device. + +### Compute pipelines outside the bundled archive built at every start + +- **Symptom:** a compute pipeline the archive bundled with the app does not hold (no bundle, as in a headless boot or a build without `pso_offline.py`; a shader outside the shader map; an OS update the bundle's binaries do not survive) was compiled again at its first dispatch of every start the system's shader cache had dropped it, and the device's own pipeline archive (`pso_archive`) never held one: `compute pipelines so far: 0 from the archive bundled with the app, N built` start after start. +- **Cause:** `cps_new` built such a pipeline through the `MTLDevice` (`newComputePipelineStateWithFunction`), which no pipeline serializer sees. Only the render bases went through the flush period's Metal 4 compiler, whose serializer captures what it compiles. +- **Fix:** a compute function with a Metal 4 library descriptor (`fn4_note`) is looked up in the bundle, then in the device's own archive files. On a miss it is built through the `MTLDevice` as before, for the dispatch, and compiled again through the Metal 4 compiler into the current flush period on a background queue, one at a time at utility QoS (`cps_harvest`, `arch_capture_cs`): the serializer captures compute pipelines as it captures bases, and the flush writes them. The dispatch does not wait for the capture, which compiles the pipeline whole where the `MTLDevice` gets it from the system's shader cache: a first version that built the dispatch's pipeline through the capture took 95 ms for Star Fox's first 5 compute pipelines, against 1.2 ms through the `MTLDevice`. A period with compute pipelines is a plain file, never a `p` one, so the lookups skip the prebuild's files. Compaction captures a compute pipeline the prewarm takes from an old file again, as it does bases. Still built through the `MTLDevice` and never looked up: a function with constants and the embedded kernels, which have no descriptor. The log counts them: `compute pipelines so far: N from the archive bundled with the app, M from this device's archive, K built (… ms looking up, … ms building)`, and `pipeline archive: … and M compute pipelines written to …`. +- **Measurement:** headless boots of 90 s to the title (frame 5,100) without the bundle, each series with an archive and prewarm list of its own. Before: 5 compute pipelines built at the first start (1.2 ms in all, from the system's shader cache) and 9 at the second (2.2 ms), none kept. After: 5 built at the first start (0.6 ms), and the flushes wrote them (`2 new pipeline bases and 1 compute pipelines`, `50 … and 4 compute pipelines`); the second start took 8 from the device's archive (the prewarm's `C` rows and the first dispatches; 1.4 ms of lookups in all) and built none. Both reached the same frame with the same five `[RED]` lines. With a warm system cache the two cost about the same; the archive keeps the pipelines when that cache drops them. +- **Found on:** [Star Fox](../../dm/games/0400E88025B1A000/README.md) (v131072, with a provisional profile before this repository had one), chain `ae59da13e481`, M5 Pro, macOS 27.0, on a fork with other host changes. +- **Check:** `t_pso_archive` (`compute_pipelines`): a compute pipeline is built, compiled into the flush period in the background, written to a plain file, taken from it again without a build, captured again during a compaction, and a function without a descriptor is built through the `MTLDevice`, never looked up and not captured; `t_pso_bundle`: a shader outside the map is captured, one with function constants is not. + ### The device's prewarm list unread without a seed list - **Symptom:** `[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).