okami.mom/strata

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

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

main
21.7 KiB494 linesraw
1// metal/src/mtl_rt.mm - see mtl_rt.h.  Built with ARC (-fobjc-arc).
2#import <Foundation/Foundation.h>
3#import <Metal/Metal.h>
4
5#include "mtl_rt.h"
6#include "resource_path.h"
7
8#include <chrono>
9#include <cstdio>
10#include <cstdlib>
11#include <fstream>
12#include <sstream>
13
14namespace mtl {
15
16double now_s() {
17    return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count();
18}
19
20std::string read_file(const std::string& path) {
21    std::ifstream f(path, std::ios::binary);
22    if (!f) {
23        std::fprintf(stderr, "mtl: cannot read %s\n", path.c_str());
24        std::exit(2);
25    }
26    std::stringstream ss;
27    ss << f.rdbuf();
28    return ss.str();
29}
30
31struct Context::Impl {
32    id<MTLDevice> dev;
33    id<MTLCommandQueue> q;
34    id<MTLCommandQueue> q2 = nil;   // run_graph_async's queue
35    std::vector<id<MTLLibrary>> libs;
36    id<MTLSharedEvent> ev = nil;   // run_graph_seg's handshake timeline
37    uint64_t ev_v = 0;
38};
39
40static inline id<MTLBuffer> B(const Buffer& b) { return (__bridge id<MTLBuffer>)b.handle; }
41// the MTLBuffer and offset that bind byte `off` of b (a chunked buffer: the chunk the offset selects)
42static inline id<MTLBuffer> BO(const Buffer& b, size_t off, size_t& o) {
43    if (!b.chunks) { o = off + b.bias; return B(b); }   // (bias: a view onto part of a bigger allocation; 0 otherwise)
44    const size_t k = std::min(off / b.stride, b.chunks->size() - 1);
45    o = off - k * b.stride;
46    return (__bridge id<MTLBuffer>)(*b.chunks)[k];
47}
48static inline id<MTLComputePipelineState> P(const Pipeline* p) { return (__bridge id<MTLComputePipelineState>)p->handle; }
49static std::string g_device_name = "unknown GPU";
50
51Context::Context() : impl_(new Impl) {
52    impl_->dev = MTLCreateSystemDefaultDevice();
53    if (!impl_->dev) {
54        std::fprintf(stderr, "mtl: no Metal device\n");
55        std::exit(2);
56    }
57    impl_->q = [impl_->dev newCommandQueue];
58    // env, then <exe dir>/metal/ (a component package), then the compiled-in source-tree path
59    ggml_common_path = strata_metal::resource2("STRATA_GGML_COMMON", "strata-quant-common.h", "ggml-common.h", STRATA_GGML_COMMON_DEFAULT);
60    kernel_dir = strata_metal::resource("STRATA_METAL_KERNELS", "kernels", STRATA_METAL_KERNELS_DEFAULT);
61}
62
63Context::~Context() { delete impl_; }
64
65std::string Context::device_name() const { return [[impl_->dev name] UTF8String]; }
66bool Context::has_family_apple(int n) const {
67    return [impl_->dev supportsFamily:(MTLGPUFamily)(MTLGPUFamilyApple1 + (n - 1))];
68}
69bool Context::supports_metal4() const {
70    if (@available(macOS 26.0, *)) return [impl_->dev supportsFamily:MTLGPUFamilyMetal4];
71    return false;
72}
73uint64_t Context::recommended_working_set() const { return [impl_->dev recommendedMaxWorkingSetSize]; }
74uint64_t Context::max_buffer_length() const { return [impl_->dev maxBufferLength]; }
75
76int Context::compile(const std::vector<std::string>& files, const std::string& prelude, bool fast_math) {
77    std::string why;
78    const int id = compile_try(files, prelude, fast_math, &why);
79    if (id < 0) {
80        std::fprintf(stderr, "mtl: compile failed (%s, macOS %s; %s):\n%s\n", [[impl_->dev name] UTF8String],
81                     [[[NSProcessInfo processInfo] operatingSystemVersionString] UTF8String],
82                     files.empty() ? "?" : files.back().c_str(), why.c_str());
83        std::exit(3);
84    }
85    return id;
86}
87
88// The same, and a failure is returned (-1, the compiler's message in *why) instead of ending the process: for a library that has a fallback.
89int Context::compile_try(const std::vector<std::string>& files, const std::string& prelude, bool fast_math, std::string* why) {
90    std::string src = prelude + "\n#include <metal_stdlib>\nusing namespace metal;\n";
91    if (!ggml_common_path.empty() && prelude.find("NO_GGML_COMMON") == std::string::npos) {
92        src += "#define GGML_COMMON_DECL_METAL\n#define GGML_COMMON_IMPL_METAL\n";
93        src += read_file(ggml_common_path);
94        src += "\n";
95    }
96    for (const auto& f : files) {
97        std::string p = (f.size() && f[0] == '/') ? f : kernel_dir + "/" + f;
98        src += "#line 1 \"" + f + "\"\n" + read_file(p) + "\n";
99    }
100    if (const char* dump = std::getenv("STRATA_METAL_MSL_DUMP")) {   // research: the full text of every library, as the compiler gets it
101        static int ndump = 0;
102        char name[32];
103        std::snprintf(name, sizeof name, "/%03d.msl", ndump++);
104        if (std::FILE* f = std::fopen((std::string(dump) + name).c_str(), "wb")) {
105            std::fwrite(src.data(), 1, src.size(), f);
106            std::fclose(f);
107        }
108        if (std::FILE* f = std::fopen((std::string(dump) + "/index.txt").c_str(), "ab")) {
109            std::fprintf(f, "%s:", name + 1);
110            for (const auto& fl : files) std::fprintf(f, " %s", fl.c_str());
111            std::fprintf(f, "\n");
112            std::fclose(f);
113        }
114    }
115    MTLCompileOptions* o = [MTLCompileOptions new];
116    // Safe math by default: no reassociation, so every token of a window is bitwise what a one-token call gives
117    // (the kernels write their contractions as explicit fma).  Measured free on the M5 Max.
118    fast_math = false;
119    if (const char* m = std::getenv("STRATA_METAL_MATH")) fast_math = std::string(m) == "fast";
120    if (@available(macOS 15.0, *)) {
121        o.mathMode = fast_math ? MTLMathModeFast : MTLMathModeSafe;
122    } else {
123        o.fastMathEnabled = fast_math;
124    }
125    NSError* err = nil;
126    id<MTLLibrary> lib = [impl_->dev newLibraryWithSource:[NSString stringWithUTF8String:src.c_str()] options:o error:&err];
127    if (!lib) {
128        if (why) *why = err ? [[err localizedDescription] UTF8String] : "unknown";
129        return -1;
130    }
131    impl_->libs.push_back(lib);
132    return (int)impl_->libs.size() - 1;
133}
134
135Pipeline Context::pipeline(int lib, const std::string& fn, const Constants& c) {
136    NSError* err = nil;
137    id<MTLFunction> f;
138    NSString* name = [NSString stringWithUTF8String:fn.c_str()];
139    if (c.vals.empty()) {
140        f = [impl_->libs[lib] newFunctionWithName:name];
141        // a function with (optional) function constants needs a specialization even when none is set
142        if (f && f.functionConstantsDictionary.count > 0)
143            f = [impl_->libs[lib] newFunctionWithName:name constantValues:[MTLFunctionConstantValues new] error:&err];
144    } else {
145        MTLFunctionConstantValues* cv = [MTLFunctionConstantValues new];
146        for (const auto& v : c.vals) {
147            int32_t iv = (int32_t)v.v;
148            bool bv = v.v != 0;
149            uint32_t uv = v.v;
150            switch (v.type) {
151                case 0: [cv setConstantValue:&iv type:MTLDataTypeInt atIndex:v.index]; break;
152                case 1: [cv setConstantValue:&bv type:MTLDataTypeBool atIndex:v.index]; break;
153                default: [cv setConstantValue:&uv type:MTLDataTypeUInt atIndex:v.index]; break;
154            }
155        }
156        f = [impl_->libs[lib] newFunctionWithName:name constantValues:cv error:&err];
157    }
158    if (!f) {
159        std::fprintf(stderr, "mtl: no function %s %s\n", fn.c_str(), err ? [[err localizedDescription] UTF8String] : "");
160        std::exit(3);
161    }
162    MTLComputePipelineDescriptor* d = [MTLComputePipelineDescriptor new];
163    d.computeFunction = f;
164    d.supportIndirectCommandBuffers = YES;
165    id<MTLComputePipelineState> ps = [impl_->dev newComputePipelineStateWithDescriptor:d
166                                                                               options:MTLPipelineOptionNone
167                                                                            reflection:nil
168                                                                                 error:&err];
169    if (!ps) {
170        std::fprintf(stderr, "mtl: pipeline %s: %s\n", fn.c_str(), [[err localizedDescription] UTF8String]);
171        std::exit(3);
172    }
173    Pipeline p;
174    p.handle = (__bridge_retained void*)ps;
175    p.max_threads = (int)ps.maxTotalThreadsPerThreadgroup;
176    if (const char* cap = std::getenv("STRATA_METAL_MAX_THREADS_CAP")) {   // test hook, see require_fit
177        const int lim = std::atoi(cap);
178        if (lim > 0 && lim < p.max_threads) p.max_threads = lim;
179    }
180    p.simd_width = (int)ps.threadExecutionWidth;
181    p.static_tg_mem = (int)ps.staticThreadgroupMemoryLength;
182    p.name = fn;
183    if (!c.vals.empty()) {
184        p.name += "{";
185        for (size_t i = 0; i < c.vals.size(); ++i)
186            p.name += (i ? "," : "") + std::to_string(c.vals[i].index) + "=" + std::to_string((int)c.vals[i].v);
187        p.name += "}";
188    }
189    g_device_name = [[impl_->dev name] UTF8String];
190    return p;
191}
192
193void require_fit(const Pipeline& p, uint32_t threads, const char* where) {
194    if (threads == 0 || (int64_t)threads <= (int64_t)p.max_threads) return;
195    std::fprintf(stderr,
196                 "strata metal: the kernel %s can run at most %d threads per threadgroup on this GPU (%s), but the %s asks "
197                 "for %u.\nMetal skips such a dispatch without any error, so every answer would be wrong; stopping here "
198                 "instead.  Please report this (the GPU, macOS version and this line) at "
199                 "https://github.com/Niko1221/Strata/issues .  (#2323)\n",
200                 p.name.empty() ? "?" : p.name.c_str(), p.max_threads, g_device_name.c_str(), where, threads);
201    std::fflush(stderr);
202    std::exit(6);
203}
204
205Buffer Context::alloc(size_t bytes) {
206    id<MTLBuffer> b = [impl_->dev newBufferWithLength:bytes options:MTLResourceStorageModeShared];
207    if (!b) {
208        std::fprintf(stderr, "mtl: alloc %zu failed\n", bytes);
209        std::exit(4);
210    }
211    std::memset([b contents], 0, bytes);
212    allocated_ += bytes;
213    Buffer r;
214    r.handle = (__bridge_retained void*)b;
215    r.ptr = [b contents];
216    r.bytes = bytes;
217    return r;
218}
219
220Buffer Context::wrap(void* p, size_t bytes, size_t max_span) {
221    const size_t pg = 16384, maxlen = [impl_->dev maxBufferLength] / pg * pg;
222    if (bytes <= maxlen || std::getenv("STRATA_METAL_WRAP_SPLIT") && std::string(std::getenv("STRATA_METAL_WRAP_SPLIT")) == "0")
223        return wrap(p, bytes);
224    const size_t span = (max_span + pg - 1) / pg * pg;
225    if (span >= maxlen / 2) {
226        std::fprintf(stderr, "mtl: wrap %zu: a tensor of %zu bytes does not fit the chunks\n", bytes, max_span);
227        std::exit(4);
228    }
229    Buffer r;
230    r.chunks = std::make_shared<std::vector<void*>>();
231    r.stride = maxlen - span;
232    for (size_t base = 0; base < bytes; base += r.stride) {
233        const size_t len = std::min(maxlen, (bytes - base + pg - 1) / pg * pg);
234        id<MTLBuffer> b = [impl_->dev newBufferWithBytesNoCopy:(uint8_t*) p + base length:len
235                                                        options:MTLResourceStorageModeShared deallocator:nil];
236        if (!b) {
237            std::fprintf(stderr, "mtl: wrap chunk %zu+%zu failed\n", base, len);
238            std::exit(4);
239        }
240        r.chunks->push_back((__bridge_retained void*)b);
241        if (base + len >= bytes) break;
242    }
243    allocated_ += bytes;
244    r.handle = (*r.chunks)[0];
245    r.ptr = p;
246    r.bytes = bytes;
247    std::fprintf(stderr, "mtl: wrapped %.2f GB as %zu overlapping buffers (maxBufferLength %.2f GB, overlap %.2f GB)\n",
248                 bytes / 1e9, r.chunks->size(), maxlen / 1e9, span / 1e9);
249    return r;
250}
251
252Buffer Context::wrap(void* p, size_t bytes) {
253    id<MTLBuffer> b = [impl_->dev newBufferWithBytesNoCopy:p length:bytes options:MTLResourceStorageModeShared deallocator:nil];
254    if (!b) {
255        std::fprintf(stderr, "mtl: wrap %zu failed\n", bytes);
256        std::exit(4);
257    }
258    allocated_ += bytes;
259    Buffer r;
260    r.handle = (__bridge_retained void*)b;
261    r.ptr = p;
262    r.bytes = bytes;
263    return r;
264}
265
266void Context::free(Buffer& b) {
267    if (b.chunks) {
268        for (void* h : *b.chunks) { id<MTLBuffer> x = (__bridge_transfer id<MTLBuffer>)h; x = nil; }
269        b = Buffer{};
270        return;
271    }
272    if (b.handle) {
273        id<MTLBuffer> x = (__bridge_transfer id<MTLBuffer>)b.handle;
274        x = nil;
275    }
276    b = Buffer{};
277}
278
279static void encode(id<MTLComputeCommandEncoder> enc, const Dispatch& d) {
280    require_fit(d, "dispatch");
281    [enc setComputePipelineState:P(d.p)];
282    for (size_t i = 0; i < d.args.size(); ++i) {
283        const Arg& a = d.args[i];
284        if (a.buf) {
285            size_t o;
286            id<MTLBuffer> mb = BO(*a.buf, a.off, o);
287            [enc setBuffer:mb offset:o atIndex:i];
288        }
289        else
290            [enc setBytes:a.bytes.data() length:a.bytes.size() atIndex:i];
291    }
292    if (d.tg_mem) [enc setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0];
293    if (d.indirect)
294        [enc dispatchThreadgroupsWithIndirectBuffer:B(*d.indirect)
295                               indirectBufferOffset:d.ind_off
296                              threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];
297    else
298        [enc dispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2])
299            threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];
300}
301
302double Context::run(const std::vector<Dispatch>& ds, int reps, bool concurrent, bool barrier_between) {
303    @autoreleasepool {
304        id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
305        id<MTLComputeCommandEncoder> enc =
306            [cb computeCommandEncoderWithDispatchType:concurrent ? MTLDispatchTypeConcurrent : MTLDispatchTypeSerial];
307        for (int r = 0; r < reps; ++r)
308            for (const auto& d : ds) {
309                encode(enc, d);
310                if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
311            }
312        [enc endEncoding];
313        [cb commit];
314        [cb waitUntilCompleted];
315        if (cb.status != MTLCommandBufferStatusCompleted) {
316            std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
317            std::exit(5);
318        }
319        return cb.GPUEndTime - cb.GPUStartTime;
320    }
321}
322
323double Context::run_graph(const std::vector<Dispatch>& ds, size_t count) {
324    // The wait spins on the buffer's status for up to 20 ms before it blocks: waitUntilCompleted's thread wake costs ~0.5 ms
325    // a window (M5 Max, Q2_0 decode: +5% tok/s, same tokens).  STRATA_METAL_SPIN=0: the blocking wait.
326    static const bool spin = !(std::getenv("STRATA_METAL_SPIN") && std::string(std::getenv("STRATA_METAL_SPIN")) == "0");
327    @autoreleasepool {
328        id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
329        id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
330        const size_t nd = std::min(count, ds.size());
331        for (size_t i = 0; i < nd; ++i) {
332            if (i > 0 && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
333            encode(enc, ds[i]);
334        }
335        [enc endEncoding];
336        [cb commit];
337        if (spin) {
338            const auto t0 = std::chrono::steady_clock::now();
339            while (cb.status < MTLCommandBufferStatusCompleted &&
340                   std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count() < 20e-3) {}
341        }
342        if (cb.status < MTLCommandBufferStatusCompleted) [cb waitUntilCompleted];
343        if (cb.status != MTLCommandBufferStatusCompleted) {
344            std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
345            std::exit(5);
346        }
347        return cb.GPUEndTime - cb.GPUStartTime;
348    }
349}
350
351void* Context::run_graph_async(const std::vector<Dispatch>& ds) {
352    @autoreleasepool {
353        if (impl_->q2 == nil) impl_->q2 = [impl_->dev newCommandQueue];
354        id<MTLCommandBuffer> cb = [impl_->q2 commandBufferWithUnretainedReferences];
355        id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
356        for (size_t i = 0; i < ds.size(); ++i) {
357            if (i > 0 && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
358            encode(enc, ds[i]);
359        }
360        [enc endEncoding];
361        [cb commit];
362        return (__bridge_retained void*) cb;
363    }
364}
365
366double Context::wait_async(void* token) {
367    if (token == nullptr) return 0.0;
368    @autoreleasepool {
369        id<MTLCommandBuffer> cb = (__bridge_transfer id<MTLCommandBuffer>) token;
370        if (cb.status < MTLCommandBufferStatusCompleted) [cb waitUntilCompleted];
371        if (cb.status != MTLCommandBufferStatusCompleted) {
372            std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
373            std::exit(5);
374        }
375        return cb.GPUEndTime - cb.GPUStartTime;
376    }
377}
378
379double Context::run_graph_seg(const std::vector<Dispatch>& ds, const std::vector<int>& cuts, void (*at_cut)(void*, int),
380                              void* user) {
381    @autoreleasepool {
382        if (impl_->ev == nil) impl_->ev = [impl_->dev newSharedEvent];
383        id<MTLSharedEvent> ev = impl_->ev;
384        const uint64_t base = impl_->ev_v;
385        id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
386        size_t i = 0;
387        for (size_t s = 0; s <= cuts.size(); ++s) {
388            const size_t end = s < cuts.size() ? (size_t) cuts[s] : ds.size();
389            id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
390            const size_t first = i;
391            for (; i < end; ++i) {
392                if (i > first && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
393                encode(enc, ds[i]);
394            }
395            [enc endEncoding];
396            if (s < cuts.size()) {
397                [cb encodeSignalEvent:ev value:base + 2 * s + 1];
398                [cb encodeWaitForEvent:ev value:base + 2 * s + 2];
399            }
400        }
401        [cb commit];
402        for (size_t s = 0; s < cuts.size(); ++s) {
403            const uint64_t want = base + 2 * s + 1;
404            while (ev.signaledValue < want) {
405                if (cb.status >= MTLCommandBufferStatusCompleted) break;   // an error: the wait below reports it
406            }
407            at_cut(user, (int) s);
408            ev.signaledValue = base + 2 * s + 2;
409        }
410        impl_->ev_v = base + 2 * cuts.size() + 2;
411        [cb waitUntilCompleted];
412        if (cb.status != MTLCommandBufferStatusCompleted) {
413            std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
414            std::exit(5);
415        }
416        return cb.GPUEndTime - cb.GPUStartTime;
417    }
418}
419
420double Context::run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds) {
421    double gpu = 0;
422    const double t0 = now_s();
423    for (int r = 0; r < reps; ++r) {
424        @autoreleasepool {
425            id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
426            id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
427            for (const auto& d : ds) encode(enc, d);
428            [enc endEncoding];
429            [cb commit];
430            [cb waitUntilCompleted];
431            gpu += cb.GPUEndTime - cb.GPUStartTime;
432        }
433    }
434    if (gpu_seconds) *gpu_seconds = gpu;
435    return now_s() - t0;
436}
437
438void Context::warm(const std::vector<Dispatch>& ds, double seconds) {
439    const double t0 = now_s();
440    while (now_s() - t0 < seconds) run(ds);
441}
442
443double Context::run_icb(const std::vector<Dispatch>& ds, int reps, bool barrier_between) {
444    @autoreleasepool {
445        size_t maxb = 1;
446        for (const auto& d : ds) maxb = std::max(maxb, d.args.size());
447        MTLIndirectCommandBufferDescriptor* desc = [MTLIndirectCommandBufferDescriptor new];
448        desc.commandTypes = MTLIndirectCommandTypeConcurrentDispatch;
449        desc.inheritBuffers = NO;
450        desc.inheritPipelineState = NO;
451        desc.maxKernelBufferBindCount = maxb;
452        id<MTLIndirectCommandBuffer> icb = [impl_->dev newIndirectCommandBufferWithDescriptor:desc
453                                                                              maxCommandCount:ds.size()
454                                                                                      options:0];
455        NSMutableSet* used = [NSMutableSet new];
456        for (size_t i = 0; i < ds.size(); ++i) {
457            const Dispatch& d = ds[i];
458            require_fit(d, "indirect-command dispatch");
459            id<MTLIndirectComputeCommand> c = [icb indirectComputeCommandAtIndex:i];
460            [c setComputePipelineState:P(d.p)];
461            for (size_t a = 0; a < d.args.size(); ++a) {
462                if (!d.args[a].buf) {
463                    std::fprintf(stderr, "mtl: run_icb needs buffer arguments only\n");
464                    std::exit(5);
465                }
466                size_t o;
467                id<MTLBuffer> mb = BO(*d.args[a].buf, d.args[a].off, o);
468                [c setKernelBuffer:mb offset:o atIndex:a];
469                [used addObject:mb];
470            }
471            if (d.tg_mem) [c setThreadgroupMemoryLength:(d.tg_mem + 15) / 16 * 16 atIndex:0];
472            [c concurrentDispatchThreadgroups:MTLSizeMake(d.grid[0], d.grid[1], d.grid[2])
473                        threadsPerThreadgroup:MTLSizeMake(d.tg[0], d.tg[1], d.tg[2])];
474            if (barrier_between) [c setBarrier];
475        }
476        id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
477        id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
478        for (id<MTLBuffer> b in used) [enc useResource:b usage:MTLResourceUsageRead | MTLResourceUsageWrite];
479        for (int r = 0; r < reps; ++r) {
480            [enc executeCommandsInBuffer:icb withRange:NSMakeRange(0, ds.size())];
481            if (barrier_between) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
482        }
483        [enc endEncoding];
484        [cb commit];
485        [cb waitUntilCompleted];
486        if (cb.status != MTLCommandBufferStatusCompleted) {
487            std::fprintf(stderr, "mtl: icb command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
488            std::exit(5);
489        }
490        return cb.GPUEndTime - cb.GPUStartTime;
491    }
492}
493
494}  // namespace mtl