okami.mom/strata

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

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

main
5.5 KiB115 linesraw
1// mtl_doorbell.cpp - can Strata's doorbell protocol run on Metal?
2//  A. in-kernel spin: a running kernel polls a shared-memory word that the CPU writes later (the CUDA doorbell model)
3//  B. MTLSharedEvent ping-pong: the GPU signals "routing ready" (value 2l+1), the host sees it, does its part, sets
4//     2l+2 from the CPU, and the GPU (encodeWait inside the same, already committed command buffer) goes on.
5//     Measures the round trip per "layer".
6#define NS_PRIVATE_IMPLEMENTATION
7#define MTL_PRIVATE_IMPLEMENTATION
8#include <Foundation/Foundation.hpp>
9#include <Metal/Metal.hpp>
10
11#include <atomic>
12#include <chrono>
13#include <cstdio>
14#include <thread>
15#include <vector>
16#include <algorithm>
17
18static double now_us() {
19    return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count();
20}
21static const char* kSrc = R"MSL(
22#include <metal_stdlib>
23using namespace metal;
24struct SpinArgs { device atomic_uint* flag; device uint* out; uint want; uint max_iter; };
25kernel void spin(constant SpinArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
26    if (i != 0) return;
27    uint it = 0;
28    while (atomic_load_explicit(p.flag, memory_order_relaxed) != p.want && it < p.max_iter) ++it;
29    p.out[0] = it;
30    p.out[1] = atomic_load_explicit(p.flag, memory_order_relaxed);
31}
32struct TickArgs { device uint* x; };
33kernel void tick(constant TickArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { if (i == 0) p.x[0] += 1; }
34)MSL";
35struct SpinArgs { uint64_t flag, out; uint32_t want, max_iter; };
36struct TickArgs { uint64_t x; };
37
38int main() {
39    NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init();
40    MTL::Device* dev = MTL::CreateSystemDefaultDevice();
41    NS::Error* e = nullptr;
42    MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), nullptr, &e);
43    if (!lib) { std::printf("compile failed\n"); return 1; }
44    auto pipe = [&](const char* n) { return dev->newComputePipelineState(lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding)), &e); };
45    MTL::ComputePipelineState* p_spin = pipe("spin");
46    MTL::ComputePipelineState* p_tick = pipe("tick");
47    MTL::CommandQueue* q = dev->newCommandQueue();
48    MTL::Buffer* bf = dev->newBuffer(16384, MTL::ResourceStorageModeShared);
49    MTL::Buffer* bo = dev->newBuffer(16384, MTL::ResourceStorageModeShared);
50    MTL::ResidencySet* rs = dev->newResidencySet(MTL::ResidencySetDescriptor::alloc()->init(), &e);
51    rs->addAllocation(bf); rs->addAllocation(bo); rs->commit(); q->addResidencySet(rs);
52    volatile uint32_t* flag = (volatile uint32_t*) bf->contents();
53    uint32_t* out = (uint32_t*) bo->contents();
54
55    // ---- A: in-kernel spin on a word the CPU writes 5 ms after commit
56    for (int rep = 0; rep < 3; ++rep) {
57        *flag = 0; out[0] = out[1] = 0;
58        SpinArgs a{bf->gpuAddress(), bo->gpuAddress(), 7, 200000000u};
59        MTL::CommandBuffer* cb = q->commandBuffer();
60        MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
61        enc->setComputePipelineState(p_spin);
62        enc->setBytes(&a, sizeof a, 0);
63        enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1));
64        enc->endEncoding();
65        const double t0 = now_us();
66        cb->commit();
67        std::this_thread::sleep_for(std::chrono::milliseconds(5));
68        std::atomic_thread_fence(std::memory_order_seq_cst);
69        *flag = 7;
70        const double tw = now_us();
71        cb->waitUntilCompleted();
72        std::printf("A in-kernel spin: GPU saw the CPU store: %s (iterations %u, flag %u), done %.0f us after the store, status %d\n",
73                    out[1] == 7 ? "YES" : "NO (timed out)", out[0], out[1], now_us() - tw, (int) cb->status());
74        (void) t0;
75    }
76
77    // ---- B: shared-event ping-pong, L "layers" in ONE committed command buffer
78    for (int rep = 0; rep < 3; ++rep) {
79        const int L = 48;
80        MTL::SharedEvent* ev = dev->newSharedEvent();
81        ev->setSignaledValue(0);
82        out[0] = 0;
83        MTL::CommandBuffer* cb = q->commandBuffer();
84        TickArgs ta{bo->gpuAddress()};
85        for (int l = 0; l < L; ++l) {
86            MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
87            enc->setComputePipelineState(p_tick);
88            enc->setBytes(&ta, sizeof ta, 0);
89            enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1));
90            enc->endEncoding();
91            cb->encodeSignalEvent(ev, 2 * l + 1);   // "the miss list of layer l is ready"
92            cb->encodeWait(ev, 2 * l + 2);          // "the host has answered layer l"
93        }
94        std::vector<double> rt;
95        const double t0 = now_us();
96        cb->commit();
97        for (int l = 0; l < L; ++l) {
98            while (ev->signaledValue() < (uint64_t) (2 * l + 1)) {}
99            const double ts = now_us();
100            if (out[0] != (uint32_t) (l + 1)) std::printf("  layer %d: host read %u (stale?)\n", l, out[0]);
101            ev->setSignaledValue(2 * l + 2);
102            rt.push_back(ts);
103        }
104        cb->waitUntilCompleted();
105        const double total = now_us() - t0;
106        std::vector<double> gaps;
107        for (int l = 1; l < L; ++l) gaps.push_back(rt[l] - rt[l - 1]);
108        std::sort(gaps.begin(), gaps.end());
109        std::printf("B shared-event round trip: %d layers in %.0f us, per layer median %.1f us (min %.1f, max %.1f), ticks %u, status %d\n",
110                    L, total, gaps[gaps.size() / 2], gaps.front(), gaps.back(), out[0], (int) cb->status());
111        ev->release();
112    }
113    pool->release();
114    return 0;
115}