okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
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 () { 27return 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]]) { 35if (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]]) { 40if (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]]) { 45uint s = 0; 46for (ulong k = i; k < p.n4; k += g) { uint4 v = p.base[k]; s += v.x ^ v.y ^ v.z ^ v.w; } 47atomic_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 ) { 56NS ::AutoreleasePool * pool = NS ::AutoreleasePool ::alloc ()-> init (); 57MTL ::Device * dev = MTL ::CreateSystemDefaultDevice (); 58if (!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 (), 63dev -> 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 72NS ::Error * e = nullptr ; 73double t0 = now_ms (); 74MTL ::CompileOptions * co = MTL ::CompileOptions ::alloc ()-> init (); 75MTL ::Library * lib = dev -> newLibrary (NS ::String ::string (kSrc ,NS ::UTF8StringEncoding ),co ,& e ); 76if (!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 ); 78auto pipe = [& ](const char * n ) { 79MTL ::Function * f = lib -> newFunction (NS ::String ::string (n ,NS ::UTF8StringEncoding )); 80MTL ::ComputePipelineState * p = dev -> newComputePipelineState (f ,& e ); 81if (!p ) { std::printf ("pipeline %s failed\n" ,n ); std::exit (1 ); } 82return p ; 83 }; 84MTL ::ComputePipelineState * p_axpy = pipe ("axpy" ); 85MTL ::ComputePipelineState * p_probe = pipe ("probe" ); 86MTL ::ComputePipelineState * p_sum = pipe ("sum" ); 87MTL ::CommandQueue * q = dev -> newCommandQueue (); 88 89// ---- 3/4. hello kernel through raw GPU addresses; residency through a residency set 90const uint32_t N = 1 <<20 ; 91MTL ::Buffer * bx = dev -> newBuffer (N * 4 ,MTL ::ResourceStorageModeShared ); 92MTL ::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" ); 95float * hx = (float * )bx -> contents (); 96float * hy = (float * )by -> contents (); 97for (uint32_t i = 0 ;i < N ;++ i ) {hx [i ]= (float )i ;hy [i ]= 1.0f ; } 98MTL ::ResidencySetDescriptor * rd = MTL ::ResidencySetDescriptor ::alloc ()-> init (); 99MTL ::ResidencySet * rs = dev -> newResidencySet (rd ,& e ); 100if (!rs ) { std::printf ("residency set failed\n" );return 1 ; } 101rs -> addAllocation (bx );rs -> addAllocation (by );rs -> commit (); 102q -> addResidencySet (rs ); 103 { 104AxpyArgs a {bx -> gpuAddress (),by -> gpuAddress (),2.0f ,N }; 105MTL ::CommandBuffer * cb = q -> commandBuffer (); 106MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 107enc -> setComputePipelineState (p_axpy ); 108enc -> setBytes (& a ,sizeof a ,0 ); 109enc -> dispatchThreads (MTL ::Size (N ,1 ,1 ),MTL ::Size (256 ,1 ,1 )); 110enc -> endEncoding (); 111cb -> commit (); 112cb -> waitUntilCompleted (); 113int bad = 0 ; 114for (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 { 119MTL ::SharedEvent * ev = dev -> newSharedEvent (); 120MTL ::CommandBuffer * cb = q -> commandBuffer (); 121MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 122AxpyArgs a {bx -> gpuAddress (),by -> gpuAddress (),1.0f ,N }; 123enc -> setComputePipelineState (p_axpy ); 124enc -> setBytes (& a ,sizeof a ,0 ); 125enc -> dispatchThreads (MTL ::Size (N ,1 ,1 ),MTL ::Size (256 ,1 ,1 )); 126enc -> endEncoding (); 127cb -> encodeSignalEvent (ev ,1 ); 128double ts = now_ms (); 129cb -> commit (); 130long spins = 0 ; 131while (ev -> signaledValue ()< 1 )++ spins ; 132 std::printf ("shared event: signalled after %.3f ms, %ld host polls\n" ,now_ms ()- ts ,spins ); 133ev -> release (); 134 } 135// dispatch cost: 1,000 tiny dispatches in one command buffer (the window-replay cost model) 136 { 137AxpyArgs a {bx -> gpuAddress (),by -> gpuAddress (),0.0f ,256 }; 138for (int rep = 0 ;rep < 3 ;++ rep ) { 139double ts = now_ms (); 140MTL ::CommandBuffer * cb = q -> commandBufferWithUnretainedReferences (); 141MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 142for (int k = 0 ;k < 1000 ;++ k ) { 143enc -> setComputePipelineState (p_axpy ); 144enc -> setBytes (& a ,sizeof a ,0 ); 145enc -> dispatchThreads (MTL ::Size (256 ,1 ,1 ),MTL ::Size (256 ,1 ,1 )); 146 } 147enc -> endEncoding (); 148const double te = now_ms (); 149cb -> commit (); 150cb -> 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 156if (argc < 2 ) {pool -> release ();return 0 ; } 157const char * path = argv [1 ]; 158const int fd = open (path ,O_RDONLY ); 159if (fd < 0 ) { std::printf ("open %s failed\n" ,path );return 1 ; } 160struct stat sb ;fstat (fd ,& sb ); 161const uint64_t fsize = (uint64_t )sb .st_size ; 162const uint64_t pg = (uint64_t )sysconf (_SC_PAGESIZE ); 163const 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 ); 165for (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 167const int prot = mode == 0 ?PROT_READ : (PROT_READ |PROT_WRITE ); 168const int flags = mode == 0 ?MAP_SHARED :MAP_PRIVATE ; 169void * m = mmap (nullptr ,mlen ,prot ,flags ,fd ,0 ); 170if (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 )); 173double ts = now_ms (); 174MTL ::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 ; 178const uint64_t chunk = argc > 2 ? (std::strtoull (argv [2 ],nullptr ,10 ) <<20 ) : (4ull <<30 ); 179ts = now_ms (); 180bool all = true; 181for (uint64_t off = 0 ;off < mlen ;off += chunk ) { 182const uint64_t len = std::min (chunk ,mlen - off ); 183MTL ::Buffer * b = dev -> newBuffer ((char * )m + off ,len ,MTL ::ResourceStorageModeShared ,nullptr ); 184if (!b ) {all = false;break ; } 185chunks .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) 190const uint32_t NP = 64 ; 191MTL ::Buffer * boffs = dev -> newBuffer (NP * 8 ,MTL ::ResourceStorageModeShared ); 192MTL ::Buffer * bout = dev -> newBuffer (NP * 4 ,MTL ::ResourceStorageModeShared ); 193uint64_t * offs = (uint64_t * )boffs -> contents (); 194for (uint32_t i = 0 ;i < NP ;++ i )offs [i ]= ((fsize /NP )* i )& ~(uint64_t )4095 ; 195auto 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 ); 198uint32_t n = 0 ; 199 std::vector < uint32_t > idx ; 200for (uint32_t i = 0 ;i < NP ;++ i ) 201if (keep [i ] >=base_off && keep [i ]< base_off + b -> length ()) {offs [n ++ ]= keep [i ]- base_off ;idx .push_back (i ); } 202MTL ::ResidencySet * r2 = dev -> newResidencySet (rd ,& e ); 203r2 -> addAllocation (b );r2 -> addAllocation (boffs );r2 -> addAllocation (bout );r2 -> commit (); 204double tr = now_ms (); 205r2 -> requestResidency (); 206const double treq = now_ms ()- tr ; 207ProbeArgs a {b -> gpuAddress (),boffs -> gpuAddress (),bout -> gpuAddress (),n }; 208MTL ::CommandBuffer * cb = q -> commandBuffer (); 209cb -> useResidencySet (r2 ); 210MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 211enc -> setComputePipelineState (p_probe ); 212enc -> setBytes (& a ,sizeof a ,0 ); 213enc -> dispatchThreads (MTL ::Size (n ?n :1 ,1 ,1 ),MTL ::Size (64 ,1 ,1 )); 214enc -> endEncoding (); 215tr = now_ms (); 216cb -> commit (); 217cb -> waitUntilCompleted (); 218const double trun = now_ms ()- tr ; 219int okc = 0 ,bad = 0 ; 220const uint32_t * out = (const uint32_t * )bout -> contents (); 221for (uint32_t k = 0 ;k < n ;++ k ) { 222const uint64_t fo = keep [idx [k ]]; 223uint32_t want = 0 ; 224pread (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 , 228okc ,bad ,treq ,trun , (int )cb -> status ()); 229for (uint32_t i = 0 ;i < NP ;++ i )offs [i ]= keep [i ]; 230r2 -> release (); 231 }; 232if (whole )run_probe (whole ,0 ,"whole buffer" ); 233if (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) 235if (all && !chunks .empty ()) { 236MTL ::Buffer * b = chunks [chunks .size () /2 ]; 237MTL ::Buffer * bs = dev -> newBuffer (4 ,MTL ::ResourceStorageModeShared ); 238for (int rep = 0 ;rep < 2 ;++ rep ) { 239* (uint32_t * )bs -> contents ()= 0 ; 240MTL ::ResidencySet * r2 = dev -> newResidencySet (rd ,& e ); 241r2 -> addAllocation (b );r2 -> addAllocation (bs );r2 -> commit (); 242SumArgs a {b -> gpuAddress (),bs -> gpuAddress (),b -> length () /16 }; 243double tr = now_ms (); 244MTL ::CommandBuffer * cb = q -> commandBuffer (); 245cb -> useResidencySet (r2 ); 246MTL ::ComputeCommandEncoder * enc = cb -> computeCommandEncoder (); 247enc -> setComputePipelineState (p_sum ); 248enc -> setBytes (& a ,sizeof a ,0 ); 249enc -> dispatchThreads (MTL ::Size (40 * 1024 ,1 ,1 ),MTL ::Size (256 ,1 ,1 )); 250enc -> endEncoding (); 251cb -> commit (); 252cb -> waitUntilCompleted (); 253const 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 , 255rep == 0 ?"first touch" :"again" ,dt ,b -> length () /dt /1e6 ); 256r2 -> release (); 257 } 258bs -> release (); 259 } 260for (auto * b :chunks )b -> release (); 261if (whole )whole -> release (); 262boffs -> release ();bout -> release (); 263munmap (m ,mlen ); 264 } 265close (fd ); 266pool -> release (); 267return 0 ; 268}