okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
23.8 KiB643 linesraw
1// metal/src/gpu/runtime.cpp - include/strata/gpu/runtime.hpp on Metal (metal-cpp).  Skeleton of MAC-PLAN Phase 1.
2//
3// Memory model (measured on the M5 Max, phaseA-tests/mac-design.md):
4//   - every allocation is one MTLBuffer, storageModeShared, hazard tracking untracked (the engine orders its own work
5//     on streams, as on CUDA); the "device pointer" handed to the host code is the buffer's gpuAddress, which differs
6//     from contents() on Apple GPUs, so host code that wrongly dereferences a device pointer faults instead of
7//     silently working.  host_view() is the sanctioned CPU view.
8//   - all buffers sit in one MTLResidencySet attached to every queue, so kernels may take raw gpuAddress pointers.
9// Streams: a command queue + the open command buffer + the open compute encoder + a shared-event timeline.  Work is
10// committed at event records, synchronizations, host functions and every kFlushEvery dispatches.
11// Graphs: begin_capture switches the stream to recording; dispatch/copy/memset/event ops are kept as data and
12// re-encoded by graph_launch (encoding measured at ~0.17 us per dispatch on the M5 Max).
13#define NS_PRIVATE_IMPLEMENTATION
14#define MTL_PRIVATE_IMPLEMENTATION
15#include <execinfo.h>
16#include <Foundation/Foundation.hpp>
17#include <Metal/Metal.hpp>
18
19#include "strata/gpu/metal.hpp"
20#include "strata/gpu/runtime.hpp"
21
22#include <sys/sysctl.h>
23
24#include <atomic>
25#include <chrono>
26#include <cstdio>
27#include <cstring>
28#include <iterator>
29#include <map>
30#include <mutex>
31#include <thread>
32#include <vector>
33
34namespace strata::gpu {
35
36namespace {
37
38constexpr int kFlushEvery = 4096;   // dispatches per command buffer before an automatic commit
39
40struct Alloc {
41    MTL::Buffer* buf = nullptr;
42    uint64_t gpu = 0;
43    uint8_t* cpu = nullptr;
44    size_t bytes = 0;
45    bool host = false;   // from host_alloc (the host code holds the CPU address)
46    bool purged = false; // purge_device_allocations: its memory given back (any later copy is an error)
47};
48
49struct Op {
50    enum Kind { Dispatch, Copy, Fill, Record, Wait } kind = Dispatch;
51    MTL::ComputePipelineState* pipe = nullptr;
52    uint8_t args[256];
53    size_t arg_bytes = 0;
54    std::vector<uint8_t> big_args;
55    metal::Grid groups, threads;
56    size_t tg_bytes = 0;
57    void* dst = nullptr;
58    const void* src = nullptr;
59    size_t bytes = 0;
60    int value = 0;
61    Event ev = nullptr;
62};
63
64}  // namespace
65
66struct EventImpl {
67    MTL::SharedEvent* ev = nullptr;   // the recording stream's timeline
68    uint64_t value = 0;               // 0: never recorded (complete, as a fresh CUDA event)
69};
70
71struct GraphImpl {
72    std::vector<Op> ops;
73};
74struct GraphExecImpl {
75    std::vector<Op> ops;
76};
77
78struct StreamImpl {
79    MTL::CommandQueue* q = nullptr;
80    MTL::CommandBuffer* cb = nullptr;
81    MTL::ComputeCommandEncoder* enc = nullptr;
82    MTL::SharedEvent* tl = nullptr;
83    uint64_t submitted = 0;   // the timeline value the last committed command buffer signals
84    int pending = 0;          // dispatches in the open command buffer
85    GraphImpl* rec = nullptr;
86};
87
88namespace {
89
90struct Runtime {
91    MTL::Device* dev = nullptr;
92    MTL::ResidencySet* rs = nullptr;
93    std::mutex mu;
94    std::map<uint64_t, Alloc> by_gpu;   // gpuAddress -> allocation
95    std::map<uintptr_t, uint64_t> by_cpu;   // contents() -> gpuAddress
96    StreamImpl* legacy = nullptr;
97    std::map<std::string, MTL::ComputePipelineState*> pipes;
98    std::map<std::string, MTL::Library*> libs;
99    metal::Stats stats;
100};
101
102Runtime& rt() {
103    static Runtime* r = [] {
104        auto* x = new Runtime;
105        x->dev = MTL::CreateSystemDefaultDevice();
106        NS::Error* e = nullptr;
107        MTL::ResidencySetDescriptor* d = MTL::ResidencySetDescriptor::alloc()->init();
108        x->rs = x->dev->newResidencySet(d, &e);
109        d->release();
110        return x;
111    }();
112    return *r;
113}
114
115thread_local Error t_last = kSuccess;
116Error fail(Error e) {
117    if (e != kSuccess && e != kNotReady) t_last = e;
118    return e;
119}
120
121StreamImpl* make_stream() {
122    auto* s = new StreamImpl;
123    s->q = rt().dev->newCommandQueue();
124    s->q->addResidencySet(rt().rs);
125    s->tl = rt().dev->newSharedEvent();
126    s->tl->setSignaledValue(0);
127    return s;
128}
129
130StreamImpl* S(Stream s) {
131    if (s) return s;
132    Runtime& r = rt();
133    std::lock_guard<std::mutex> lk(r.mu);
134    if (!r.legacy) r.legacy = make_stream();
135    return r.legacy;
136}
137
138/// The allocation that holds GPU address `p` (or CPU address `p` of a host allocation), with the offset into it.
139const Alloc* find(const void* p, size_t* off) {
140    Runtime& r = rt();
141    std::lock_guard<std::mutex> lk(r.mu);
142    const uint64_t a = (uint64_t) (uintptr_t) p;
143    auto it = r.by_gpu.upper_bound(a);
144    if (it != r.by_gpu.begin()) {
145        --it;
146        if (a < it->first + it->second.bytes) { *off = a - it->first; return &it->second; }
147    }
148    auto ic = r.by_cpu.upper_bound((uintptr_t) p);
149    if (ic != r.by_cpu.begin()) {
150        --ic;
151        const Alloc& al = r.by_gpu[ic->second];
152        if ((uintptr_t) p < ic->first + al.bytes) { *off = (uintptr_t) p - ic->first; return &al; }
153    }
154    return nullptr;
155}
156
157MTL::CommandBuffer* open_cb(StreamImpl* s) {
158    if (!s->cb) {
159        s->cb = s->q->commandBufferWithUnretainedReferences();
160        s->cb->retain();
161        ++rt().stats.command_buffers;
162    }
163    return s->cb;
164}
165void end_encoder(StreamImpl* s) {
166    if (s->enc) { s->enc->endEncoding(); s->enc = nullptr; }
167}
168MTL::ComputeCommandEncoder* encoder(StreamImpl* s) {
169    if (!s->enc) s->enc = open_cb(s)->computeCommandEncoder();   // serial dispatch: each dispatch sees the last
170    return s->enc;
171}
172void flush(StreamImpl* s) {
173    if (!s->cb) return;
174    end_encoder(s);
175    s->cb->encodeSignalEvent(s->tl, ++s->submitted);
176    s->cb->commit();
177    s->cb->release();
178    s->cb = nullptr;
179    s->pending = 0;
180}
181Error wait_value(MTL::SharedEvent* ev, uint64_t v) {
182    while (ev->signaledValue() < v) std::this_thread::yield();
183    ++rt().stats.host_syncs;
184    return kSuccess;
185}
186
187void check_purged(const Alloc* a, const char* what) {
188    if (a && a->purged) {
189        std::fprintf(stderr, "strata metal runtime: a %s touches a device allocation of %.1f MB that was given back "
190                             "(STRATA_METAL_KEEP_HOST_WEIGHTS=1 keeps it)\n", what, a->bytes / 1e6);
191        void* fr[48];
192        backtrace_symbols_fd(fr, backtrace(fr, 48), 2);   // which host code still reads it
193        std::abort();
194    }
195}
196
197Error encode_copy(StreamImpl* s, void* dst, const void* src, size_t n) {
198    size_t od = 0, os = 0;
199    const Alloc* ad = find(dst, &od);
200    const Alloc* as = find(src, &os);
201    check_purged(ad, "copy");
202    check_purged(as, "copy");
203    if (ad && as) {   // buffer to buffer: a blit, in stream order
204        end_encoder(s);
205        MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder();
206        b->copyFromBuffer(as->buf, os, ad->buf, od, n);
207        b->endEncoding();
208        ++rt().stats.blits;
209        return kSuccess;
210    }
211    // ordinary host memory on one side: the stream's earlier work must be complete first (the conservative CUDA
212    // pageable-memory semantics: the call returns when the copy is done)
213    flush(s);
214    wait_value(s->tl, s->submitted);
215    uint8_t* d = ad ? ad->cpu + od : (uint8_t*) dst;
216    const uint8_t* sp = as ? as->cpu + os : (const uint8_t*) src;
217    std::memcpy(d, sp, n);
218    return kSuccess;
219}
220
221Error encode_fill(StreamImpl* s, void* p, int value, size_t n) {
222    size_t off = 0;
223    const Alloc* a = find(p, &off);
224    if (!a) return fail(kErrorInvalidValue);
225    check_purged(a, "fill");
226    end_encoder(s);
227    MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder();
228    b->fillBuffer(a->buf, NS::Range::Make(off, n), (uint8_t) value);
229    b->endEncoding();
230    ++rt().stats.blits;
231    return kSuccess;
232}
233
234Error encode_dispatch(StreamImpl* s, const Op& o) {
235    MTL::ComputeCommandEncoder* e = encoder(s);
236    e->setComputePipelineState(o.pipe);
237    if (o.big_args.empty()) e->setBytes(o.args, o.arg_bytes, 0);
238    else e->setBytes(o.big_args.data(), o.big_args.size(), 0);
239    if (o.tg_bytes) e->setThreadgroupMemoryLength(o.tg_bytes, 0);
240    e->dispatchThreadgroups(MTL::Size(o.groups.x, o.groups.y, o.groups.z), MTL::Size(o.threads.x, o.threads.y, o.threads.z));
241    ++rt().stats.dispatches;
242    if (++s->pending >= kFlushEvery) flush(s);
243    return kSuccess;
244}
245
246Error record_event(EventImpl* e, StreamImpl* s) {
247    flush(s);   // CUDA submits on launch: a recorded event must become complete without a further call
248    e->ev = s->tl;
249    e->value = s->submitted;
250    return kSuccess;
251}
252Error wait_event(StreamImpl* s, EventImpl* e) {
253    if (!e || e->value == 0) return kSuccess;
254    end_encoder(s);
255    open_cb(s)->encodeWait(e->ev, e->value);
256    return kSuccess;
257}
258
259Error run_op(StreamImpl* s, const Op& o) {
260    switch (o.kind) {
261        case Op::Dispatch: return encode_dispatch(s, o);
262        case Op::Copy: return encode_copy(s, o.dst, o.src, o.bytes);
263        case Op::Fill: return encode_fill(s, o.dst, o.value, o.bytes);
264        case Op::Record: return record_event(o.ev, s);
265        case Op::Wait: return wait_event(s, o.ev);
266    }
267    return kSuccess;
268}
269
270// STRATA_METAL_ALLOC_LOG=1: every allocation of 16 MB or more, with the running total (memory budgets on small Macs)
271void alloc_log(const char* what, size_t n) {
272    static const bool on = std::getenv("STRATA_METAL_ALLOC_LOG") != nullptr;
273    static std::atomic<uint64_t> tot{0};
274    const uint64_t t = tot += n;
275    if (on && n >= (16u << 20)) std::fprintf(stderr, "strata metal runtime: %s %.1f MB (total %.2f GB)\n", what, n / 1e6, t / 1e9);
276}
277
278Error new_alloc(void** p, size_t bytes, bool host) {
279    Runtime& r = rt();
280    const size_t n = bytes ? bytes : 1;
281    MTL::Buffer* b = r.dev->newBuffer(n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);
282    if (!b) return fail(kErrorMemoryAllocation);
283    Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, host};
284    alloc_log(host ? "host alloc" : "device alloc", n);
285    {
286        std::lock_guard<std::mutex> lk(r.mu);
287        r.by_gpu[a.gpu] = a;
288        r.by_cpu[(uintptr_t) a.cpu] = a.gpu;
289        r.rs->addAllocation(b);
290        r.rs->commit();
291    }
292    *p = host ? (void*) a.cpu : (void*) (uintptr_t) a.gpu;
293    return kSuccess;
294}
295
296Error free_alloc(void* p) {
297    if (!p) return kSuccess;
298    Runtime& r = rt();
299    size_t off = 0;
300    const Alloc* a = find(p, &off);
301    if (!a || off != 0) return fail(kErrorInvalidValue);
302    device_synchronize();   // as cudaFree: the GPU is done with it
303    std::lock_guard<std::mutex> lk(r.mu);
304    MTL::Buffer* b = a->buf;
305    const uint64_t g = a->gpu;
306    r.by_cpu.erase((uintptr_t) a->cpu);
307    r.by_gpu.erase(g);
308    r.rs->removeAllocation(b);
309    r.rs->commit();
310    b->release();
311    return kSuccess;
312}
313
314}  // namespace
315
316// ---------------------------------------------------------------------------------------------------- runtime.hpp
317void* host_view(const void* p) {
318    size_t off = 0;
319    const Alloc* a = find(p, &off);
320    return a ? a->cpu + off : nullptr;
321}
322
323// The Metal decode window reads the model itself; the device copies of the weights the shared host code uploads for
324// the CUDA-shaped kernels (the pack's dense pool, the native head, ...) are never read on Metal.  On a small Mac their
325// memory is worth more as expert arena: every device (not host) allocation of min_bytes or more is made purgeable-empty
326// and dropped from the residency set.  Returns the bytes given back.
327uint64_t purge_device_allocations(size_t min_bytes) {
328    Runtime& r = rt();
329    device_synchronize();
330    std::lock_guard<std::mutex> lk(r.mu);
331    uint64_t n = 0;
332    for (auto& [gpu, a] : r.by_gpu) {
333        if (a.host || a.purged || a.bytes < min_bytes) continue;
334        r.rs->removeAllocation(a.buf);
335        a.buf->setPurgeableState(MTL::PurgeableStateEmpty);
336        a.purged = true;
337        n += a.bytes;
338    }
339    r.rs->commit();
340    return n;
341}
342
343Error get_last_error() { const Error e = t_last; t_last = kSuccess; return e; }
344Error peek_last_error() { return t_last; }
345const char* error_string(Error e) {
346    switch (e) {
347        case kSuccess: return "no error";
348        case kNotReady: return "device not ready";
349        case kErrorInvalidValue: return "invalid argument";
350        case kErrorMemoryAllocation: return "out of memory";
351        case kErrorUnsupported: return "operation not supported on Metal";
352        case kErrorLaunchFailure: return "command buffer failed";
353    }
354    return "unknown Metal runtime error";
355}
356
357Error get_device(int* dev) { *dev = 0; return kSuccess; }
358Error set_device(int dev) { return dev == 0 ? kSuccess : fail(kErrorInvalidValue); }
359Error device_count(int* n) { *n = rt().dev ? 1 : 0; return kSuccess; }
360Error device_synchronize() {
361    Runtime& r = rt();
362    StreamImpl* s = S(nullptr);
363    flush(s);
364    return wait_value(s->tl, s->submitted);
365    (void) r;
366}
367Error mem_get_info(size_t* free_b, size_t* total_b) {
368    // the GPU's budget is the working set the OS grants this process; what is free is that minus what is allocated
369    MTL::Device* d = rt().dev;
370    const uint64_t budget = d->recommendedMaxWorkingSetSize();
371    const uint64_t used = d->currentAllocatedSize();
372    *total_b = (size_t) budget;
373    *free_b = (size_t) (used < budget ? budget - used : 0);
374    return kSuccess;
375}
376Error device_integrated(int* v, int) { *v = 1; return kSuccess; }
377Error device_sm_count(int* v, int) { *v = 0; return fail(kErrorUnsupported); }   // Apple reports no core count
378Error device_clock_khz(int* v, int) { *v = 0; return fail(kErrorUnsupported); }
379Error runtime_version(int* v) { *v = 0; return kSuccess; }
380Error device_can_access_peer(int* v, int, int) { *v = 0; return kSuccess; }
381Error device_enable_peer_access(int, unsigned) { return fail(kErrorUnsupported); }
382Error get_device_properties(DeviceProp* p, int dev) {
383    if (dev != 0) return fail(kErrorInvalidValue);
384    *p = DeviceProp{};
385    MTL::Device* d = rt().dev;
386    std::snprintf(p->name, sizeof p->name, "%s", d->name()->utf8String());
387    std::snprintf(p->gcnArchName, sizeof p->gcnArchName, "%s", d->supportsFamily(MTL::GPUFamilyApple10) ? "apple10" : "apple9-or-older");
388    p->warpSize = 32;   // the SIMD-group width of every Apple GPU
389    p->totalGlobalMem = (size_t) d->recommendedMaxWorkingSetSize();
390    return kSuccess;
391}
392
393Error malloc_device_raw(void** p, size_t bytes) { return new_alloc(p, bytes, false); }
394Error free_device(void* p) { return free_alloc(p); }
395Error host_alloc_raw(void** p, size_t bytes, unsigned) { return new_alloc(p, bytes, true); }
396Error free_host(void* p) {
397    {
398        Runtime& r = rt();
399        std::lock_guard<std::mutex> lk(r.mu);
400        auto it = r.by_cpu.find((uintptr_t) p);
401        if (it == r.by_cpu.end()) return fail(kErrorInvalidValue);
402    }
403    return free_alloc(p);
404}
405Error host_register(void* p, size_t bytes, unsigned) {
406    // existing host memory (an mmapped file, an arena) as a NoCopy buffer: page-aligned start and length required
407    const uintptr_t pg = 16384;
408    if (((uintptr_t) p % pg) != 0) return fail(kErrorInvalidValue);
409    Runtime& r = rt();
410    const size_t n = (bytes + pg - 1) / pg * pg;
411    MTL::Buffer* b = r.dev->newBuffer(p, n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked, nullptr);
412    if (!b) return fail(kErrorMemoryAllocation);
413    Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, true};
414    alloc_log("host register", n);
415    std::lock_guard<std::mutex> lk(r.mu);
416    r.by_gpu[a.gpu] = a;
417    r.by_cpu[(uintptr_t) a.cpu] = a.gpu;
418    r.rs->addAllocation(b);
419    r.rs->commit();
420    return kSuccess;
421}
422Error host_unregister(void* p) { return free_alloc(p); }
423Error host_device_pointer_raw(void** dev, void* host) {
424    size_t off = 0;
425    const Alloc* a = find(host, &off);
426    if (!a) return fail(kErrorInvalidValue);
427    *dev = (void*) (uintptr_t) (a->gpu + off);
428    return kSuccess;
429}
430Error memset_device(void* p, int value, size_t bytes) {
431    StreamImpl* s = S(nullptr);
432    const Error e = encode_fill(s, p, value, bytes);
433    flush(s);
434    wait_value(s->tl, s->submitted);
435    return e;
436}
437Error memset_async(void* p, int value, size_t bytes, Stream st) {
438    StreamImpl* s = S(st);
439    if (s->rec) {
440        Op o;
441        o.kind = Op::Fill; o.dst = p; o.value = value; o.bytes = bytes;
442        s->rec->ops.push_back(std::move(o));
443        return kSuccess;
444    }
445    return encode_fill(s, p, value, bytes);
446}
447
448Error memcpy_sync(void* dst, const void* src, size_t bytes, CopyKind) {
449    StreamImpl* s = S(nullptr);
450    const Error e = encode_copy(s, dst, src, bytes);
451    flush(s);
452    wait_value(s->tl, s->submitted);
453    return e;
454}
455Error memcpy_2d_async(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, CopyKind k, Stream st) {
456    for (size_t r = 0; r < height; ++r) {   // skeleton: one copy per row (rare in the engine)
457        const Error e = memcpy_async((uint8_t*) dst + r * dpitch, (const uint8_t*) src + r * spitch, width, k, st);
458        if (e != kSuccess) return e;
459    }
460    return kSuccess;
461}
462Error memcpy_peer_async(void* dst, int dst_dev, const void* src, int src_dev, size_t bytes, Stream st) {
463    if (dst_dev != 0 || src_dev != 0) return fail(kErrorInvalidValue);   // one GPU
464    return memcpy_async(dst, src, bytes, kDeviceToDevice, st);
465}
466Error memcpy_async(void* dst, const void* src, size_t bytes, CopyKind, Stream st) {
467    StreamImpl* s = S(st);
468    if (s->rec) {
469        Op o;
470        o.kind = Op::Copy; o.dst = dst; o.src = src; o.bytes = bytes;
471        s->rec->ops.push_back(std::move(o));
472        return kSuccess;
473    }
474    return encode_copy(s, dst, src, bytes);
475}
476
477Error stream_create(Stream* s, unsigned) { *s = make_stream(); return kSuccess; }
478Error stream_destroy(Stream s) {
479    if (!s) return kSuccess;
480    flush(s);
481    wait_value(s->tl, s->submitted);
482    s->tl->release();
483    s->q->release();
484    delete s;
485    return kSuccess;
486}
487Error stream_synchronize(Stream st) {
488    StreamImpl* s = S(st);
489    flush(s);
490    return wait_value(s->tl, s->submitted);
491}
492Error stream_query(Stream st) {
493    StreamImpl* s = S(st);
494    flush(s);
495    return s->tl->signaledValue() >= s->submitted ? kSuccess : kNotReady;
496}
497Error stream_wait_event(Stream st, Event e, unsigned) {
498    StreamImpl* s = S(st);
499    if (s->rec) {
500        Op o;
501        o.kind = Op::Wait; o.ev = e;
502        s->rec->ops.push_back(std::move(o));
503        return kSuccess;
504    }
505    return wait_event(s, e);
506}
507Error launch_host_func(Stream st, HostFn fn, void* arg) {
508    // skeleton: in stream order by completing the stream first (the engine's uses are rare; Phase 2 replaces this by a
509    // completion handler + a shared-event wait so the host thread does not block)
510    StreamImpl* s = S(st);
511    if (s->rec) return fail(kErrorUnsupported);
512    flush(s);
513    wait_value(s->tl, s->submitted);
514    fn(arg);
515    return kSuccess;
516}
517
518Error event_create(Event* e, unsigned) { *e = new EventImpl; return kSuccess; }
519Error event_destroy(Event e) {
520    delete e;
521    return kSuccess;
522}
523Error event_record(Event e, Stream st) {
524    StreamImpl* s = S(st);
525    if (s->rec) {
526        Op o;
527        o.kind = Op::Record; o.ev = e;
528        s->rec->ops.push_back(std::move(o));
529        return kSuccess;
530    }
531    return record_event(e, s);
532}
533Error event_query(Event e) { return !e->ev || e->ev->signaledValue() >= e->value ? kSuccess : kNotReady; }
534Error event_synchronize(Event e) { return e->ev ? wait_value(e->ev, e->value) : kSuccess; }
535Error event_elapsed_ms(float* ms, Event, Event) { *ms = 0.0f; return fail(kErrorUnsupported); }
536
537Error begin_capture(Stream st) {
538    StreamImpl* s = S(st);
539    if (s->rec) return fail(kErrorInvalidValue);
540    flush(s);
541    s->rec = new GraphImpl;
542    return kSuccess;
543}
544Error end_capture(Stream st, Graph* g) {
545    StreamImpl* s = S(st);
546    if (!s->rec) { *g = nullptr; return fail(kErrorInvalidValue); }
547    *g = s->rec;
548    s->rec = nullptr;
549    return kSuccess;
550}
551Error graph_node_count(Graph g, size_t* n) { *n = g ? g->ops.size() : 0; return kSuccess; }
552Error graph_instantiate(GraphExec* x, Graph g) {
553    *x = new GraphExecImpl{g->ops};
554    return kSuccess;
555}
556Error graph_launch(GraphExec x, Stream st) {
557    StreamImpl* s = S(st);
558    if (s->rec) {   // a graph launched into a capture becomes part of it (CUDA: a child graph)
559        s->rec->ops.insert(s->rec->ops.end(), x->ops.begin(), x->ops.end());
560        return kSuccess;
561    }
562    for (const Op& o : x->ops) {
563        const Error e = run_op(s, o);
564        if (e != kSuccess) return e;
565    }
566    return kSuccess;
567}
568Error graph_upload(GraphExec, Stream) { return kSuccess; }
569Error graph_destroy(Graph g) { delete g; return kSuccess; }
570Error graph_exec_destroy(GraphExec x) { delete x; return kSuccess; }
571
572// ---------------------------------------------------------------------------------------------------- metal.hpp
573namespace metal {
574
575MTL::Device* device() { return rt().dev; }
576
577MTL::ComputePipelineState* pipeline(const char* source_name, const char* source, const char* function, std::string& err) {
578    Runtime& r = rt();
579    const std::string key = std::string(source_name) + "::" + function;
580    std::lock_guard<std::mutex> lk(r.mu);
581    if (auto it = r.pipes.find(key); it != r.pipes.end()) return it->second;
582    MTL::Library*& lib = r.libs[source_name];
583    NS::Error* e = nullptr;
584    if (!lib) {
585        MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init();
586        co->setMathMode(MTL::MathModeSafe);   // no fast-math reassociation: parity with the CUDA reference first
587        lib = r.dev->newLibrary(NS::String::string(source, NS::UTF8StringEncoding), co, &e);
588        co->release();
589        if (!lib) {
590            err = std::string("MSL compile of ") + source_name + ": " + (e ? e->localizedDescription()->utf8String() : "?");
591            return nullptr;
592        }
593    }
594    MTL::Function* f = lib->newFunction(NS::String::string(function, NS::UTF8StringEncoding));
595    if (!f) { err = std::string("no MSL function ") + function; return nullptr; }
596    MTL::ComputePipelineState* p = r.dev->newComputePipelineState(f, &e);
597    f->release();
598    if (!p) { err = std::string("pipeline ") + function + ": " + (e ? e->localizedDescription()->utf8String() : "?"); return nullptr; }
599    r.pipes[key] = p;
600    return p;
601}
602
603Error dispatch(Stream st, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid groups, Grid threads,
604               size_t tg_bytes) {
605    if (arg_bytes > 4096) return fail(kErrorInvalidValue);   // setBytes limit
606    {   // Metal skips a dispatch above the pipeline's maxTotalThreadsPerThreadgroup without any error (#2323): stop instead
607        const uint64_t want = (uint64_t) threads.x * threads.y * threads.z;
608        if (p && want > (uint64_t) p->maxTotalThreadsPerThreadgroup()) {
609            Runtime& r = rt();
610            std::string name = "?";
611            {
612                std::lock_guard<std::mutex> lk(r.mu);
613                for (const auto& kv : r.pipes)
614                    if (kv.second == p) { name = kv.first; break; }
615            }
616            std::fprintf(stderr,
617                         "strata metal: the kernel %s can run at most %lu threads per threadgroup on this GPU (%s), but the "
618                         "launch asks for %lu.\nMetal skips such a dispatch without any error, so every answer would be "
619                         "wrong; stopping here instead.  Please report this (the GPU, macOS version and this line) at "
620                         "https://github.com/Niko1221/Strata/issues .  (#2323)\n",
621                         name.c_str(), (unsigned long) p->maxTotalThreadsPerThreadgroup(),
622                         r.dev->name()->utf8String(), (unsigned long) want);
623            std::fflush(stderr);
624            std::exit(6);
625        }
626    }
627    StreamImpl* s = S(st);
628    Op o;
629    o.kind = Op::Dispatch;
630    o.pipe = p;
631    if (arg_bytes <= sizeof o.args) { std::memcpy(o.args, args, arg_bytes); o.arg_bytes = arg_bytes; }
632    else o.big_args.assign((const uint8_t*) args, (const uint8_t*) args + arg_bytes);
633    o.groups = groups;
634    o.threads = threads;
635    o.tg_bytes = tg_bytes;
636    if (s->rec) { s->rec->ops.push_back(std::move(o)); return kSuccess; }
637    return encode_dispatch(s, o);
638}
639
640Stats stats() { return rt().stats; }
641
642}  // namespace metal
643}  // namespace strata::gpu