okami.mom/strata

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

Niko1221Merge f-mac-rel (Mac Metal support) into f-144-rel6a74320ca

main
14.2 KiB268 linesraw
1// mtl_probe.cpp - M5 Max checks for the Metal device-interface design (mac-design stream).
2//  1. device facts: unified memory, maxBufferLength, recommendedMaxWorkingSetSize, GPU families
3//  2. MSL compiled at run time (no offline `metal` tool in the Command Line Tools)
4//  3. a hello kernel that takes RAW GPU ADDRESSES in a setBytes struct (the CUDA "void* device pointer" model)
5//  4. gpuAddress vs contents(): are they equal?
6//  5. newBufferWithBytesNoCopy over an mmapped file > 30 GB: alignment, max length, split into chunks, GPU reads it
7// Build: clang++ -std=c++20 -O2 -I metal-cpp mtl_probe.cpp -framework Metal -framework Foundation -framework QuartzCore
8#define NS_PRIVATE_IMPLEMENTATION
9#define MTL_PRIVATE_IMPLEMENTATION
10#include <Foundation/Foundation.hpp>
11#include <Metal/Metal.hpp>
12
13#include <fcntl.h>
14#include <sys/mman.h>
15#include <sys/stat.h>
16#include <unistd.h>
17
18#include <chrono>
19#include <cstdint>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <string>
24#include <vector>
25
26static double now_ms() {
27    return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
28}
29
30static const char* kSrc = R"MSL(
31#include <metal_stdlib>
32using namespace metal;
33struct AxpyArgs { device const float* x; device float* y; float a; uint n; };
34kernel void axpy(constant AxpyArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
35    if (i < p.n) p.y[i] = p.a * p.x[i] + p.y[i];
36}
37// reads one uint32 at each probe offset of a (possibly huge) buffer given by raw GPU address
38struct ProbeArgs { device const uint* base; device const ulong* offs; device uint* out; uint n; };
39kernel void probe(constant ProbeArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
40    if (i < p.n) p.out[i] = p.base[p.offs[i] / 4];
41}
42// streaming read of a buffer range: sum of uint32 (bandwidth through a NoCopy file buffer)
43struct SumArgs { device const uint4* base; device atomic_uint* out; ulong n4; };
44kernel void sum(constant SumArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]], uint g [[threads_per_grid]]) {
45    uint s = 0;
46    for (ulong k = i; k < p.n4; k += g) { uint4 v = p.base[k]; s += v.x ^ v.y ^ v.z ^ v.w; }
47    atomic_fetch_add_explicit(p.out, s, memory_order_relaxed);
48}
49)MSL";
50
51struct AxpyArgs { uint64_t x, y; float a; uint32_t n; };
52struct ProbeArgs { uint64_t base, offs, out; uint32_t n; };
53struct SumArgs { uint64_t base, out; uint64_t n4; };
54
55int main(int argc, char** argv) {
56    NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init();
57    MTL::Device* dev = MTL::CreateSystemDefaultDevice();
58    if (!dev) { std::printf("no Metal device\n"); return 1; }
59    std::printf("device: %s\n", dev->name()->utf8String());
60    std::printf("unified memory: %d\n", (int) dev->hasUnifiedMemory());
61    std::printf("maxBufferLength: %llu (%.2f GiB)\n", (unsigned long long) dev->maxBufferLength(), dev->maxBufferLength() / 1073741824.0);
62    std::printf("recommendedMaxWorkingSetSize: %llu (%.2f GiB)\n", (unsigned long long) dev->recommendedMaxWorkingSetSize(),
63                dev->recommendedMaxWorkingSetSize() / 1073741824.0);
64    std::printf("maxThreadgroupMemoryLength: %llu\n", (unsigned long long) dev->maxThreadgroupMemoryLength());
65    std::printf("families: apple7 %d apple8 %d apple9 %d apple10 %d metal3 %d metal4 %d\n", (int) dev->supportsFamily(MTL::GPUFamilyApple7),
66                (int) dev->supportsFamily(MTL::GPUFamilyApple8), (int) dev->supportsFamily(MTL::GPUFamilyApple9),
67                (int) dev->supportsFamily(MTL::GPUFamilyApple10), (int) dev->supportsFamily(MTL::GPUFamilyMetal3),
68                (int) dev->supportsFamily(MTL::GPUFamilyMetal4));
69    std::printf("page size: %ld\n", sysconf(_SC_PAGESIZE));
70
71    // ---- 2. run-time MSL compile
72    NS::Error* e = nullptr;
73    double t0 = now_ms();
74    MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init();
75    MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), co, &e);
76    if (!lib) { std::printf("MSL compile failed: %s\n", e ? e->localizedDescription()->utf8String() : "?"); return 1; }
77    std::printf("MSL run-time compile: %.1f ms\n", now_ms() - t0);
78    auto pipe = [&](const char* n) {
79        MTL::Function* f = lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding));
80        MTL::ComputePipelineState* p = dev->newComputePipelineState(f, &e);
81        if (!p) { std::printf("pipeline %s failed\n", n); std::exit(1); }
82        return p;
83    };
84    MTL::ComputePipelineState* p_axpy = pipe("axpy");
85    MTL::ComputePipelineState* p_probe = pipe("probe");
86    MTL::ComputePipelineState* p_sum = pipe("sum");
87    MTL::CommandQueue* q = dev->newCommandQueue();
88
89    // ---- 3/4. hello kernel through raw GPU addresses; residency through a residency set
90    const uint32_t N = 1 << 20;
91    MTL::Buffer* bx = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared);
92    MTL::Buffer* by = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared);
93    std::printf("buffer x: contents %p gpuAddress 0x%llx (%s)\n", bx->contents(), (unsigned long long) bx->gpuAddress(),
94                (uint64_t) bx->contents() == bx->gpuAddress() ? "EQUAL" : "different");
95    float* hx = (float*) bx->contents();
96    float* hy = (float*) by->contents();
97    for (uint32_t i = 0; i < N; ++i) { hx[i] = (float) i; hy[i] = 1.0f; }
98    MTL::ResidencySetDescriptor* rd = MTL::ResidencySetDescriptor::alloc()->init();
99    MTL::ResidencySet* rs = dev->newResidencySet(rd, &e);
100    if (!rs) { std::printf("residency set failed\n"); return 1; }
101    rs->addAllocation(bx); rs->addAllocation(by); rs->commit();
102    q->addResidencySet(rs);
103    {
104        AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 2.0f, N};
105        MTL::CommandBuffer* cb = q->commandBuffer();
106        MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
107        enc->setComputePipelineState(p_axpy);
108        enc->setBytes(&a, sizeof a, 0);
109        enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1));
110        enc->endEncoding();
111        cb->commit();
112        cb->waitUntilCompleted();
113        int bad = 0;
114        for (uint32_t i = 0; i < N; ++i) if (hy[i] != 2.0f * i + 1.0f) ++bad;
115        std::printf("hello axpy via raw GPU addresses + residency set: %s (%d bad)\n", bad ? "FAIL" : "OK", bad);
116    }
117    // MTLSharedEvent as the CUDA event: signal from the GPU, poll from the host
118    {
119        MTL::SharedEvent* ev = dev->newSharedEvent();
120        MTL::CommandBuffer* cb = q->commandBuffer();
121        MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
122        AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 1.0f, N};
123        enc->setComputePipelineState(p_axpy);
124        enc->setBytes(&a, sizeof a, 0);
125        enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1));
126        enc->endEncoding();
127        cb->encodeSignalEvent(ev, 1);
128        double ts = now_ms();
129        cb->commit();
130        long spins = 0;
131        while (ev->signaledValue() < 1) ++spins;
132        std::printf("shared event: signalled after %.3f ms, %ld host polls\n", now_ms() - ts, spins);
133        ev->release();
134    }
135    // dispatch cost: 1,000 tiny dispatches in one command buffer (the window-replay cost model)
136    {
137        AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 0.0f, 256};
138        for (int rep = 0; rep < 3; ++rep) {
139            double ts = now_ms();
140            MTL::CommandBuffer* cb = q->commandBufferWithUnretainedReferences();
141            MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
142            for (int k = 0; k < 1000; ++k) {
143                enc->setComputePipelineState(p_axpy);
144                enc->setBytes(&a, sizeof a, 0);
145                enc->dispatchThreads(MTL::Size(256, 1, 1), MTL::Size(256, 1, 1));
146            }
147            enc->endEncoding();
148            const double te = now_ms();
149            cb->commit();
150            cb->waitUntilCompleted();
151            std::printf("1000 dependent tiny dispatches: encode %.3f ms, encode+run %.3f ms\n", te - ts, now_ms() - ts);
152        }
153    }
154
155    // ---- 5. a > 30 GB mmapped file wrapped with newBufferWithBytesNoCopy
156    if (argc < 2) { pool->release(); return 0; }
157    const char* path = argv[1];
158    const int fd = open(path, O_RDONLY);
159    if (fd < 0) { std::printf("open %s failed\n", path); return 1; }
160    struct stat sb; fstat(fd, &sb);
161    const uint64_t fsize = (uint64_t) sb.st_size;
162    const uint64_t pg = (uint64_t) sysconf(_SC_PAGESIZE);
163    const uint64_t mlen = (fsize + pg - 1) / pg * pg;   // NoCopy wants a page-multiple length
164    std::printf("file %s: %.2f GiB\n", path, fsize / 1073741824.0);
165    for (int mode = 0; mode < 2; ++mode) {
166        // mode 0: PROT_READ MAP_SHARED (read-only, what the engine wants); mode 1: PROT_READ|PROT_WRITE MAP_PRIVATE
167        const int prot = mode == 0 ? PROT_READ : (PROT_READ | PROT_WRITE);
168        const int flags = mode == 0 ? MAP_SHARED : MAP_PRIVATE;
169        void* m = mmap(nullptr, mlen, prot, flags, fd, 0);
170        if (m == MAP_FAILED) { std::printf("mmap mode %d failed\n", mode); continue; }
171        std::printf("-- mode %d (%s): mmap at %p (page aligned %d)\n", mode, mode == 0 ? "PROT_READ MAP_SHARED" : "RW MAP_PRIVATE", m,
172                    (int) (((uintptr_t) m % pg) == 0));
173        double ts = now_ms();
174        MTL::Buffer* whole = dev->newBuffer(m, mlen, MTL::ResourceStorageModeShared, nullptr);
175        std::printf("   one NoCopy buffer of %.2f GiB: %s (%.1f ms)\n", mlen / 1073741824.0, whole ? "OK" : "nil", now_ms() - ts);
176        // chunks of at most maxBufferLength / 2 (and a 4 GiB variant: one chunk per few layers)
177        std::vector<MTL::Buffer*> chunks;
178        const uint64_t chunk = argc > 2 ? (std::strtoull(argv[2], nullptr, 10) << 20) : (4ull << 30);
179        ts = now_ms();
180        bool all = true;
181        for (uint64_t off = 0; off < mlen; off += chunk) {
182            const uint64_t len = std::min(chunk, mlen - off);
183            MTL::Buffer* b = dev->newBuffer((char*) m + off, len, MTL::ResourceStorageModeShared, nullptr);
184            if (!b) { all = false; break; }
185            chunks.push_back(b);
186        }
187        std::printf("   %zu NoCopy chunks of %.2f GiB: %s (%.1f ms)\n", chunks.size(), chunk / 1073741824.0, all ? "OK" : "FAILED", now_ms() - ts);
188        // GPU probe reads at 64 offsets spread over the file (the file's pattern: uint32 at offset o equals (o>>12) ^ 0x5a5a5a5a
189        // where written; holes read 0)
190        const uint32_t NP = 64;
191        MTL::Buffer* boffs = dev->newBuffer(NP * 8, MTL::ResourceStorageModeShared);
192        MTL::Buffer* bout = dev->newBuffer(NP * 4, MTL::ResourceStorageModeShared);
193        uint64_t* offs = (uint64_t*) boffs->contents();
194        for (uint32_t i = 0; i < NP; ++i) offs[i] = ((fsize / NP) * i) & ~(uint64_t) 4095;
195        auto run_probe = [&](MTL::Buffer* b, uint64_t base_off, const char* what) {
196            // offsets relative to this buffer's base
197            std::vector<uint64_t> keep(offs, offs + NP);
198            uint32_t n = 0;
199            std::vector<uint32_t> idx;
200            for (uint32_t i = 0; i < NP; ++i)
201                if (keep[i] >= base_off && keep[i] < base_off + b->length()) { offs[n++] = keep[i] - base_off; idx.push_back(i); }
202            MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e);
203            r2->addAllocation(b); r2->addAllocation(boffs); r2->addAllocation(bout); r2->commit();
204            double tr = now_ms();
205            r2->requestResidency();
206            const double treq = now_ms() - tr;
207            ProbeArgs a{b->gpuAddress(), boffs->gpuAddress(), bout->gpuAddress(), n};
208            MTL::CommandBuffer* cb = q->commandBuffer();
209            cb->useResidencySet(r2);
210            MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
211            enc->setComputePipelineState(p_probe);
212            enc->setBytes(&a, sizeof a, 0);
213            enc->dispatchThreads(MTL::Size(n ? n : 1, 1, 1), MTL::Size(64, 1, 1));
214            enc->endEncoding();
215            tr = now_ms();
216            cb->commit();
217            cb->waitUntilCompleted();
218            const double trun = now_ms() - tr;
219            int okc = 0, bad = 0;
220            const uint32_t* out = (const uint32_t*) bout->contents();
221            for (uint32_t k = 0; k < n; ++k) {
222                const uint64_t fo = keep[idx[k]];
223                uint32_t want = 0;
224                pread(fd, &want, 4, (off_t) fo);
225                (out[k] == want ? okc : bad)++;
226            }
227            std::printf("   GPU probe %s: %u reads, %d match pread, %d differ (requestResidency %.1f ms, run %.1f ms, status %d)\n", what, n,
228                        okc, bad, treq, trun, (int) cb->status());
229            for (uint32_t i = 0; i < NP; ++i) offs[i] = keep[i];
230            r2->release();
231        };
232        if (whole) run_probe(whole, 0, "whole buffer");
233        if (all && !chunks.empty()) run_probe(chunks.back(), (chunks.size() - 1) * chunk, "last chunk");
234        // a streaming GPU read over one chunk, cold then warm (page cache)
235        if (all && !chunks.empty()) {
236            MTL::Buffer* b = chunks[chunks.size() / 2];
237            MTL::Buffer* bs = dev->newBuffer(4, MTL::ResourceStorageModeShared);
238            for (int rep = 0; rep < 2; ++rep) {
239                *(uint32_t*) bs->contents() = 0;
240                MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e);
241                r2->addAllocation(b); r2->addAllocation(bs); r2->commit();
242                SumArgs a{b->gpuAddress(), bs->gpuAddress(), b->length() / 16};
243                double tr = now_ms();
244                MTL::CommandBuffer* cb = q->commandBuffer();
245                cb->useResidencySet(r2);
246                MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
247                enc->setComputePipelineState(p_sum);
248                enc->setBytes(&a, sizeof a, 0);
249                enc->dispatchThreads(MTL::Size(40 * 1024, 1, 1), MTL::Size(256, 1, 1));
250                enc->endEncoding();
251                cb->commit();
252                cb->waitUntilCompleted();
253                const double dt = now_ms() - tr;
254                std::printf("   GPU streaming read of a %.2f GiB chunk (%s): %.1f ms = %.1f GB/s\n", b->length() / 1073741824.0,
255                            rep == 0 ? "first touch" : "again", dt, b->length() / dt / 1e6);
256                r2->release();
257            }
258            bs->release();
259        }
260        for (auto* b : chunks) b->release();
261        if (whole) whole->release();
262        boffs->release(); bout->release();
263        munmap(m, mlen);
264    }
265    close(fd);
266    pool->release();
267    return 0;
268}