okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
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 () { 19return 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]]) { 26if (i != 0) return; 27uint it = 0; 28while (atomic_load_explicit(p.flag, memory_order_relaxed) != p.want && it < p.max_iter) ++it; 29p.out[0] = it; 30p.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 () { 39NS ::AutoreleasePool * pool = NS ::AutoreleasePool ::alloc ()-> init (); 40MTL ::Device * dev = MTL ::CreateSystemDefaultDevice (); 41NS ::Error * e = nullptr ; 42MTL ::Library * lib = dev -> newLibrary (NS ::String ::string (kSrc ,NS ::UTF8StringEncoding ),nullptr ,& e ); 43if (!lib ) { std::printf ("compile failed\n" );return 1 ; } 44auto pipe = [& ](const char * n ) {return dev -> newComputePipelineState (lib -> newFunction (NS ::String ::string (n ,NS ::UTF8StringEncoding )),& e ); }; 45MTL ::ComputePipelineState * p_spin = pipe ("spin" ); 46MTL ::ComputePipelineState * p_tick = pipe ("tick" ); 47MTL ::CommandQueue * q = dev -> newCommandQueue (); 48MTL ::Buffer * bf = dev -> newBuffer (16384 ,MTL ::ResourceStorageModeShared ); 49MTL ::Buffer * bo = dev -> newBuffer (16384 ,MTL ::ResourceStorageModeShared ); 50MTL ::ResidencySet * rs = dev -> newResidencySet (MTL ::ResidencySetDescriptor ::alloc ()-> init (),& e ); 51rs -> addAllocation (bf );rs -> addAllocation (bo );rs -> commit ();q -> addResidencySet (rs ); 52volatile uint32_t * flag = (volatile uint32_t * )bf -> contents (); 53uint32_t * out = (uint32_t * )bo -> contents (); 54 55// ---- A: in-kernel spin on a word the CPU writes 5 ms after commit 56for (int rep = 0 ;rep < 3 ;++ rep ) { 57* flag = 0 ;out [0 ]= out [1 ]= 0 ; 58SpinArgs a {bf -> gpuAddress (),bo -> gpuAddress (),7 ,200000000u }; 59MTL ::CommandBuffer * cb = q -> commandBuffer (); 60MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 61enc -> setComputePipelineState (p_spin ); 62enc -> setBytes (& a ,sizeof a ,0 ); 63enc -> dispatchThreads (MTL ::Size (1 ,1 ,1 ),MTL ::Size (1 ,1 ,1 )); 64enc -> endEncoding (); 65const double t0 = now_us (); 66cb -> commit (); 67 std::this_thread::sleep_for (std::chrono::milliseconds (5 )); 68 std::atomic_thread_fence (std::memory_order_seq_cst ); 69* flag = 7 ; 70const double tw = now_us (); 71cb -> 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" , 73out [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 78for (int rep = 0 ;rep < 3 ;++ rep ) { 79const int L = 48 ; 80MTL ::SharedEvent * ev = dev -> newSharedEvent (); 81ev -> setSignaledValue (0 ); 82out [0 ]= 0 ; 83MTL ::CommandBuffer * cb = q -> commandBuffer (); 84TickArgs ta {bo -> gpuAddress ()}; 85for (int l = 0 ;l < L ;++ l ) { 86MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 87enc -> setComputePipelineState (p_tick ); 88enc -> setBytes (& ta ,sizeof ta ,0 ); 89enc -> dispatchThreads (MTL ::Size (1 ,1 ,1 ),MTL ::Size (1 ,1 ,1 )); 90enc -> endEncoding (); 91cb -> encodeSignalEvent (ev ,2 * l + 1 );// "the miss list of layer l is ready" 92cb -> encodeWait (ev ,2 * l + 2 );// "the host has answered layer l" 93 } 94 std::vector < double > rt ; 95const double t0 = now_us (); 96cb -> commit (); 97for (int l = 0 ;l < L ;++ l ) { 98while (ev -> signaledValue ()< (uint64_t ) (2 * l + 1 )) {} 99const double ts = now_us (); 100if (out [0 ]!= (uint32_t ) (l + 1 )) std::printf (" layer %d: host read %u (stale?)\n" ,l ,out [0 ]); 101ev -> setSignaledValue (2 * l + 2 ); 102rt .push_back (ts ); 103 } 104cb -> waitUntilCompleted (); 105const double total = now_us ()- t0 ; 106 std::vector < double > gaps ; 107for (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" , 110L ,total ,gaps [gaps .size () /2 ],gaps .front (),gaps .back (),out [0 ], (int )cb -> status ()); 111ev -> release (); 112 } 113pool -> release (); 114return 0 ; 115}