Metal compute (gpu)
gpu.available() reports whether a Metal compute device and command queue are
available. Other GPU operations throw a catchable error when unavailable, including
on non-Apple platforms. Standalone dispatch is synchronous: it waits for completion
and reports compilation or command errors before returning.
For a sequence of dependent kernels, enqueue them in one explicit batch and wait
once. dispatch keeps its existing synchronous behavior outside this API:
GpuBatch batch = gpu.begin()
gpu.enqueue(batch, projectionKernel, projectionBuffers, projectionThreads)
gpu.enqueue(batch, normalizationKernel, normalizationBuffers, normalizationThreads)
gpu.commit(batch)enqueue records work; commit submits the entire command buffer and waits once.
Separate serial compute encoders and tracked buffers preserve dependent writes
between enqueues. Readback, host writes, ordinary synchronous dispatch using a
pending buffer, and explicit release of queued buffers/kernels throw until all
batches using that resource are waited, committed or cancelled. Initialize inputs before
enqueueing. Direct mutation through another CPU alias must also wait until completion.
For independent kernels, opt into gpu.begin(true) (or a boolean variable).
gpu.begin() and gpu.begin(false) keep serial ordering. Concurrent batches
keep a single Metal compute encoder open; gpu.barrier(batch) orders all prior
buffer accesses before subsequent dispatches. Insert a barrier for every
read-after-write, write-after-read, or write-after-write dependency between
stages; read-only sharing and disjoint buffers may run together. Dependency
tracking is explicit, not inferred from buffer arguments. Missing barriers can
produce incorrect results. Concurrent execution is eligible to overlap, not
promised to improve performance for every workload.
GpuBatch batch = gpu.begin(true)
gpu.enqueue(batch, queryKernel, queryBuffers, queryThreads)
gpu.enqueue(batch, keyKernel, keyBuffers, keyThreads)
gpu.barrier(batch) // attention reads both projection outputs
gpu.enqueue(batch, attentionKernel, attentionBuffers, attentionThreads)
gpu.commit(batch)Use the positional boolean form above; this API does not introduce named-argument
syntax. Barriers also work with enqueue2D and explicit threadgroup sizes.
A barrier in a serial batch is a no-op; one on a consumed/cancelled batch throws.
A barrier does not submit work or make readback legal: commit still waits for all
work. Empty concurrent batches and leading/trailing barriers are valid.
The implementation follows Apple’s concurrent dispatch contract
and buffer memory barriers.
gpu.cancel(batch) discards unsubmitted work and is idempotent. On an enqueue
error, cancel the batch in your catch handler. Commit consumes the batch, including
on GPU execution failure; subsequent enqueue/commit throws. Unsubmitted batches
are discarded on owner teardown; submitted batches are waited before resources
are released. Batches and their resources must belong to the
same coroutine; they cannot cross worker or async-result boundaries.
if (gpu.available()) {
GpuBuffer input = gpu.uploadFloats([1.0, 2.0, 3.0, 4.0])
GpuBuffer output = gpu.alloc(16)
string source = '#include <metal_stdlib>\nusing namespace metal;\nkernel void twice(device const float* x [[buffer(0)]], device float* y [[buffer(1)]], uint i [[thread_position_in_grid]]) { y[i] = x[i] * 2.0f; }'
GpuKernel kernel = gpu.kernel(source, "twice")
gpu.dispatch(kernel, [input, output], 4)
float[] result = gpu.readFloats(output) // [2, 4, 6, 8]
gpu.releaseKernel(kernel)
gpu.releaseBuffer(input)
gpu.releaseBuffer(output)
}| Operation | Meaning |
|---|---|
alloc(long bytes) |
Allocate a buffer; initialize contents before reading |
upload(byte[]) |
Copy bytes, including mapped weights or packed f32 storage |
wrap(byte[]) |
Wrap a nonempty fs.mapBytesSync mapping without copying; read-only GPU input |
uploadFloats(float[]) |
Convert f64 language values to f32 GPU storage |
write(GpuBuffer, byte[], long offset) |
Update existing storage at a checked byte offset |
readBytes(GpuBuffer) |
Copy all bytes into a new byte[] |
readFloats(GpuBuffer) |
Convert f32 buffer values into a new f64 float[] |
kernel(string source, string name) |
Compile Metal source and create a compute pipeline |
inferenceSource() |
Bundled inference shader source for quantized matvec, RMS norm, RoPE, attention, and DeltaNet |
dispatch(GpuKernel, GpuBuffer[], int count) |
Bind buffers at consecutive indices and launch exactly count threads |
releaseBuffer(GpuBuffer) / releaseKernel(GpuKernel) |
Release resources immediately; repeated release is harmless |
Buffers and kernels created in the main coroutine can be used by HTTP handlers
and other coroutines on the same OS thread. Load model weights and compile
kernels before calling server.listen() on that thread, then create per-request output buffers and
batches inside handlers. Handles created in a request stay in that coroutine;
do not return them through async results or share handles across native worker
threads. server.start() runs on a separate native thread and cannot borrow
these handles: every GPU handle records its creating OS thread, and cross-thread
use throws gpu: handle belongs to another thread with guidance to use
server.listen() or create resources on the server thread. A sys.worker
body, including an async fn(WorkerPort) body, plays the part of main on its
thread: buffers and kernels it creates belong to the worker’s main arena and can
be stored in its long-lived state (see sys.md). This applies regardless
of model size; a CPU-only model path may not touch GPU handles at all.
Initializing Metal disables HTTP prefork: GPU resources cannot
survive fork(), so listen() uses one process even if a worker count is set.
Batches always stay in their creating coroutine. Resources are cleaned up when that coroutine’s arena is reset
or destroyed. Ordinary helper returns and scalar checkpoints preserve them.
Explicit release is recommended for long-running inference sessions that replace
models. Released handles remain invalid even if their source variable is copied.
The buffer limit comes from the selected device. Large mapped models may need
tensor-sized uploads. Uploads copy their source, so later CPU changes require
write. Dispatch binds up to 31 buffers. The three-argument form chooses a
threadgroup width up to 256. Shader code is responsible for buffer indexing,
shapes, and race-free writes. Compile kernels once and reuse resident buffers.
gpu.wrap(mapped) retains the mapping independently of the source list’s
lifetime and releases that hold when the Metal buffer is destroyed. It accepts
only registered, page-aligned file mappings, not arbitrary byte[] allocations;
there is no hidden copying fallback. File lengths need not be page multiples:
Metal receives the mapped final page, while readback retains the logical length.
The rounded size must fit the device’s buffer limit.
Wrapped mappings are for immutable weights. gpu.write rejects them, and shader
reflection rejects binding them to a writable argument. Do not modify the source
byte array, grow it, truncate the file, or modify aliases while a wrapper exists.
Private file mappings and copy-on-write changes must not invalidate Metal’s
registered VM region. Ordinary upload remains available for mutable GPU data.
The no-copy API’s alignment and contiguous-VM requirements follow Apple’s buffer wrapping contract.
Metal shared storage requires CPU/GPU synchronization; this API provides it by waiting at synchronous dispatch, batch commit or explicit wait before exposing results. See Apple’s shared storage documentation.
Explicit launch dimensions
gpu.dispatch(kernel, buffers, count, threadgroupSize) sets the 1-D threadgroup
width. gpu.enqueue(batch, kernel, buffers, count, threadgroupSize) provides the
same control in a batch. Existing calls without the final argument keep automatic
sizing.
For 2-D kernels, use gpu.dispatch2D(kernel, buffers, width, height, groupWidth, groupHeight) or gpu.enqueue2D(batch, kernel, buffers, width, height, groupWidth, groupHeight). Grid dimensions count threads, not threadgroups. Shaders can
read uint2 positions with thread_position_in_grid and use threadgroup memory
and barriers for cooperative tiles.
Grid dimensions must be nonnegative (zero makes the launch a no-op); threadgroup dimensions must be positive. Each dimension must fit the device limit, and the threadgroup area must fit the kernel pipeline limit. Invalid dimensions throw before encoding any work, including on empty grids. Metal launches exactly the requested grid; a final partial threadgroup may be smaller. For kernels requiring full cooperative tiles, round the grid up to multiples of the group dimensions and handle edge elements in the shader without skipping required barriers.
Dynamic threadgroup memory
Add a trailing long threadgroupBytes to explicitly sized dispatch, enqueue,
dispatch2D or enqueue2D calls. This binds dynamic threadgroup memory at index 0
for Metal arguments such as threadgroup float* scratch [[threadgroup(0)]].
Lengths are nonnegative, rounded up to 16 bytes, and checked together with the
kernel’s static threadgroup memory against the device limit before encoding.
Omitting the argument preserves the existing zero-dynamic-memory behavior.
gpu.dispatch(kernel, buffers, count, 128, 8192)
gpu.enqueue2D(batch, kernel, buffers, width, height, 32, 4, 8192) Asynchronous batch submission
gpu.submit(batch) ends encoding and submits without waiting for execution.
Encode and submit the next batch while the previous one runs. All batches use
one Metal queue, whose submission order orders their work. gpu.wait(batch)
waits for completion, reports GPU errors, releases resource pins and consumes the
batch. gpu.commit(batch) remains equivalent to submit followed by wait.
Submitted batches cannot be enqueued into, barriered, submitted again or cancelled. Waiting before submit, or waiting twice, throws. Buffers and kernels remain pinned until every batch using them is waited; CPU reads/writes, direct dispatch and explicit release remain blocked even if the GPU has already finished. Owner teardown waits for outstanding submissions to protect resource and mapping lifetimes. Resource deduplication uses a per-batch hash table with amortized constant-time insertion, including when several outstanding batches share the same resources.