Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

metal: the Metal runtime behind a CUDA-name compat layer (the HIP model), so the host files build for Metal unchanged

Niko1221bf4b79abda89
diff --git a/metal/CMakeLists.txt b/metal/CMakeLists.txt
new file mode 100644
index 000000000..8b8bd60f4
--- /dev/null
+++ b/metal/CMakeLists.txt
@@ -0,0 +1,45 @@
+# metal/ - the Apple Silicon (Metal) backend, MAC-PLAN.md. Its own CMake project like sycl/, macOS only, never part of
+# the CUDA / HIP / SYCL builds. Host sources are taken from ../src UNCHANGED (the point of Phase 1: shared, not
+# copied): include/metal_compat goes first on the include path and gives them the CUDA runtime names on Metal, as
+# include/strata/hip_compat does on HIP. Only the GPU runtime (src/gpu) and the kernels are Metal's own.
+#
+# cmake -S metal -B build-metal -G Ninja -DMETAL_CPP_DIR=/path/to/metal-cpp && cmake --build build-metal
+# ./build-metal/runtime_hello
+cmake_minimum_required(VERSION 3.24)
+project(strata_metal LANGUAGES CXX)
+
+if(NOT APPLE)
+ message(FATAL_ERROR "metal/ builds on macOS only")
+endif()
+set(CMAKE_CXX_STANDARD 20)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+if(NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE)
+endif()
+
+set(STRATA_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
+set(METAL_CPP_DIR "" CACHE PATH "metal-cpp headers (https://developer.apple.com/metal/cpp/), e.g. metal-cpp_26")
+if(NOT EXISTS "${METAL_CPP_DIR}/Metal/Metal.hpp")
+ message(FATAL_ERROR "METAL_CPP_DIR='${METAL_CPP_DIR}' has no Metal/Metal.hpp")
+endif()
+
+find_library(METAL_FW Metal REQUIRED)
+find_library(FOUNDATION_FW Foundation REQUIRED)
+find_library(QUARTZ_FW QuartzCore REQUIRED)
+
+# the device runtime (include/strata/gpu/runtime.hpp on metal-cpp)
+add_library(strata_gpu_metal STATIC src/gpu/runtime.cpp)
+target_include_directories(strata_gpu_metal BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include/metal_compat
+ ${CMAKE_CURRENT_SOURCE_DIR}/include ${STRATA_ROOT}/include)
+target_include_directories(strata_gpu_metal SYSTEM PUBLIC ${METAL_CPP_DIR})
+target_compile_definitions(strata_gpu_metal PUBLIC STRATA_GPU_METAL=1)
+target_link_libraries(strata_gpu_metal PUBLIC ${METAL_FW} ${FOUNDATION_FW} ${QUARTZ_FW})
+
+# the shared host files built for Metal so far, taken from ../src unchanged
+add_library(strata_core_metal STATIC ${STRATA_ROOT}/src/core/graph.cpp)
+target_link_libraries(strata_core_metal PUBLIC strata_gpu_metal)
+
+add_executable(runtime_hello tests/runtime_hello.cpp)
+target_link_libraries(runtime_hello PRIVATE strata_core_metal)
+enable_testing()
+add_test(NAME runtime_hello COMMAND runtime_hello)
diff --git a/metal/include/metal_compat/cuda_runtime.h b/metal/include/metal_compat/cuda_runtime.h
new file mode 100644
index 000000000..afd72bd35
--- /dev/null
+++ b/metal/include/metal_compat/cuda_runtime.h
@@ -0,0 +1,129 @@
+// metal/include/metal_compat/cuda_runtime.h - the CUDA runtime names the host files use, on Metal.
+//
+// The HIP build's approach (include/strata/hip_compat/cuda_runtime.h maps every cudaX the host code calls to hipX),
+// applied to Metal: this directory goes first on the Metal build's include path, so the shared host files compile for
+// Metal UNCHANGED, and the CUDA / HIP builds never see this file (their objects stay byte-identical by construction).
+// Every name forwards to strata::gpu's Metal implementation (metal/src/gpu/runtime.cpp), whose semantics are the
+// CUDA ones. Only the names in the Phase 1 inventory (phaseA-tests/mac-design.md §1.3) are provided; a host file that
+// uses another one fails to compile on Metal, which is the point.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#include <immintrin.h> // metal_compat/immintrin.h: CUDA's headers bring the x86 one in on a PC
+#include "strata/gpu/runtime.hpp" // metal/include/strata/gpu: the Metal runtime
+
+namespace strata::gpu::compat_detail { inline Error bad() { return kErrorUnsupported; } }
+
+// ---- types and constants
+using cudaError_t = strata::gpu::Error;
+using cudaStream_t = strata::gpu::Stream;
+using cudaEvent_t = strata::gpu::Event;
+using cudaGraph_t = strata::gpu::Graph;
+using cudaGraphExec_t = strata::gpu::GraphExec;
+using cudaGraphNode_t = void*;
+using cudaDeviceProp = strata::gpu::DeviceProp;
+using cudaMemcpyKind = strata::gpu::CopyKind;
+using cudaHostFn_t = strata::gpu::HostFn;
+inline constexpr cudaError_t cudaSuccess = strata::gpu::kSuccess;
+inline constexpr cudaError_t cudaErrorNotReady = strata::gpu::kNotReady;
+inline constexpr cudaError_t cudaErrorMemoryAllocation = strata::gpu::kErrorMemoryAllocation;
+inline constexpr cudaError_t cudaErrorPeerAccessAlreadyEnabled = strata::gpu::kErrorPeerAccessAlreadyEnabled;
+inline constexpr cudaError_t cudaErrorStreamCaptureUnsupported = strata::gpu::kErrorUnsupported;
+inline constexpr cudaMemcpyKind cudaMemcpyHostToDevice = strata::gpu::kHostToDevice;
+inline constexpr cudaMemcpyKind cudaMemcpyDeviceToHost = strata::gpu::kDeviceToHost;
+inline constexpr cudaMemcpyKind cudaMemcpyDeviceToDevice = strata::gpu::kDeviceToDevice;
+inline constexpr cudaMemcpyKind cudaMemcpyDefault = strata::gpu::kCopyDefault;
+inline constexpr unsigned cudaHostAllocDefault = strata::gpu::kHostAllocDefault;
+inline constexpr unsigned cudaHostAllocPortable = strata::gpu::kHostAllocPortable;
+inline constexpr unsigned cudaHostAllocMapped = strata::gpu::kHostAllocMapped;
+inline constexpr unsigned cudaHostRegisterPortable = strata::gpu::kHostRegisterPortable;
+inline constexpr unsigned cudaHostRegisterMapped = strata::gpu::kHostRegisterMapped;
+inline constexpr unsigned cudaHostRegisterReadOnly = strata::gpu::kHostRegisterReadOnly;
+inline constexpr unsigned cudaEventDefault = strata::gpu::kEventDefault;
+inline constexpr unsigned cudaEventDisableTiming = strata::gpu::kEventDisableTiming;
+inline constexpr unsigned cudaEventBlockingSync = strata::gpu::kEventBlockingSync;
+inline constexpr unsigned cudaStreamNonBlocking = strata::gpu::kStreamNonBlocking;
+enum cudaStreamCaptureMode { cudaStreamCaptureModeGlobal = 0, cudaStreamCaptureModeThreadLocal = 1, cudaStreamCaptureModeRelaxed = 2 };
+enum cudaDeviceAttr { cudaDevAttrClockRate = 13, cudaDevAttrMultiProcessorCount = 16, cudaDevAttrIntegrated = 18 };
+
+// ---- errors, devices
+inline cudaError_t cudaGetLastError() { return strata::gpu::get_last_error(); }
+inline cudaError_t cudaPeekAtLastError() { return strata::gpu::peek_last_error(); }
+inline const char* cudaGetErrorString(cudaError_t e) { return strata::gpu::error_string(e); }
+inline cudaError_t cudaGetDevice(int* d) { return strata::gpu::get_device(d); }
+inline cudaError_t cudaSetDevice(int d) { return strata::gpu::set_device(d); }
+inline cudaError_t cudaGetDeviceCount(int* n) { return strata::gpu::device_count(n); }
+inline cudaError_t cudaDeviceSynchronize() { return strata::gpu::device_synchronize(); }
+inline cudaError_t cudaMemGetInfo(size_t* f, size_t* t) { return strata::gpu::mem_get_info(f, t); }
+inline cudaError_t cudaGetDeviceProperties(cudaDeviceProp* p, int d) { return strata::gpu::get_device_properties(p, d); }
+inline cudaError_t cudaRuntimeGetVersion(int* v) { return strata::gpu::runtime_version(v); }
+inline cudaError_t cudaDeviceGetAttribute(int* v, cudaDeviceAttr a, int d) {
+ switch (a) {
+ case cudaDevAttrIntegrated: return strata::gpu::device_integrated(v, d);
+ case cudaDevAttrMultiProcessorCount: return strata::gpu::device_sm_count(v, d);
+ case cudaDevAttrClockRate: return strata::gpu::device_clock_khz(v, d);
+ }
+ return strata::gpu::compat_detail::bad();
+}
+inline cudaError_t cudaDeviceCanAccessPeer(int* v, int d, int p) { return strata::gpu::device_can_access_peer(v, d, p); }
+inline cudaError_t cudaDeviceEnablePeerAccess(int p, unsigned f) { return strata::gpu::device_enable_peer_access(p, f); }
+
+// ---- memory and copies
+template <class T> inline cudaError_t cudaMalloc(T** p, size_t n) { return strata::gpu::malloc_device(p, n); }
+inline cudaError_t cudaFree(void* p) { return strata::gpu::free_device(p); }
+template <class T> inline cudaError_t cudaHostAlloc(T** p, size_t n, unsigned f) { return strata::gpu::host_alloc(p, n, f); }
+template <class T> inline cudaError_t cudaMallocHost(T** p, size_t n) { return strata::gpu::malloc_host(p, n); }
+inline cudaError_t cudaFreeHost(void* p) { return strata::gpu::free_host(p); }
+template <class T> inline cudaError_t cudaHostGetDevicePointer(T** d, void* h, unsigned f) { return strata::gpu::host_device_pointer(d, h, f); }
+inline cudaError_t cudaHostRegister(void* p, size_t n, unsigned f) { return strata::gpu::host_register(p, n, f); }
+inline cudaError_t cudaHostUnregister(void* p) { return strata::gpu::host_unregister(p); }
+inline cudaError_t cudaMemset(void* p, int v, size_t n) { return strata::gpu::memset_device(p, v, n); }
+inline cudaError_t cudaMemsetAsync(void* p, int v, size_t n, cudaStream_t s = nullptr) { return strata::gpu::memset_async(p, v, n, s); }
+inline cudaError_t cudaMemcpy(void* d, const void* s, size_t n, cudaMemcpyKind k) { return strata::gpu::memcpy_sync(d, s, n, k); }
+inline cudaError_t cudaMemcpyAsync(void* d, const void* s, size_t n, cudaMemcpyKind k, cudaStream_t st = nullptr) {
+ return strata::gpu::memcpy_async(d, s, n, k, st);
+}
+inline cudaError_t cudaMemcpy2DAsync(void* d, size_t dp, const void* s, size_t sp, size_t w, size_t h, cudaMemcpyKind k,
+ cudaStream_t st = nullptr) {
+ return strata::gpu::memcpy_2d_async(d, dp, s, sp, w, h, k, st);
+}
+inline cudaError_t cudaMemcpyPeerAsync(void* d, int dd, const void* s, int sd, size_t n, cudaStream_t st = nullptr) {
+ return strata::gpu::memcpy_peer_async(d, dd, s, sd, n, st);
+}
+
+// ---- streams, events, host functions
+inline cudaError_t cudaStreamCreate(cudaStream_t* s) { return strata::gpu::stream_create(s); }
+inline cudaError_t cudaStreamCreateWithFlags(cudaStream_t* s, unsigned f) { return strata::gpu::stream_create(s, f); }
+inline cudaError_t cudaStreamDestroy(cudaStream_t s) { return strata::gpu::stream_destroy(s); }
+inline cudaError_t cudaStreamSynchronize(cudaStream_t s) { return strata::gpu::stream_synchronize(s); }
+inline cudaError_t cudaStreamQuery(cudaStream_t s) { return strata::gpu::stream_query(s); }
+inline cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, unsigned f = 0) { return strata::gpu::stream_wait_event(s, e, f); }
+inline cudaError_t cudaLaunchHostFunc(cudaStream_t s, cudaHostFn_t fn, void* a) { return strata::gpu::launch_host_func(s, fn, a); }
+inline cudaError_t cudaEventCreate(cudaEvent_t* e) { return strata::gpu::event_create(e); }
+inline cudaError_t cudaEventCreateWithFlags(cudaEvent_t* e, unsigned f) { return strata::gpu::event_create(e, f); }
+inline cudaError_t cudaEventDestroy(cudaEvent_t e) { return strata::gpu::event_destroy(e); }
+inline cudaError_t cudaEventRecord(cudaEvent_t e, cudaStream_t s = nullptr) { return strata::gpu::event_record(e, s); }
+inline cudaError_t cudaEventQuery(cudaEvent_t e) { return strata::gpu::event_query(e); }
+inline cudaError_t cudaEventSynchronize(cudaEvent_t e) { return strata::gpu::event_synchronize(e); }
+inline cudaError_t cudaEventElapsedTime(float* ms, cudaEvent_t a, cudaEvent_t b) { return strata::gpu::event_elapsed_ms(ms, a, b); }
+
+// ---- graphs
+inline cudaError_t cudaStreamBeginCapture(cudaStream_t s, cudaStreamCaptureMode m) {
+ return m == cudaStreamCaptureModeThreadLocal ? strata::gpu::begin_capture(s) : strata::gpu::compat_detail::bad();
+}
+inline cudaError_t cudaStreamEndCapture(cudaStream_t s, cudaGraph_t* g) { return strata::gpu::end_capture(s, g); }
+inline cudaError_t cudaGraphGetNodes(cudaGraph_t g, cudaGraphNode_t* nodes, size_t* n) {
+ return nodes == nullptr ? strata::gpu::graph_node_count(g, n) : strata::gpu::compat_detail::bad();
+}
+inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t* x, cudaGraph_t g, cudaGraphNode_t*, char*, size_t) {
+ return strata::gpu::graph_instantiate(x, g);
+}
+inline cudaError_t cudaGraphInstantiate(cudaGraphExec_t* x, cudaGraph_t g, unsigned long long f = 0) {
+ return strata::gpu::graph_instantiate(x, g, f);
+}
+inline cudaError_t cudaGraphLaunch(cudaGraphExec_t x, cudaStream_t s) { return strata::gpu::graph_launch(x, s); }
+inline cudaError_t cudaGraphUpload(cudaGraphExec_t x, cudaStream_t s) { return strata::gpu::graph_upload(x, s); }
+inline cudaError_t cudaGraphDestroy(cudaGraph_t g) { return strata::gpu::graph_destroy(g); }
+inline cudaError_t cudaGraphExecDestroy(cudaGraphExec_t x) { return strata::gpu::graph_exec_destroy(x); }
diff --git a/metal/include/metal_compat/immintrin.h b/metal/include/metal_compat/immintrin.h
new file mode 100644
index 000000000..1f39edddb
--- /dev/null
+++ b/metal/include/metal_compat/immintrin.h
@@ -0,0 +1,5 @@
+// metal/include/metal_compat/immintrin.h - the x86 intrinsics the host loops use, on arm64: the spin-wait hint and
+// the store fence before a host flag is raised (verify.cpp, session.cpp, mtp.cpp, graph.cpp).
+#pragma once
+static inline void _mm_pause() { __asm__ __volatile__("yield"); }
+static inline void _mm_sfence() { __asm__ __volatile__("dmb ishst" ::: "memory"); }
diff --git a/metal/include/strata/gpu/metal.hpp b/metal/include/strata/gpu/metal.hpp
new file mode 100644
index 000000000..4880bdc8c
--- /dev/null
+++ b/metal/include/strata/gpu/metal.hpp
@@ -0,0 +1,44 @@
+// metal/include/strata/gpu/metal.hpp - what the Metal kernel library needs beyond include/strata/gpu/runtime.hpp.
+//
+// The host code never includes this: it sees only runtime.hpp and the strata::kernels::* headers. The Metal
+// implementations of those kernel headers (metal/src/kernels/*) turn their `void* stream` into a gpu::Stream and call
+// dispatch(): encoded now, or recorded when the stream is being captured (the Metal "graph").
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <string>
+
+#include "strata/gpu/runtime.hpp"
+
+namespace MTL {
+class Device;
+class ComputePipelineState;
+} // namespace MTL
+
+namespace strata::gpu::metal {
+
+MTL::Device* device();
+
+/// Compile MSL source at run time (the Command Line Tools have no offline `metal` compiler) and return the pipeline
+/// of `function`. Cached by (source name, function name); nullptr and `err` on failure.
+MTL::ComputePipelineState* pipeline(const char* source_name, const char* source, const char* function, std::string& err);
+
+struct Grid {
+ uint32_t x = 1, y = 1, z = 1;
+};
+
+/// One compute dispatch: `args` (<= 4 KiB, copied now, as a CUDA kernel's arguments are at launch/capture) is bound at
+/// buffer index 0; the kernel reads its device pointers (gpuAddress values) from it. `threadgroups` x `threads`
+/// like a CUDA <<<grid, block, shared>>>. Dispatches on one stream are ordered (each one sees the previous one's
+/// writes), as kernels on one CUDA stream are.
+Error dispatch(Stream s, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid threadgroups, Grid threads,
+ size_t threadgroup_bytes = 0);
+
+/// Counters for tests and the dispatch-cost budget.
+struct Stats {
+ uint64_t dispatches = 0, command_buffers = 0, blits = 0, host_syncs = 0;
+};
+Stats stats();
+
+} // namespace strata::gpu::metal
diff --git a/metal/include/strata/gpu/runtime.hpp b/metal/include/strata/gpu/runtime.hpp
new file mode 100644
index 000000000..7791dc4ad
--- /dev/null
+++ b/metal/include/strata/gpu/runtime.hpp
@@ -0,0 +1,126 @@
+// metal/include/strata/gpu/runtime.hpp - the device runtime of the Metal build (MAC-PLAN Phase 1, compat design).
+//
+// The shared host files keep calling the CUDA runtime names; on Metal those names come from
+// metal/include/metal_compat/cuda_runtime.h (first on the include path, as include/strata/hip_compat is on HIP), which
+// forwards every one to the functions declared here. metal/src/gpu/runtime.cpp implements them on metal-cpp:
+// - a device pointer is the MTLBuffer's gpuAddress (the host never dereferences it; kernels take it from their
+// argument struct); host_alloc returns contents() and host_device_pointer maps it to its gpuAddress; every buffer is
+// in one residency set;
+// - a Stream is a command queue + the open command buffer / compute encoder + a shared-event timeline; an Event is a
+// (shared event, value) pair;
+// - begin_capture / end_capture / graph_launch record the stream's dispatches and re-encode them per launch (the CUDA
+// graph rule "per-step values live in device buffers, not in arguments" holds here too);
+// - caps().unified_memory is true and host_view(device_pointer) is the CPU address of a device allocation.
+// The CUDA and HIP builds never include this directory.
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+// The signatures and the meaning of each call are those of the CUDA runtime call of the same purpose.
+
+namespace strata::gpu {
+
+enum Error : int { kSuccess = 0, kNotReady = 600, kErrorInvalidValue = 1, kErrorMemoryAllocation = 2, kErrorUnsupported = 801,
+ kErrorLaunchFailure = 719 };
+struct StreamImpl;
+struct EventImpl;
+struct GraphImpl;
+struct GraphExecImpl;
+using Stream = StreamImpl*; // nullptr = the default (legacy) stream, as on CUDA
+using Event = EventImpl*;
+using Graph = GraphImpl*;
+using GraphExec = GraphExecImpl*;
+enum CopyKind : int { kHostToHost = 0, kHostToDevice = 1, kDeviceToHost = 2, kDeviceToDevice = 3, kCopyDefault = 4 };
+using HostFn = void (*)(void*);
+struct DeviceProp { // the fields the host code reads
+ char name[256] = {};
+ char gcnArchName[256] = {};
+ int major = 0, minor = 0, warpSize = 32, multiProcessorCount = 0;
+ size_t totalGlobalMem = 0;
+};
+
+inline constexpr unsigned kHostAllocDefault = 0;
+inline constexpr unsigned kHostAllocPortable = 1;
+inline constexpr unsigned kHostAllocMapped = 2;
+inline constexpr unsigned kHostRegisterPortable = 1;
+inline constexpr unsigned kHostRegisterMapped = 2;
+inline constexpr unsigned kHostRegisterReadOnly = 8;
+inline constexpr unsigned kEventDefault = 0;
+inline constexpr unsigned kEventBlockingSync = 1;
+inline constexpr unsigned kEventDisableTiming = 2;
+inline constexpr unsigned kStreamNonBlocking = 1;
+
+struct Caps {
+ bool unified_memory = true;
+};
+inline Caps caps() { return Caps{}; }
+void* host_view(const void* device_pointer);
+
+Error get_last_error();
+Error peek_last_error();
+const char* error_string(Error e);
+
+Error get_device(int* dev);
+Error set_device(int dev);
+Error device_count(int* n);
+Error device_synchronize();
+Error mem_get_info(size_t* free_b, size_t* total_b);
+Error get_device_properties(DeviceProp* p, int dev);
+Error device_integrated(int* v, int dev);
+Error device_sm_count(int* v, int dev);
+Error device_clock_khz(int* v, int dev);
+Error runtime_version(int* v);
+Error device_can_access_peer(int* v, int dev, int peer);
+Error device_enable_peer_access(int peer, unsigned flags);
+inline constexpr Error kErrorPeerAccessAlreadyEnabled = Error(704);
+
+Error malloc_device_raw(void** p, size_t bytes);
+template <class T> inline Error malloc_device(T** p, size_t bytes) { return malloc_device_raw((void**) (void*) p, bytes); }
+Error free_device(void* p);
+Error host_alloc_raw(void** p, size_t bytes, unsigned flags);
+template <class T> inline Error host_alloc(T** p, size_t bytes, unsigned flags) { return host_alloc_raw((void**) (void*) p, bytes, flags); }
+Error free_host(void* p);
+template <class T> inline Error malloc_host(T** p, size_t bytes) { return host_alloc_raw((void**) (void*) p, bytes, 0); }
+Error host_device_pointer_raw(void** dev, void* host);
+template <class T> inline Error host_device_pointer(T** dev, void* host, unsigned = 0) {
+ return host_device_pointer_raw((void**) (void*) dev, host);
+}
+Error host_register(void* p, size_t bytes, unsigned flags);
+Error host_unregister(void* p);
+Error memset_device(void* p, int value, size_t bytes);
+Error memset_async(void* p, int value, size_t bytes, Stream s = nullptr);
+
+Error memcpy_sync(void* dst, const void* src, size_t bytes, CopyKind k);
+Error memcpy_async(void* dst, const void* src, size_t bytes, CopyKind k, Stream s = nullptr);
+Error memcpy_2d_async(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, CopyKind k,
+ Stream s = nullptr);
+Error memcpy_peer_async(void* dst, int dst_dev, const void* src, int src_dev, size_t bytes, Stream s = nullptr);
+
+Error stream_create(Stream* s, unsigned flags);
+inline Error stream_create(Stream* s) { return stream_create(s, 0); }
+Error stream_destroy(Stream s);
+Error stream_synchronize(Stream s);
+Error stream_query(Stream s);
+Error stream_wait_event(Stream s, Event e, unsigned flags = 0);
+Error launch_host_func(Stream s, HostFn fn, void* arg);
+
+Error event_create(Event* e, unsigned flags);
+inline Error event_create(Event* e) { return event_create(e, 0); }
+Error event_destroy(Event e);
+Error event_record(Event e, Stream s = nullptr);
+Error event_query(Event e);
+Error event_synchronize(Event e);
+Error event_elapsed_ms(float* ms, Event a, Event b);
+
+Error begin_capture(Stream s);
+Error end_capture(Stream s, Graph* g);
+Error graph_node_count(Graph g, size_t* n);
+Error graph_instantiate(GraphExec* x, Graph g);
+inline Error graph_instantiate(GraphExec* x, Graph g, unsigned long long) { return graph_instantiate(x, g); }
+Error graph_launch(GraphExec x, Stream s);
+Error graph_upload(GraphExec x, Stream s);
+Error graph_destroy(Graph g);
+Error graph_exec_destroy(GraphExec x);
+
+} // namespace strata::gpu
diff --git a/metal/probe/mkfile.c b/metal/probe/mkfile.c
new file mode 100644
index 000000000..068aadbd9
--- /dev/null
+++ b/metal/probe/mkfile.c
@@ -0,0 +1,23 @@
+// mkfile.c - write a dense test file of N GiB with F_NOCACHE (so it is not left in the page cache):
+// the first uint32 of every 4 KiB is (offset >> 12) ^ 0x5a5a5a5a, the rest is a cheap pattern.
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+int main(int argc, char** argv) {
+ if (argc < 3) return 1;
+ const uint64_t gib = strtoull(argv[2], 0, 10);
+ int fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
+ if (fd < 0) return 2;
+ fcntl(fd, F_NOCACHE, 1);
+ const size_t B = 64u << 20;
+ uint32_t* buf = aligned_alloc(16384, B);
+ for (uint64_t off = 0; off < (gib << 30); off += B) {
+ for (size_t i = 0; i < B / 4; ++i) buf[i] = (uint32_t) (i * 2654435761u);
+ for (size_t p = 0; p < B; p += 4096) buf[p / 4] = (uint32_t) ((off + p) >> 12) ^ 0x5a5a5a5au;
+ if (write(fd, buf, B) != (ssize_t) B) return 3;
+ }
+ close(fd);
+ return 0;
+}
diff --git a/metal/probe/mtl_doorbell.cpp b/metal/probe/mtl_doorbell.cpp
new file mode 100644
index 000000000..20baf0d87
--- /dev/null
+++ b/metal/probe/mtl_doorbell.cpp
@@ -0,0 +1,115 @@
+// mtl_doorbell.cpp - can Strata's doorbell protocol run on Metal?
+// A. in-kernel spin: a running kernel polls a shared-memory word that the CPU writes later (the CUDA doorbell model)
+// B. MTLSharedEvent ping-pong: the GPU signals "routing ready" (value 2l+1), the host sees it, does its part, sets
+// 2l+2 from the CPU, and the GPU (encodeWait inside the same, already committed command buffer) goes on.
+// Measures the round trip per "layer".
+#define NS_PRIVATE_IMPLEMENTATION
+#define MTL_PRIVATE_IMPLEMENTATION
+#include <Foundation/Foundation.hpp>
+#include <Metal/Metal.hpp>
+
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <thread>
+#include <vector>
+#include <algorithm>
+
+static double now_us() {
+ return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+static const char* kSrc = R"MSL(
+#include <metal_stdlib>
+using namespace metal;
+struct SpinArgs { device atomic_uint* flag; device uint* out; uint want; uint max_iter; };
+kernel void spin(constant SpinArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ if (i != 0) return;
+ uint it = 0;
+ while (atomic_load_explicit(p.flag, memory_order_relaxed) != p.want && it < p.max_iter) ++it;
+ p.out[0] = it;
+ p.out[1] = atomic_load_explicit(p.flag, memory_order_relaxed);
+}
+struct TickArgs { device uint* x; };
+kernel void tick(constant TickArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) { if (i == 0) p.x[0] += 1; }
+)MSL";
+struct SpinArgs { uint64_t flag, out; uint32_t want, max_iter; };
+struct TickArgs { uint64_t x; };
+
+int main() {
+ NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init();
+ MTL::Device* dev = MTL::CreateSystemDefaultDevice();
+ NS::Error* e = nullptr;
+ MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), nullptr, &e);
+ if (!lib) { std::printf("compile failed\n"); return 1; }
+ auto pipe = [&](const char* n) { return dev->newComputePipelineState(lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding)), &e); };
+ MTL::ComputePipelineState* p_spin = pipe("spin");
+ MTL::ComputePipelineState* p_tick = pipe("tick");
+ MTL::CommandQueue* q = dev->newCommandQueue();
+ MTL::Buffer* bf = dev->newBuffer(16384, MTL::ResourceStorageModeShared);
+ MTL::Buffer* bo = dev->newBuffer(16384, MTL::ResourceStorageModeShared);
+ MTL::ResidencySet* rs = dev->newResidencySet(MTL::ResidencySetDescriptor::alloc()->init(), &e);
+ rs->addAllocation(bf); rs->addAllocation(bo); rs->commit(); q->addResidencySet(rs);
+ volatile uint32_t* flag = (volatile uint32_t*) bf->contents();
+ uint32_t* out = (uint32_t*) bo->contents();
+
+ // ---- A: in-kernel spin on a word the CPU writes 5 ms after commit
+ for (int rep = 0; rep < 3; ++rep) {
+ *flag = 0; out[0] = out[1] = 0;
+ SpinArgs a{bf->gpuAddress(), bo->gpuAddress(), 7, 200000000u};
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ enc->setComputePipelineState(p_spin);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1));
+ enc->endEncoding();
+ const double t0 = now_us();
+ cb->commit();
+ std::this_thread::sleep_for(std::chrono::milliseconds(5));
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+ *flag = 7;
+ const double tw = now_us();
+ cb->waitUntilCompleted();
+ 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",
+ out[1] == 7 ? "YES" : "NO (timed out)", out[0], out[1], now_us() - tw, (int) cb->status());
+ (void) t0;
+ }
+
+ // ---- B: shared-event ping-pong, L "layers" in ONE committed command buffer
+ for (int rep = 0; rep < 3; ++rep) {
+ const int L = 48;
+ MTL::SharedEvent* ev = dev->newSharedEvent();
+ ev->setSignaledValue(0);
+ out[0] = 0;
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ TickArgs ta{bo->gpuAddress()};
+ for (int l = 0; l < L; ++l) {
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ enc->setComputePipelineState(p_tick);
+ enc->setBytes(&ta, sizeof ta, 0);
+ enc->dispatchThreads(MTL::Size(1, 1, 1), MTL::Size(1, 1, 1));
+ enc->endEncoding();
+ cb->encodeSignalEvent(ev, 2 * l + 1); // "the miss list of layer l is ready"
+ cb->encodeWait(ev, 2 * l + 2); // "the host has answered layer l"
+ }
+ std::vector<double> rt;
+ const double t0 = now_us();
+ cb->commit();
+ for (int l = 0; l < L; ++l) {
+ while (ev->signaledValue() < (uint64_t) (2 * l + 1)) {}
+ const double ts = now_us();
+ if (out[0] != (uint32_t) (l + 1)) std::printf(" layer %d: host read %u (stale?)\n", l, out[0]);
+ ev->setSignaledValue(2 * l + 2);
+ rt.push_back(ts);
+ }
+ cb->waitUntilCompleted();
+ const double total = now_us() - t0;
+ std::vector<double> gaps;
+ for (int l = 1; l < L; ++l) gaps.push_back(rt[l] - rt[l - 1]);
+ std::sort(gaps.begin(), gaps.end());
+ 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",
+ L, total, gaps[gaps.size() / 2], gaps.front(), gaps.back(), out[0], (int) cb->status());
+ ev->release();
+ }
+ pool->release();
+ return 0;
+}
diff --git a/metal/probe/mtl_probe.cpp b/metal/probe/mtl_probe.cpp
new file mode 100644
index 000000000..d1e0a3353
--- /dev/null
+++ b/metal/probe/mtl_probe.cpp
@@ -0,0 +1,268 @@
+// mtl_probe.cpp - M5 Max checks for the Metal device-interface design (mac-design stream).
+// 1. device facts: unified memory, maxBufferLength, recommendedMaxWorkingSetSize, GPU families
+// 2. MSL compiled at run time (no offline `metal` tool in the Command Line Tools)
+// 3. a hello kernel that takes RAW GPU ADDRESSES in a setBytes struct (the CUDA "void* device pointer" model)
+// 4. gpuAddress vs contents(): are they equal?
+// 5. newBufferWithBytesNoCopy over an mmapped file > 30 GB: alignment, max length, split into chunks, GPU reads it
+// Build: clang++ -std=c++20 -O2 -I metal-cpp mtl_probe.cpp -framework Metal -framework Foundation -framework QuartzCore
+#define NS_PRIVATE_IMPLEMENTATION
+#define MTL_PRIVATE_IMPLEMENTATION
+#include <Foundation/Foundation.hpp>
+#include <Metal/Metal.hpp>
+
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <chrono>
+#include <cstdint>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <vector>
+
+static double now_ms() {
+ return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+static const char* kSrc = R"MSL(
+#include <metal_stdlib>
+using namespace metal;
+struct AxpyArgs { device const float* x; device float* y; float a; uint n; };
+kernel void axpy(constant AxpyArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ if (i < p.n) p.y[i] = p.a * p.x[i] + p.y[i];
+}
+// reads one uint32 at each probe offset of a (possibly huge) buffer given by raw GPU address
+struct ProbeArgs { device const uint* base; device const ulong* offs; device uint* out; uint n; };
+kernel void probe(constant ProbeArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ if (i < p.n) p.out[i] = p.base[p.offs[i] / 4];
+}
+// streaming read of a buffer range: sum of uint32 (bandwidth through a NoCopy file buffer)
+struct SumArgs { device const uint4* base; device atomic_uint* out; ulong n4; };
+kernel void sum(constant SumArgs& p [[buffer(0)]], uint i [[thread_position_in_grid]], uint g [[threads_per_grid]]) {
+ uint s = 0;
+ for (ulong k = i; k < p.n4; k += g) { uint4 v = p.base[k]; s += v.x ^ v.y ^ v.z ^ v.w; }
+ atomic_fetch_add_explicit(p.out, s, memory_order_relaxed);
+}
+)MSL";
+
+struct AxpyArgs { uint64_t x, y; float a; uint32_t n; };
+struct ProbeArgs { uint64_t base, offs, out; uint32_t n; };
+struct SumArgs { uint64_t base, out; uint64_t n4; };
+
+int main(int argc, char** argv) {
+ NS::AutoreleasePool* pool = NS::AutoreleasePool::alloc()->init();
+ MTL::Device* dev = MTL::CreateSystemDefaultDevice();
+ if (!dev) { std::printf("no Metal device\n"); return 1; }
+ std::printf("device: %s\n", dev->name()->utf8String());
+ std::printf("unified memory: %d\n", (int) dev->hasUnifiedMemory());
+ std::printf("maxBufferLength: %llu (%.2f GiB)\n", (unsigned long long) dev->maxBufferLength(), dev->maxBufferLength() / 1073741824.0);
+ std::printf("recommendedMaxWorkingSetSize: %llu (%.2f GiB)\n", (unsigned long long) dev->recommendedMaxWorkingSetSize(),
+ dev->recommendedMaxWorkingSetSize() / 1073741824.0);
+ std::printf("maxThreadgroupMemoryLength: %llu\n", (unsigned long long) dev->maxThreadgroupMemoryLength());
+ std::printf("families: apple7 %d apple8 %d apple9 %d apple10 %d metal3 %d metal4 %d\n", (int) dev->supportsFamily(MTL::GPUFamilyApple7),
+ (int) dev->supportsFamily(MTL::GPUFamilyApple8), (int) dev->supportsFamily(MTL::GPUFamilyApple9),
+ (int) dev->supportsFamily(MTL::GPUFamilyApple10), (int) dev->supportsFamily(MTL::GPUFamilyMetal3),
+ (int) dev->supportsFamily(MTL::GPUFamilyMetal4));
+ std::printf("page size: %ld\n", sysconf(_SC_PAGESIZE));
+
+ // ---- 2. run-time MSL compile
+ NS::Error* e = nullptr;
+ double t0 = now_ms();
+ MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init();
+ MTL::Library* lib = dev->newLibrary(NS::String::string(kSrc, NS::UTF8StringEncoding), co, &e);
+ if (!lib) { std::printf("MSL compile failed: %s\n", e ? e->localizedDescription()->utf8String() : "?"); return 1; }
+ std::printf("MSL run-time compile: %.1f ms\n", now_ms() - t0);
+ auto pipe = [&](const char* n) {
+ MTL::Function* f = lib->newFunction(NS::String::string(n, NS::UTF8StringEncoding));
+ MTL::ComputePipelineState* p = dev->newComputePipelineState(f, &e);
+ if (!p) { std::printf("pipeline %s failed\n", n); std::exit(1); }
+ return p;
+ };
+ MTL::ComputePipelineState* p_axpy = pipe("axpy");
+ MTL::ComputePipelineState* p_probe = pipe("probe");
+ MTL::ComputePipelineState* p_sum = pipe("sum");
+ MTL::CommandQueue* q = dev->newCommandQueue();
+
+ // ---- 3/4. hello kernel through raw GPU addresses; residency through a residency set
+ const uint32_t N = 1 << 20;
+ MTL::Buffer* bx = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared);
+ MTL::Buffer* by = dev->newBuffer(N * 4, MTL::ResourceStorageModeShared);
+ std::printf("buffer x: contents %p gpuAddress 0x%llx (%s)\n", bx->contents(), (unsigned long long) bx->gpuAddress(),
+ (uint64_t) bx->contents() == bx->gpuAddress() ? "EQUAL" : "different");
+ float* hx = (float*) bx->contents();
+ float* hy = (float*) by->contents();
+ for (uint32_t i = 0; i < N; ++i) { hx[i] = (float) i; hy[i] = 1.0f; }
+ MTL::ResidencySetDescriptor* rd = MTL::ResidencySetDescriptor::alloc()->init();
+ MTL::ResidencySet* rs = dev->newResidencySet(rd, &e);
+ if (!rs) { std::printf("residency set failed\n"); return 1; }
+ rs->addAllocation(bx); rs->addAllocation(by); rs->commit();
+ q->addResidencySet(rs);
+ {
+ AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 2.0f, N};
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ enc->setComputePipelineState(p_axpy);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1));
+ enc->endEncoding();
+ cb->commit();
+ cb->waitUntilCompleted();
+ int bad = 0;
+ for (uint32_t i = 0; i < N; ++i) if (hy[i] != 2.0f * i + 1.0f) ++bad;
+ std::printf("hello axpy via raw GPU addresses + residency set: %s (%d bad)\n", bad ? "FAIL" : "OK", bad);
+ }
+ // MTLSharedEvent as the CUDA event: signal from the GPU, poll from the host
+ {
+ MTL::SharedEvent* ev = dev->newSharedEvent();
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 1.0f, N};
+ enc->setComputePipelineState(p_axpy);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(N, 1, 1), MTL::Size(256, 1, 1));
+ enc->endEncoding();
+ cb->encodeSignalEvent(ev, 1);
+ double ts = now_ms();
+ cb->commit();
+ long spins = 0;
+ while (ev->signaledValue() < 1) ++spins;
+ std::printf("shared event: signalled after %.3f ms, %ld host polls\n", now_ms() - ts, spins);
+ ev->release();
+ }
+ // dispatch cost: 1,000 tiny dispatches in one command buffer (the window-replay cost model)
+ {
+ AxpyArgs a{bx->gpuAddress(), by->gpuAddress(), 0.0f, 256};
+ for (int rep = 0; rep < 3; ++rep) {
+ double ts = now_ms();
+ MTL::CommandBuffer* cb = q->commandBufferWithUnretainedReferences();
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ for (int k = 0; k < 1000; ++k) {
+ enc->setComputePipelineState(p_axpy);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(256, 1, 1), MTL::Size(256, 1, 1));
+ }
+ enc->endEncoding();
+ const double te = now_ms();
+ cb->commit();
+ cb->waitUntilCompleted();
+ std::printf("1000 dependent tiny dispatches: encode %.3f ms, encode+run %.3f ms\n", te - ts, now_ms() - ts);
+ }
+ }
+
+ // ---- 5. a > 30 GB mmapped file wrapped with newBufferWithBytesNoCopy
+ if (argc < 2) { pool->release(); return 0; }
+ const char* path = argv[1];
+ const int fd = open(path, O_RDONLY);
+ if (fd < 0) { std::printf("open %s failed\n", path); return 1; }
+ struct stat sb; fstat(fd, &sb);
+ const uint64_t fsize = (uint64_t) sb.st_size;
+ const uint64_t pg = (uint64_t) sysconf(_SC_PAGESIZE);
+ const uint64_t mlen = (fsize + pg - 1) / pg * pg; // NoCopy wants a page-multiple length
+ std::printf("file %s: %.2f GiB\n", path, fsize / 1073741824.0);
+ for (int mode = 0; mode < 2; ++mode) {
+ // mode 0: PROT_READ MAP_SHARED (read-only, what the engine wants); mode 1: PROT_READ|PROT_WRITE MAP_PRIVATE
+ const int prot = mode == 0 ? PROT_READ : (PROT_READ | PROT_WRITE);
+ const int flags = mode == 0 ? MAP_SHARED : MAP_PRIVATE;
+ void* m = mmap(nullptr, mlen, prot, flags, fd, 0);
+ if (m == MAP_FAILED) { std::printf("mmap mode %d failed\n", mode); continue; }
+ std::printf("-- mode %d (%s): mmap at %p (page aligned %d)\n", mode, mode == 0 ? "PROT_READ MAP_SHARED" : "RW MAP_PRIVATE", m,
+ (int) (((uintptr_t) m % pg) == 0));
+ double ts = now_ms();
+ MTL::Buffer* whole = dev->newBuffer(m, mlen, MTL::ResourceStorageModeShared, nullptr);
+ std::printf(" one NoCopy buffer of %.2f GiB: %s (%.1f ms)\n", mlen / 1073741824.0, whole ? "OK" : "nil", now_ms() - ts);
+ // chunks of at most maxBufferLength / 2 (and a 4 GiB variant: one chunk per few layers)
+ std::vector<MTL::Buffer*> chunks;
+ const uint64_t chunk = argc > 2 ? (std::strtoull(argv[2], nullptr, 10) << 20) : (4ull << 30);
+ ts = now_ms();
+ bool all = true;
+ for (uint64_t off = 0; off < mlen; off += chunk) {
+ const uint64_t len = std::min(chunk, mlen - off);
+ MTL::Buffer* b = dev->newBuffer((char*) m + off, len, MTL::ResourceStorageModeShared, nullptr);
+ if (!b) { all = false; break; }
+ chunks.push_back(b);
+ }
+ std::printf(" %zu NoCopy chunks of %.2f GiB: %s (%.1f ms)\n", chunks.size(), chunk / 1073741824.0, all ? "OK" : "FAILED", now_ms() - ts);
+ // GPU probe reads at 64 offsets spread over the file (the file's pattern: uint32 at offset o equals (o>>12) ^ 0x5a5a5a5a
+ // where written; holes read 0)
+ const uint32_t NP = 64;
+ MTL::Buffer* boffs = dev->newBuffer(NP * 8, MTL::ResourceStorageModeShared);
+ MTL::Buffer* bout = dev->newBuffer(NP * 4, MTL::ResourceStorageModeShared);
+ uint64_t* offs = (uint64_t*) boffs->contents();
+ for (uint32_t i = 0; i < NP; ++i) offs[i] = ((fsize / NP) * i) & ~(uint64_t) 4095;
+ auto run_probe = [&](MTL::Buffer* b, uint64_t base_off, const char* what) {
+ // offsets relative to this buffer's base
+ std::vector<uint64_t> keep(offs, offs + NP);
+ uint32_t n = 0;
+ std::vector<uint32_t> idx;
+ for (uint32_t i = 0; i < NP; ++i)
+ if (keep[i] >= base_off && keep[i] < base_off + b->length()) { offs[n++] = keep[i] - base_off; idx.push_back(i); }
+ MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e);
+ r2->addAllocation(b); r2->addAllocation(boffs); r2->addAllocation(bout); r2->commit();
+ double tr = now_ms();
+ r2->requestResidency();
+ const double treq = now_ms() - tr;
+ ProbeArgs a{b->gpuAddress(), boffs->gpuAddress(), bout->gpuAddress(), n};
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ cb->useResidencySet(r2);
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ enc->setComputePipelineState(p_probe);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(n ? n : 1, 1, 1), MTL::Size(64, 1, 1));
+ enc->endEncoding();
+ tr = now_ms();
+ cb->commit();
+ cb->waitUntilCompleted();
+ const double trun = now_ms() - tr;
+ int okc = 0, bad = 0;
+ const uint32_t* out = (const uint32_t*) bout->contents();
+ for (uint32_t k = 0; k < n; ++k) {
+ const uint64_t fo = keep[idx[k]];
+ uint32_t want = 0;
+ pread(fd, &want, 4, (off_t) fo);
+ (out[k] == want ? okc : bad)++;
+ }
+ std::printf(" GPU probe %s: %u reads, %d match pread, %d differ (requestResidency %.1f ms, run %.1f ms, status %d)\n", what, n,
+ okc, bad, treq, trun, (int) cb->status());
+ for (uint32_t i = 0; i < NP; ++i) offs[i] = keep[i];
+ r2->release();
+ };
+ if (whole) run_probe(whole, 0, "whole buffer");
+ if (all && !chunks.empty()) run_probe(chunks.back(), (chunks.size() - 1) * chunk, "last chunk");
+ // a streaming GPU read over one chunk, cold then warm (page cache)
+ if (all && !chunks.empty()) {
+ MTL::Buffer* b = chunks[chunks.size() / 2];
+ MTL::Buffer* bs = dev->newBuffer(4, MTL::ResourceStorageModeShared);
+ for (int rep = 0; rep < 2; ++rep) {
+ *(uint32_t*) bs->contents() = 0;
+ MTL::ResidencySet* r2 = dev->newResidencySet(rd, &e);
+ r2->addAllocation(b); r2->addAllocation(bs); r2->commit();
+ SumArgs a{b->gpuAddress(), bs->gpuAddress(), b->length() / 16};
+ double tr = now_ms();
+ MTL::CommandBuffer* cb = q->commandBuffer();
+ cb->useResidencySet(r2);
+ MTL::ComputeCommandEncoder* enc = cb->computeCommandEncoder();
+ enc->setComputePipelineState(p_sum);
+ enc->setBytes(&a, sizeof a, 0);
+ enc->dispatchThreads(MTL::Size(40 * 1024, 1, 1), MTL::Size(256, 1, 1));
+ enc->endEncoding();
+ cb->commit();
+ cb->waitUntilCompleted();
+ const double dt = now_ms() - tr;
+ std::printf(" GPU streaming read of a %.2f GiB chunk (%s): %.1f ms = %.1f GB/s\n", b->length() / 1073741824.0,
+ rep == 0 ? "first touch" : "again", dt, b->length() / dt / 1e6);
+ r2->release();
+ }
+ bs->release();
+ }
+ for (auto* b : chunks) b->release();
+ if (whole) whole->release();
+ boffs->release(); bout->release();
+ munmap(m, mlen);
+ }
+ close(fd);
+ pool->release();
+ return 0;
+}
diff --git a/metal/src/gpu/runtime.cpp b/metal/src/gpu/runtime.cpp
new file mode 100644
index 000000000..3b8d158e6
--- /dev/null
+++ b/metal/src/gpu/runtime.cpp
@@ -0,0 +1,573 @@
+// metal/src/gpu/runtime.cpp - include/strata/gpu/runtime.hpp on Metal (metal-cpp). Skeleton of MAC-PLAN Phase 1.
+//
+// Memory model (measured on the M5 Max, phaseA-tests/mac-design.md):
+// - every allocation is one MTLBuffer, storageModeShared, hazard tracking untracked (the engine orders its own work
+// on streams, as on CUDA); the "device pointer" handed to the host code is the buffer's gpuAddress, which differs
+// from contents() on Apple GPUs, so host code that wrongly dereferences a device pointer faults instead of
+// silently working. host_view() is the sanctioned CPU view.
+// - all buffers sit in one MTLResidencySet attached to every queue, so kernels may take raw gpuAddress pointers.
+// Streams: a command queue + the open command buffer + the open compute encoder + a shared-event timeline. Work is
+// committed at event records, synchronizations, host functions and every kFlushEvery dispatches.
+// Graphs: begin_capture switches the stream to recording; dispatch/copy/memset/event ops are kept as data and
+// re-encoded by graph_launch (encoding measured at ~0.17 us per dispatch on the M5 Max).
+#define NS_PRIVATE_IMPLEMENTATION
+#define MTL_PRIVATE_IMPLEMENTATION
+#include <Foundation/Foundation.hpp>
+#include <Metal/Metal.hpp>
+
+#include "strata/gpu/metal.hpp"
+#include "strata/gpu/runtime.hpp"
+
+#include <sys/sysctl.h>
+
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <iterator>
+#include <map>
+#include <mutex>
+#include <thread>
+#include <vector>
+
+namespace strata::gpu {
+
+namespace {
+
+constexpr int kFlushEvery = 4096; // dispatches per command buffer before an automatic commit
+
+struct Alloc {
+ MTL::Buffer* buf = nullptr;
+ uint64_t gpu = 0;
+ uint8_t* cpu = nullptr;
+ size_t bytes = 0;
+ bool host = false; // from host_alloc (the host code holds the CPU address)
+};
+
+struct Op {
+ enum Kind { Dispatch, Copy, Fill, Record, Wait } kind = Dispatch;
+ MTL::ComputePipelineState* pipe = nullptr;
+ uint8_t args[256];
+ size_t arg_bytes = 0;
+ std::vector<uint8_t> big_args;
+ metal::Grid groups, threads;
+ size_t tg_bytes = 0;
+ void* dst = nullptr;
+ const void* src = nullptr;
+ size_t bytes = 0;
+ int value = 0;
+ Event ev = nullptr;
+};
+
+} // namespace
+
+struct EventImpl {
+ MTL::SharedEvent* ev = nullptr; // the recording stream's timeline
+ uint64_t value = 0; // 0: never recorded (complete, as a fresh CUDA event)
+};
+
+struct GraphImpl {
+ std::vector<Op> ops;
+};
+struct GraphExecImpl {
+ std::vector<Op> ops;
+};
+
+struct StreamImpl {
+ MTL::CommandQueue* q = nullptr;
+ MTL::CommandBuffer* cb = nullptr;
+ MTL::ComputeCommandEncoder* enc = nullptr;
+ MTL::SharedEvent* tl = nullptr;
+ uint64_t submitted = 0; // the timeline value the last committed command buffer signals
+ int pending = 0; // dispatches in the open command buffer
+ GraphImpl* rec = nullptr;
+};
+
+namespace {
+
+struct Runtime {
+ MTL::Device* dev = nullptr;
+ MTL::ResidencySet* rs = nullptr;
+ std::mutex mu;
+ std::map<uint64_t, Alloc> by_gpu; // gpuAddress -> allocation
+ std::map<uintptr_t, uint64_t> by_cpu; // contents() -> gpuAddress
+ StreamImpl* legacy = nullptr;
+ std::map<std::string, MTL::ComputePipelineState*> pipes;
+ std::map<std::string, MTL::Library*> libs;
+ metal::Stats stats;
+};
+
+Runtime& rt() {
+ static Runtime* r = [] {
+ auto* x = new Runtime;
+ x->dev = MTL::CreateSystemDefaultDevice();
+ NS::Error* e = nullptr;
+ MTL::ResidencySetDescriptor* d = MTL::ResidencySetDescriptor::alloc()->init();
+ x->rs = x->dev->newResidencySet(d, &e);
+ d->release();
+ return x;
+ }();
+ return *r;
+}
+
+thread_local Error t_last = kSuccess;
+Error fail(Error e) {
+ if (e != kSuccess && e != kNotReady) t_last = e;
+ return e;
+}
+
+StreamImpl* make_stream() {
+ auto* s = new StreamImpl;
+ s->q = rt().dev->newCommandQueue();
+ s->q->addResidencySet(rt().rs);
+ s->tl = rt().dev->newSharedEvent();
+ s->tl->setSignaledValue(0);
+ return s;
+}
+
+StreamImpl* S(Stream s) {
+ if (s) return s;
+ Runtime& r = rt();
+ std::lock_guard<std::mutex> lk(r.mu);
+ if (!r.legacy) r.legacy = make_stream();
+ return r.legacy;
+}
+
+/// The allocation that holds GPU address `p` (or CPU address `p` of a host allocation), with the offset into it.
+const Alloc* find(const void* p, size_t* off) {
+ Runtime& r = rt();
+ std::lock_guard<std::mutex> lk(r.mu);
+ const uint64_t a = (uint64_t) (uintptr_t) p;
+ auto it = r.by_gpu.upper_bound(a);
+ if (it != r.by_gpu.begin()) {
+ --it;
+ if (a < it->first + it->second.bytes) { *off = a - it->first; return &it->second; }
+ }
+ auto ic = r.by_cpu.upper_bound((uintptr_t) p);
+ if (ic != r.by_cpu.begin()) {
+ --ic;
+ const Alloc& al = r.by_gpu[ic->second];
+ if ((uintptr_t) p < ic->first + al.bytes) { *off = (uintptr_t) p - ic->first; return &al; }
+ }
+ return nullptr;
+}
+
+MTL::CommandBuffer* open_cb(StreamImpl* s) {
+ if (!s->cb) {
+ s->cb = s->q->commandBufferWithUnretainedReferences();
+ s->cb->retain();
+ ++rt().stats.command_buffers;
+ }
+ return s->cb;
+}
+void end_encoder(StreamImpl* s) {
+ if (s->enc) { s->enc->endEncoding(); s->enc = nullptr; }
+}
+MTL::ComputeCommandEncoder* encoder(StreamImpl* s) {
+ if (!s->enc) s->enc = open_cb(s)->computeCommandEncoder(); // serial dispatch: each dispatch sees the last
+ return s->enc;
+}
+void flush(StreamImpl* s) {
+ if (!s->cb) return;
+ end_encoder(s);
+ s->cb->encodeSignalEvent(s->tl, ++s->submitted);
+ s->cb->commit();
+ s->cb->release();
+ s->cb = nullptr;
+ s->pending = 0;
+}
+Error wait_value(MTL::SharedEvent* ev, uint64_t v) {
+ while (ev->signaledValue() < v) std::this_thread::yield();
+ ++rt().stats.host_syncs;
+ return kSuccess;
+}
+
+Error encode_copy(StreamImpl* s, void* dst, const void* src, size_t n) {
+ size_t od = 0, os = 0;
+ const Alloc* ad = find(dst, &od);
+ const Alloc* as = find(src, &os);
+ if (ad && as) { // buffer to buffer: a blit, in stream order
+ end_encoder(s);
+ MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder();
+ b->copyFromBuffer(as->buf, os, ad->buf, od, n);
+ b->endEncoding();
+ ++rt().stats.blits;
+ return kSuccess;
+ }
+ // ordinary host memory on one side: the stream's earlier work must be complete first (the conservative CUDA
+ // pageable-memory semantics: the call returns when the copy is done)
+ flush(s);
+ wait_value(s->tl, s->submitted);
+ uint8_t* d = ad ? ad->cpu + od : (uint8_t*) dst;
+ const uint8_t* sp = as ? as->cpu + os : (const uint8_t*) src;
+ std::memcpy(d, sp, n);
+ return kSuccess;
+}
+
+Error encode_fill(StreamImpl* s, void* p, int value, size_t n) {
+ size_t off = 0;
+ const Alloc* a = find(p, &off);
+ if (!a) return fail(kErrorInvalidValue);
+ end_encoder(s);
+ MTL::BlitCommandEncoder* b = open_cb(s)->blitCommandEncoder();
+ b->fillBuffer(a->buf, NS::Range::Make(off, n), (uint8_t) value);
+ b->endEncoding();
+ ++rt().stats.blits;
+ return kSuccess;
+}
+
+Error encode_dispatch(StreamImpl* s, const Op& o) {
+ MTL::ComputeCommandEncoder* e = encoder(s);
+ e->setComputePipelineState(o.pipe);
+ if (o.big_args.empty()) e->setBytes(o.args, o.arg_bytes, 0);
+ else e->setBytes(o.big_args.data(), o.big_args.size(), 0);
+ if (o.tg_bytes) e->setThreadgroupMemoryLength(o.tg_bytes, 0);
+ e->dispatchThreadgroups(MTL::Size(o.groups.x, o.groups.y, o.groups.z), MTL::Size(o.threads.x, o.threads.y, o.threads.z));
+ ++rt().stats.dispatches;
+ if (++s->pending >= kFlushEvery) flush(s);
+ return kSuccess;
+}
+
+Error record_event(EventImpl* e, StreamImpl* s) {
+ flush(s); // CUDA submits on launch: a recorded event must become complete without a further call
+ e->ev = s->tl;
+ e->value = s->submitted;
+ return kSuccess;
+}
+Error wait_event(StreamImpl* s, EventImpl* e) {
+ if (!e || e->value == 0) return kSuccess;
+ end_encoder(s);
+ open_cb(s)->encodeWait(e->ev, e->value);
+ return kSuccess;
+}
+
+Error run_op(StreamImpl* s, const Op& o) {
+ switch (o.kind) {
+ case Op::Dispatch: return encode_dispatch(s, o);
+ case Op::Copy: return encode_copy(s, o.dst, o.src, o.bytes);
+ case Op::Fill: return encode_fill(s, o.dst, o.value, o.bytes);
+ case Op::Record: return record_event(o.ev, s);
+ case Op::Wait: return wait_event(s, o.ev);
+ }
+ return kSuccess;
+}
+
+Error new_alloc(void** p, size_t bytes, bool host) {
+ Runtime& r = rt();
+ const size_t n = bytes ? bytes : 1;
+ MTL::Buffer* b = r.dev->newBuffer(n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);
+ if (!b) return fail(kErrorMemoryAllocation);
+ Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, host};
+ {
+ std::lock_guard<std::mutex> lk(r.mu);
+ r.by_gpu[a.gpu] = a;
+ r.by_cpu[(uintptr_t) a.cpu] = a.gpu;
+ r.rs->addAllocation(b);
+ r.rs->commit();
+ }
+ *p = host ? (void*) a.cpu : (void*) (uintptr_t) a.gpu;
+ return kSuccess;
+}
+
+Error free_alloc(void* p) {
+ if (!p) return kSuccess;
+ Runtime& r = rt();
+ size_t off = 0;
+ const Alloc* a = find(p, &off);
+ if (!a || off != 0) return fail(kErrorInvalidValue);
+ device_synchronize(); // as cudaFree: the GPU is done with it
+ std::lock_guard<std::mutex> lk(r.mu);
+ MTL::Buffer* b = a->buf;
+ const uint64_t g = a->gpu;
+ r.by_cpu.erase((uintptr_t) a->cpu);
+ r.by_gpu.erase(g);
+ r.rs->removeAllocation(b);
+ r.rs->commit();
+ b->release();
+ return kSuccess;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------------------------------------------- runtime.hpp
+void* host_view(const void* p) {
+ size_t off = 0;
+ const Alloc* a = find(p, &off);
+ return a ? a->cpu + off : nullptr;
+}
+
+Error get_last_error() { const Error e = t_last; t_last = kSuccess; return e; }
+Error peek_last_error() { return t_last; }
+const char* error_string(Error e) {
+ switch (e) {
+ case kSuccess: return "no error";
+ case kNotReady: return "device not ready";
+ case kErrorInvalidValue: return "invalid argument";
+ case kErrorMemoryAllocation: return "out of memory";
+ case kErrorUnsupported: return "operation not supported on Metal";
+ case kErrorLaunchFailure: return "command buffer failed";
+ }
+ return "unknown Metal runtime error";
+}
+
+Error get_device(int* dev) { *dev = 0; return kSuccess; }
+Error set_device(int dev) { return dev == 0 ? kSuccess : fail(kErrorInvalidValue); }
+Error device_count(int* n) { *n = rt().dev ? 1 : 0; return kSuccess; }
+Error device_synchronize() {
+ Runtime& r = rt();
+ StreamImpl* s = S(nullptr);
+ flush(s);
+ return wait_value(s->tl, s->submitted);
+ (void) r;
+}
+Error mem_get_info(size_t* free_b, size_t* total_b) {
+ // the GPU's budget is the working set the OS grants this process; what is free is that minus what is allocated
+ MTL::Device* d = rt().dev;
+ const uint64_t budget = d->recommendedMaxWorkingSetSize();
+ const uint64_t used = d->currentAllocatedSize();
+ *total_b = (size_t) budget;
+ *free_b = (size_t) (used < budget ? budget - used : 0);
+ return kSuccess;
+}
+Error device_integrated(int* v, int) { *v = 1; return kSuccess; }
+Error device_sm_count(int* v, int) { *v = 0; return fail(kErrorUnsupported); } // Apple reports no core count
+Error device_clock_khz(int* v, int) { *v = 0; return fail(kErrorUnsupported); }
+Error runtime_version(int* v) { *v = 0; return kSuccess; }
+Error device_can_access_peer(int* v, int, int) { *v = 0; return kSuccess; }
+Error device_enable_peer_access(int, unsigned) { return fail(kErrorUnsupported); }
+Error get_device_properties(DeviceProp* p, int dev) {
+ if (dev != 0) return fail(kErrorInvalidValue);
+ *p = DeviceProp{};
+ MTL::Device* d = rt().dev;
+ std::snprintf(p->name, sizeof p->name, "%s", d->name()->utf8String());
+ std::snprintf(p->gcnArchName, sizeof p->gcnArchName, "%s", d->supportsFamily(MTL::GPUFamilyApple10) ? "apple10" : "apple9-or-older");
+ p->warpSize = 32; // the SIMD-group width of every Apple GPU
+ p->totalGlobalMem = (size_t) d->recommendedMaxWorkingSetSize();
+ return kSuccess;
+}
+
+Error malloc_device_raw(void** p, size_t bytes) { return new_alloc(p, bytes, false); }
+Error free_device(void* p) { return free_alloc(p); }
+Error host_alloc_raw(void** p, size_t bytes, unsigned) { return new_alloc(p, bytes, true); }
+Error free_host(void* p) {
+ {
+ Runtime& r = rt();
+ std::lock_guard<std::mutex> lk(r.mu);
+ auto it = r.by_cpu.find((uintptr_t) p);
+ if (it == r.by_cpu.end()) return fail(kErrorInvalidValue);
+ }
+ return free_alloc(p);
+}
+Error host_register(void* p, size_t bytes, unsigned) {
+ // existing host memory (an mmapped file, an arena) as a NoCopy buffer: page-aligned start and length required
+ const uintptr_t pg = 16384;
+ if (((uintptr_t) p % pg) != 0) return fail(kErrorInvalidValue);
+ Runtime& r = rt();
+ const size_t n = (bytes + pg - 1) / pg * pg;
+ MTL::Buffer* b = r.dev->newBuffer(p, n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked, nullptr);
+ if (!b) return fail(kErrorMemoryAllocation);
+ Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, true};
+ std::lock_guard<std::mutex> lk(r.mu);
+ r.by_gpu[a.gpu] = a;
+ r.by_cpu[(uintptr_t) a.cpu] = a.gpu;
+ r.rs->addAllocation(b);
+ r.rs->commit();
+ return kSuccess;
+}
+Error host_unregister(void* p) { return free_alloc(p); }
+Error host_device_pointer_raw(void** dev, void* host) {
+ size_t off = 0;
+ const Alloc* a = find(host, &off);
+ if (!a) return fail(kErrorInvalidValue);
+ *dev = (void*) (uintptr_t) (a->gpu + off);
+ return kSuccess;
+}
+Error memset_device(void* p, int value, size_t bytes) {
+ StreamImpl* s = S(nullptr);
+ const Error e = encode_fill(s, p, value, bytes);
+ flush(s);
+ wait_value(s->tl, s->submitted);
+ return e;
+}
+Error memset_async(void* p, int value, size_t bytes, Stream st) {
+ StreamImpl* s = S(st);
+ if (s->rec) {
+ Op o;
+ o.kind = Op::Fill; o.dst = p; o.value = value; o.bytes = bytes;
+ s->rec->ops.push_back(std::move(o));
+ return kSuccess;
+ }
+ return encode_fill(s, p, value, bytes);
+}
+
+Error memcpy_sync(void* dst, const void* src, size_t bytes, CopyKind) {
+ StreamImpl* s = S(nullptr);
+ const Error e = encode_copy(s, dst, src, bytes);
+ flush(s);
+ wait_value(s->tl, s->submitted);
+ return e;
+}
+Error memcpy_2d_async(void* dst, size_t dpitch, const void* src, size_t spitch, size_t width, size_t height, CopyKind k, Stream st) {
+ for (size_t r = 0; r < height; ++r) { // skeleton: one copy per row (rare in the engine)
+ const Error e = memcpy_async((uint8_t*) dst + r * dpitch, (const uint8_t*) src + r * spitch, width, k, st);
+ if (e != kSuccess) return e;
+ }
+ return kSuccess;
+}
+Error memcpy_peer_async(void* dst, int dst_dev, const void* src, int src_dev, size_t bytes, Stream st) {
+ if (dst_dev != 0 || src_dev != 0) return fail(kErrorInvalidValue); // one GPU
+ return memcpy_async(dst, src, bytes, kDeviceToDevice, st);
+}
+Error memcpy_async(void* dst, const void* src, size_t bytes, CopyKind, Stream st) {
+ StreamImpl* s = S(st);
+ if (s->rec) {
+ Op o;
+ o.kind = Op::Copy; o.dst = dst; o.src = src; o.bytes = bytes;
+ s->rec->ops.push_back(std::move(o));
+ return kSuccess;
+ }
+ return encode_copy(s, dst, src, bytes);
+}
+
+Error stream_create(Stream* s, unsigned) { *s = make_stream(); return kSuccess; }
+Error stream_destroy(Stream s) {
+ if (!s) return kSuccess;
+ flush(s);
+ wait_value(s->tl, s->submitted);
+ s->tl->release();
+ s->q->release();
+ delete s;
+ return kSuccess;
+}
+Error stream_synchronize(Stream st) {
+ StreamImpl* s = S(st);
+ flush(s);
+ return wait_value(s->tl, s->submitted);
+}
+Error stream_query(Stream st) {
+ StreamImpl* s = S(st);
+ flush(s);
+ return s->tl->signaledValue() >= s->submitted ? kSuccess : kNotReady;
+}
+Error stream_wait_event(Stream st, Event e, unsigned) {
+ StreamImpl* s = S(st);
+ if (s->rec) {
+ Op o;
+ o.kind = Op::Wait; o.ev = e;
+ s->rec->ops.push_back(std::move(o));
+ return kSuccess;
+ }
+ return wait_event(s, e);
+}
+Error launch_host_func(Stream st, HostFn fn, void* arg) {
+ // skeleton: in stream order by completing the stream first (the engine's uses are rare; Phase 2 replaces this by a
+ // completion handler + a shared-event wait so the host thread does not block)
+ StreamImpl* s = S(st);
+ if (s->rec) return fail(kErrorUnsupported);
+ flush(s);
+ wait_value(s->tl, s->submitted);
+ fn(arg);
+ return kSuccess;
+}
+
+Error event_create(Event* e, unsigned) { *e = new EventImpl; return kSuccess; }
+Error event_destroy(Event e) { delete e; return kSuccess; }
+Error event_record(Event e, Stream st) {
+ StreamImpl* s = S(st);
+ if (s->rec) {
+ Op o;
+ o.kind = Op::Record; o.ev = e;
+ s->rec->ops.push_back(std::move(o));
+ return kSuccess;
+ }
+ return record_event(e, s);
+}
+Error event_query(Event e) { return !e->ev || e->ev->signaledValue() >= e->value ? kSuccess : kNotReady; }
+Error event_synchronize(Event e) { return e->ev ? wait_value(e->ev, e->value) : kSuccess; }
+Error event_elapsed_ms(float* ms, Event, Event) { *ms = 0.0f; return fail(kErrorUnsupported); }
+
+Error begin_capture(Stream st) {
+ StreamImpl* s = S(st);
+ if (s->rec) return fail(kErrorInvalidValue);
+ flush(s);
+ s->rec = new GraphImpl;
+ return kSuccess;
+}
+Error end_capture(Stream st, Graph* g) {
+ StreamImpl* s = S(st);
+ if (!s->rec) { *g = nullptr; return fail(kErrorInvalidValue); }
+ *g = s->rec;
+ s->rec = nullptr;
+ return kSuccess;
+}
+Error graph_node_count(Graph g, size_t* n) { *n = g ? g->ops.size() : 0; return kSuccess; }
+Error graph_instantiate(GraphExec* x, Graph g) {
+ *x = new GraphExecImpl{g->ops};
+ return kSuccess;
+}
+Error graph_launch(GraphExec x, Stream st) {
+ StreamImpl* s = S(st);
+ if (s->rec) { // a graph launched into a capture becomes part of it (CUDA: a child graph)
+ s->rec->ops.insert(s->rec->ops.end(), x->ops.begin(), x->ops.end());
+ return kSuccess;
+ }
+ for (const Op& o : x->ops) {
+ const Error e = run_op(s, o);
+ if (e != kSuccess) return e;
+ }
+ return kSuccess;
+}
+Error graph_upload(GraphExec, Stream) { return kSuccess; }
+Error graph_destroy(Graph g) { delete g; return kSuccess; }
+Error graph_exec_destroy(GraphExec x) { delete x; return kSuccess; }
+
+// ---------------------------------------------------------------------------------------------------- metal.hpp
+namespace metal {
+
+MTL::Device* device() { return rt().dev; }
+
+MTL::ComputePipelineState* pipeline(const char* source_name, const char* source, const char* function, std::string& err) {
+ Runtime& r = rt();
+ const std::string key = std::string(source_name) + "::" + function;
+ std::lock_guard<std::mutex> lk(r.mu);
+ if (auto it = r.pipes.find(key); it != r.pipes.end()) return it->second;
+ MTL::Library*& lib = r.libs[source_name];
+ NS::Error* e = nullptr;
+ if (!lib) {
+ MTL::CompileOptions* co = MTL::CompileOptions::alloc()->init();
+ co->setMathMode(MTL::MathModeSafe); // no fast-math reassociation: parity with the CUDA reference first
+ lib = r.dev->newLibrary(NS::String::string(source, NS::UTF8StringEncoding), co, &e);
+ co->release();
+ if (!lib) {
+ err = std::string("MSL compile of ") + source_name + ": " + (e ? e->localizedDescription()->utf8String() : "?");
+ return nullptr;
+ }
+ }
+ MTL::Function* f = lib->newFunction(NS::String::string(function, NS::UTF8StringEncoding));
+ if (!f) { err = std::string("no MSL function ") + function; return nullptr; }
+ MTL::ComputePipelineState* p = r.dev->newComputePipelineState(f, &e);
+ f->release();
+ if (!p) { err = std::string("pipeline ") + function + ": " + (e ? e->localizedDescription()->utf8String() : "?"); return nullptr; }
+ r.pipes[key] = p;
+ return p;
+}
+
+Error dispatch(Stream st, MTL::ComputePipelineState* p, const void* args, size_t arg_bytes, Grid groups, Grid threads,
+ size_t tg_bytes) {
+ if (arg_bytes > 4096) return fail(kErrorInvalidValue); // setBytes limit
+ StreamImpl* s = S(st);
+ Op o;
+ o.kind = Op::Dispatch;
+ o.pipe = p;
+ if (arg_bytes <= sizeof o.args) { std::memcpy(o.args, args, arg_bytes); o.arg_bytes = arg_bytes; }
+ else o.big_args.assign((const uint8_t*) args, (const uint8_t*) args + arg_bytes);
+ o.groups = groups;
+ o.threads = threads;
+ o.tg_bytes = tg_bytes;
+ if (s->rec) { s->rec->ops.push_back(std::move(o)); return kSuccess; }
+ return encode_dispatch(s, o);
+}
+
+Stats stats() { return rt().stats; }
+
+} // namespace metal
+} // namespace strata::gpu
diff --git a/metal/tests/runtime_hello.cpp b/metal/tests/runtime_hello.cpp
new file mode 100644
index 000000000..eee9e5f1a
--- /dev/null
+++ b/metal/tests/runtime_hello.cpp
@@ -0,0 +1,162 @@
+// metal/tests/runtime_hello.cpp - the Metal runtime end to end, with the shared src/core/graph.cpp built unchanged:
+// 1. gpu::malloc_device / host_alloc (mapped) / memcpy_async / a kernel through metal::dispatch / events / D2H
+// 2. the SHARED host file src/core/graph.cpp (CapturedGraph / GraphRegistry), compiled unchanged for Metal:
+// capture a 3-kernel "window", replay it 5 times, wait with wait_ms (event query polling), check the data path
+// is live (each replay reads the buffers' current contents, as a CUDA graph does)
+// 3. host_device_pointer: a kernel writes a mapped host buffer that the host reads without a copy
+// 4. the cost of replaying a 1,000-dispatch window
+#include "strata/core/graph.hpp"
+#include "strata/gpu/metal.hpp"
+#include "strata/gpu/runtime.hpp"
+
+#include <chrono>
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include <vector>
+
+namespace gpu = strata::gpu;
+
+static const char* kSrc = R"MSL(
+#include <metal_stdlib>
+using namespace metal;
+struct Axpy { device const float* x; device float* y; float a; uint n; };
+kernel void axpy(constant Axpy& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ if (i < p.n) p.y[i] = p.a * p.x[i] + p.y[i];
+}
+struct Scale { device float* y; device const float* s; uint n; }; // the factor is DATA (a device buffer), not an argument
+kernel void scale(constant Scale& p [[buffer(0)]], uint i [[thread_position_in_grid]]) {
+ if (i < p.n) p.y[i] *= p.s[0];
+}
+)MSL";
+struct Axpy { uint64_t x, y; float a; uint32_t n; };
+struct Scale { uint64_t y, s; uint32_t n; };
+
+static int g_fail = 0;
+#define CHECK(c, ...) do { if (!(c)) { std::printf("FAIL %s:%d: ", __FILE__, __LINE__); std::printf(__VA_ARGS__); std::printf("\n"); ++g_fail; } } while (0)
+
+static double now_ms() {
+ return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+
+int main() {
+ std::string err;
+ MTL::ComputePipelineState* p_axpy = gpu::metal::pipeline("hello", kSrc, "axpy", err);
+ MTL::ComputePipelineState* p_scale = gpu::metal::pipeline("hello", kSrc, "scale", err);
+ CHECK(p_axpy && p_scale, "pipelines: %s", err.c_str());
+ if (!p_axpy || !p_scale) return 1;
+ const uint32_t N = 1 << 16;
+ const gpu::metal::Grid groups{(N + 255) / 256, 1, 1}, threads{256, 1, 1};
+
+ gpu::Stream s = nullptr, s2 = nullptr;
+ CHECK(gpu::stream_create(&s, gpu::kStreamNonBlocking) == gpu::kSuccess, "stream");
+ CHECK(gpu::stream_create(&s2, gpu::kStreamNonBlocking) == gpu::kSuccess, "stream 2");
+ float *dx = nullptr, *dy = nullptr, *ds = nullptr, *hx = nullptr;
+ CHECK(gpu::malloc_device((void**) &dx, N * 4) == gpu::kSuccess, "malloc x");
+ CHECK(gpu::malloc_device((void**) &dy, N * 4) == gpu::kSuccess, "malloc y");
+ CHECK(gpu::malloc_device((void**) &ds, 4) == gpu::kSuccess, "malloc s");
+ CHECK(gpu::host_alloc((void**) &hx, N * 4, gpu::kHostAllocMapped) == gpu::kSuccess, "host_alloc");
+ CHECK(gpu::host_view(dx) != nullptr && gpu::host_view(dx) != (void*) dx, "a device pointer is a GPU address, not the CPU view");
+
+ // ---- 1. copies, a kernel, an event across two streams, D2H
+ std::vector<float> x(N), y(N, 1.0f), got(N);
+ for (uint32_t i = 0; i < N; ++i) x[i] = (float) (i % 1000);
+ std::memcpy(hx, x.data(), N * 4);
+ gpu::memcpy_async(dx, hx, N * 4, gpu::kHostToDevice, s); // mapped host buffer -> device: a blit
+ gpu::memcpy_async(dy, y.data(), N * 4, gpu::kHostToDevice, s); // pageable -> device
+ Axpy a{(uint64_t) dx, (uint64_t) dy, 2.0f, N};
+ gpu::metal::dispatch(s, p_axpy, &a, sizeof a, groups, threads);
+ gpu::Event ev = nullptr;
+ gpu::event_create(&ev, gpu::kEventDisableTiming);
+ gpu::event_record(ev, s);
+ gpu::stream_wait_event(s2, ev); // s2's kernel runs after s's
+ Axpy a2{(uint64_t) dx, (uint64_t) dy, 1.0f, N};
+ gpu::metal::dispatch(s2, p_axpy, &a2, sizeof a2, groups, threads);
+ gpu::memcpy_async(got.data(), dy, N * 4, gpu::kDeviceToHost, s2);
+ gpu::stream_synchronize(s2);
+ int bad = 0;
+ for (uint32_t i = 0; i < N; ++i) bad += got[i] != 3.0f * x[i] + 1.0f;
+ CHECK(bad == 0, "step 1: %d wrong values", bad);
+ std::printf("1. copies + kernel + cross-stream event + D2H: %s\n", bad ? "FAIL" : "OK");
+
+ // ---- 2. the shared CapturedGraph from src/core/graph.cpp
+ {
+ float one = 1.0f;
+ gpu::memcpy_sync(ds, &one, 4, gpu::kHostToDevice);
+ strata::core::CapturedGraph g;
+ CHECK(g.begin(s, err), "begin: %s", err.c_str());
+ Axpy w{(uint64_t) dx, (uint64_t) dy, 1.0f, N};
+ Scale sc{(uint64_t) dy, (uint64_t) ds, N};
+ gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads);
+ gpu::metal::dispatch(s, p_scale, &sc, sizeof sc, groups, threads);
+ gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads);
+ CHECK(g.end(s, err), "end: %s", err.c_str());
+ CHECK(g.nodes() == 3, "nodes %zu", g.nodes());
+ // host model of y
+ std::vector<float> m(N);
+ for (uint32_t i = 0; i < N; ++i) m[i] = got[i];
+ bool all = true;
+ for (int rep = 0; rep < 5; ++rep) {
+ const float f = rep % 2 ? 0.5f : 2.0f; // the per-step value changes as DATA between replays
+ float* sv = (float*) gpu::host_view(ds);
+ gpu::stream_synchronize(s);
+ *sv = f;
+ CHECK(g.launch(s, err), "launch: %s", err.c_str());
+ CHECK(g.wait_ms(2000), "wait_ms timed out");
+ for (uint32_t i = 0; i < N; ++i) m[i] = ((m[i] + x[i]) * f) + x[i];
+ }
+ gpu::memcpy_sync(got.data(), dy, N * 4, gpu::kDeviceToHost);
+ int wrong = 0;
+ for (uint32_t i = 0; i < N; ++i) wrong += got[i] != m[i];
+ all = wrong == 0;
+ CHECK(all, "graph replays: %d wrong values", wrong);
+ std::printf("2. shared CapturedGraph (src/core/graph.cpp): 3-kernel window, 5 replays with live data: %s\n", all ? "OK" : "FAIL");
+
+ strata::core::GraphRegistry reg(s);
+ int bodies = 0;
+ for (int k = 0; k < 4; ++k)
+ CHECK(reg.record(strata::core::LayerType::GDN, 1, [&] { ++bodies; gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads); }, err),
+ "record: %s", err.c_str());
+ CHECK(bodies == 1 && reg.size() == 1, "registry captured %d bodies", bodies);
+ CHECK(reg.launch(strata::core::LayerType::GDN, 1, 2000, err), "registry launch: %s", err.c_str());
+ std::printf(" GraphRegistry: body captured once over 4 records, launch+wait: %s\n", bodies == 1 ? "OK" : "FAIL");
+ }
+
+ // ---- 3. a mapped host buffer written by a kernel, read by the host with no copy
+ {
+ float* dview = nullptr;
+ CHECK(gpu::host_device_pointer((void**) &dview, hx) == gpu::kSuccess, "host_device_pointer");
+ std::memset(hx, 0, N * 4);
+ Axpy w{(uint64_t) dx, (uint64_t) dview, 1.0f, N};
+ gpu::metal::dispatch(s, p_axpy, &w, sizeof w, groups, threads);
+ gpu::stream_synchronize(s);
+ int wrong = 0;
+ for (uint32_t i = 0; i < N; ++i) wrong += hx[i] != x[i];
+ CHECK(wrong == 0, "mapped: %d wrong", wrong);
+ std::printf("3. kernel -> mapped host buffer, host reads it in place: %s\n", wrong ? "FAIL" : "OK");
+ }
+
+ // ---- 4. replay cost of a 1,000-dispatch window
+ {
+ strata::core::CapturedGraph g;
+ Axpy w{(uint64_t) dx, (uint64_t) dy, 0.0f, 256};
+ g.begin(s, err);
+ for (int k = 0; k < 1000; ++k) gpu::metal::dispatch(s, p_axpy, &w, sizeof w, gpu::metal::Grid{1, 1, 1}, threads);
+ g.end(s, err);
+ for (int rep = 0; rep < 5; ++rep) {
+ const double t0 = now_ms();
+ g.launch(s, err);
+ const double t1 = now_ms();
+ g.wait_ms(5000);
+ std::printf("4. 1000-dispatch window: replay (encode+commit) %.3f ms, until complete %.3f ms\n", t1 - t0, now_ms() - t0);
+ }
+ }
+ const auto st = gpu::metal::stats();
+ std::printf("stats: %llu dispatches, %llu command buffers, %llu blits, %llu host syncs\n", (unsigned long long) st.dispatches,
+ (unsigned long long) st.command_buffers, (unsigned long long) st.blits, (unsigned long long) st.host_syncs);
+ gpu::free_device(dx); gpu::free_device(dy); gpu::free_device(ds); gpu::free_host(hx);
+ gpu::event_destroy(ev);
+ gpu::stream_destroy(s); gpu::stream_destroy(s2);
+ std::printf(g_fail ? "RESULT: %d FAILED\n" : "RESULT: all passed\n", g_fail);
+ return g_fail ? 1 : 0;
+}
diff --git a/src/core/expert_cache.cpp b/src/core/expert_cache.cpp
index 9fe45205f..1920fdb7f 100644
--- a/src/core/expert_cache.cpp
+++ b/src/core/expert_cache.cpp
@@ -3,7 +3,7 @@
// #533's segmented cache uses CUDA's virtual memory management (cuMem*): not on HIP, neither the RDNA backend nor
// the gfx906 compat build (PR #638), which compiles this file as HIP without STRATA_USE_HIP
-#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
+#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
#define STRATA_EC_NO_VMM 1
#endif
diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp
index cbc19ebc4..0c26e54ce 100644
--- a/src/core/mtp.cpp
+++ b/src/core/mtp.cpp
@@ -422,7 +422,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session
// --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch
// on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default)
bool prio = false;
-#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) // (HIP: the default priority)
+#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // (HIP, Metal: the default priority)
static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }();
int prio_lo = 0, prio_hi = 0;
if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess)
diff --git a/src/core/remote_experts.cpp b/src/core/remote_experts.cpp
index 9af13abfb..f01bf6fe3 100644
--- a/src/core/remote_experts.cpp
+++ b/src/core/remote_experts.cpp
@@ -75,7 +75,7 @@ bool RemoteExperts::preflight(int device, double& free_gib, std::string& err) {
// The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up
// costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible
// before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default.
-#if !defined(STRATA_USE_HIP)
+#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL)
const char* spin = std::getenv("STRATA_REMOTE_SPIN");
if (!(spin && spin[0] == '0')) cudaInitDevice(device, cudaDeviceScheduleSpin | cudaDeviceMapHost, 0);
cudaGetLastError();
diff --git a/src/core/verify.cpp b/src/core/verify.cpp
index 3995ae9dd..5757a72fd 100644
--- a/src/core/verify.cpp
+++ b/src/core/verify.cpp
@@ -1902,7 +1902,7 @@ bool Verifier::capture(int T, std::string& err) {
std::fprintf(stderr, "\n%s\n", seq.c_str());
}
#endif
-#if !defined(STRATA_USE_HIP) // a CUDA debug listing (node types, kernel names)
+#if !defined(STRATA_USE_HIP) && !defined(STRATA_GPU_METAL) // a CUDA debug listing (node types, kernel names)
if (std::getenv("STRATA_VERIFY_NODES") != nullptr) { // what the window graph holds
size_t nn = 0;
cudaGraphGetNodes(graph, nullptr, &nn);