okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6a74320ca
main
1// metal/kernels/gridbar.metal - feasibility probe for a persistent kernel: phases separated by an in-kernel grid 2// barrier (a device atomic counter) instead of dispatch boundaries. Metal does not promise that all threadgroups of 3// a grid are resident at once; the probe launches at most one threadgroup per GPU core. 4// 5// Each phase p: every thread streams its share of chunk p (n uint4), and threadgroup g writes a token value 6// (p * 1000 + g) to flag[p][g]; after the barrier, phase p + 1 checks every flag of phase p (written by the OTHER 7// threadgroups) and counts mismatches into bad[0]. 8 9static inline void grid_barrier(device atomic_uint* bar, uint target, ushort tid) { 10 threadgroup_barrier(mem_flags::mem_device); 11#ifdef GB_FENCE 12 atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); 13#endif 14 if (tid == 0) { 15 atomic_fetch_add_explicit(bar, 1u, memory_order_relaxed); 16 while (atomic_load_explicit(bar, memory_order_relaxed) < target) {} 17 } 18 threadgroup_barrier(mem_flags::mem_device); 19#ifdef GB_FENCE 20 atomic_thread_fence(mem_flags::mem_device, memory_order_seq_cst, thread_scope_device); 21#endif 22} 23 24kernel void k_phases(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], 25 device atomic_uint* bar [[buffer(2)]], device volatile uint* flag [[buffer(3)]], 26 device atomic_uint* bad [[buffer(4)]], constant uint& n [[buffer(5)]], 27 constant uint& phases [[buffer(6)]], 28 uint tgpx [[threadgroup_position_in_grid]], uint ntgx [[threadgroups_per_grid]], 29 ushort tid [[thread_index_in_threadgroup]], uint gid [[thread_position_in_grid]], 30 uint nt [[threads_per_grid]]) { 31 const uint g = tgpx, ntg = ntgx; 32 uint4 acc = 0; 33 for (uint p = 0; p < phases; ++p) { 34 if (p > 0 && tid < ntg) { 35 const uint v = flag[(p - 1) * ntg + tid]; 36 if (v != (p - 1) * 1000 + tid) atomic_fetch_add_explicit(bad, 1u, memory_order_relaxed); 37 } 38 device const uint4* s = src + ulong(p) * n; 39 for (uint i = gid; i < n; i += nt) acc += s[i]; 40 if (tid == 0) flag[p * ntg + g] = p * 1000 + g; 41 grid_barrier(bar, (p + 1) * ntg, tid); 42 } 43 out[gid] = acc.x ^ acc.y ^ acc.z ^ acc.w; 44} 45 46// one phase per dispatch, for comparison 47kernel void k_phase1(device const uint4* src [[buffer(0)]], device uint* out [[buffer(1)]], 48 constant uint& n [[buffer(2)]], constant uint& p [[buffer(3)]], 49 uint gid [[thread_position_in_grid]], uint nt [[threads_per_grid]]) { 50 uint4 acc = 0; 51 device const uint4* s = src + ulong(p) * n; 52 for (uint i = gid; i < n; i += nt) acc += s[i]; 53 out[gid] = acc.x ^ acc.y ^ acc.z ^ acc.w; 54}