metal4

package
v0.6.20 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

Overview

Package metal4 provides a minimal, zero-cgo discipline layer over the Metal 4 compute and ML bindings in github.com/tmc/apple/metal.

Metal 4 separates command memory ownership (metal.MTL4CommandAllocator), resource binding (metal.MTL4ArgumentTable), residency (metal.MTLResidencySet), and synchronization (metal.MTLSharedEvent) so hot compute and decode loops can reuse command memory without per-step allocations.

Use Probe to inspect Metal 4 support on a device without panicking on older GPUs or macOS versions. Use NewCommandContext (or NewAllocatorPool directly) to manage a ring of reusable allocators and command buffers, residency sets, pre-populated argument tables, and shared-event synchronization:

dev := metal.MTLCreateSystemDefaultDevice()
if !metal4.Probe(dev).Ready() {
	return
}
ctx, err := metal4.NewCommandContext(dev, metal4.Options{RingDepth: 3})
if err != nil {
	return
}
defer ctx.Close()

slot, err := ctx.Acquire(metal4.DefaultTimeout)
if err != nil {
	return
}
slot.Begin()
enc := slot.CommandBuffer.ComputeCommandEncoder()
// ... encode dispatches and barriers ...
enc.EndEncoding()
slot.End()
_ = ctx.CommitAndWait(slot, metal4.DefaultTimeout)

Use NewTensor to allocate resident metal.MTLTensor resources (standalone or buffer-backed), and CommandContext.NewMLPipelineFromURL / CommandContext.NewMLPipeline with Slot.NewMLEncoder or CommandContext.DispatchML to compile and execute Metal 4 machine learning networks via metal.MTL4MachineLearningCommandEncoder. On macOS 26.6.2, Metal loads compiled .mtlpackage directories produced from Core ML .mlpackage inputs by BuildMLPackage (xcrun metal-package-builder -ml).

The zero values of AllocatorPool, CommandContext, Tensor, and MLPipeline are not usable; construct them with their New functions, and release residency resources with Close when finished.

Index

Examples

Constants

View Source
const (
	// DefaultRingDepth is the default number of command allocator slots in a ring
	// (triple-buffered pipelining).
	DefaultRingDepth = 3

	// DefaultTimeout is the default GPU synchronization timeout used when a caller
	// passes a non-positive timeout to Wait, Acquire, CommitAndWait, or Drain.
	DefaultTimeout = 5 * time.Second
)

Variables

View Source
var (
	// ErrUnsupported is returned when a device does not support Metal 4.
	ErrUnsupported = errors.New("metal4: device does not support Metal 4")

	// ErrClosed is returned when an operation is attempted on a closed CommandContext or AllocatorPool.
	ErrClosed = errors.New("metal4: closed")

	// ErrTimeout is returned when waiting on a Metal shared event exceeds the timeout.
	ErrTimeout = errors.New("metal4: timed out waiting for GPU completion")
)

Functions

func BuildMLPackage

func BuildMLPackage(mlpackagePath, mtlpackagePath string) error

BuildMLPackage converts a Core ML model package (.mlpackage) into a Metal 4 machine learning package (.mtlpackage) using Xcode's metal-package-builder.

On macOS 26.6.2, metal.MTLDevice.NewLibraryWithURLError loads .mtlpackage directories produced by metal-package-builder (containing library.mpsgraphpackage and manifest.json); it rejects raw .mlpackage and .mlmodelc directories.

func DispatchBarrier

func DispatchBarrier(enc metal.MTL4ComputeCommandEncoder)

DispatchBarrier inserts a device-visible intra-pass compute dispatch barrier on enc so subsequent dispatches observe writes from earlier dispatches.

Types

type AllocatorPool

type AllocatorPool struct {
	// contains filtered or unexported fields
}

AllocatorPool manages a fixed-size ring of reusable MTL4CommandAllocator and MTL4CommandBuffer pairs synchronized by a single MTLSharedEvent.

An AllocatorPool is not safe for concurrent use by multiple goroutines.

func NewAllocatorPool

func NewAllocatorPool(dev metal.MTLDevice, depth int, label string) (*AllocatorPool, error)

NewAllocatorPool creates a ring of depth reusable command allocators and command buffers on dev. If depth is 0, DefaultRingDepth is used.

func (*AllocatorPool) Acquire

func (p *AllocatorPool) Acquire(timeout time.Duration) (*Slot, error)

Acquire returns the next slot in the ring, waiting up to timeout if the previous submission using that slot is still in flight on the GPU. A non-positive timeout uses DefaultTimeout.

func (*AllocatorPool) AcquireSlot

func (p *AllocatorPool) AcquireSlot(index int, timeout time.Duration) (*Slot, error)

AcquireSlot returns the specific slot at index, waiting up to timeout if its previous submission is still in flight on the GPU. A non-positive timeout uses DefaultTimeout.

func (*AllocatorPool) AllocatedSize

func (p *AllocatorPool) AllocatedSize() uint64

AllocatedSize returns the sum of AllocatedSize across all allocators in the ring.

func (*AllocatorPool) Close

func (p *AllocatorPool) Close() error

Close marks the pool closed and resets all allocators after waiting for any in-flight submissions to finish. Close is idempotent.

func (*AllocatorPool) Commit

func (p *AllocatorPool) Commit(queue metal.MTL4CommandQueue, slot *Slot) (uint64, error)

Commit submits slot's command buffer to queue and signals the pool's shared event with the next monotonic value, returning that signal value.

func (*AllocatorPool) Depth

func (p *AllocatorPool) Depth() int

Depth returns the number of slots in the ring.

func (*AllocatorPool) Drain

func (p *AllocatorPool) Drain(timeout time.Duration) error

Drain waits for all submissions committed through the pool to complete.

func (*AllocatorPool) Event

func (p *AllocatorPool) Event() metal.MTLSharedEvent

Event returns the underlying MTLSharedEvent used to track in-flight slots.

func (*AllocatorPool) LastSignal

func (p *AllocatorPool) LastSignal() uint64

LastSignal returns the highest shared-event value committed through the pool.

func (*AllocatorPool) SlotAllocatedSize

func (p *AllocatorPool) SlotAllocatedSize(index int) uint64

SlotAllocatedSize returns the current allocated size in bytes of slot index, or 0 if index is out of range.

func (*AllocatorPool) Wait

func (p *AllocatorPool) Wait(signal uint64, timeout time.Duration) error

Wait blocks until the pool's shared event reaches signal or timeout elapses. A non-positive timeout uses DefaultTimeout.

type Capabilities

type Capabilities struct {
	DeviceName                   string
	UnifiedMemory                bool
	MaxBufferLength              uint64
	RecommendedMaxWorkingSetSize uint64

	SupportsApple9 bool
	SupportsMetal3 bool
	SupportsMetal4 bool

	CommandQueue           bool
	CommandAllocator       bool
	ArgumentTable          bool
	ComputeEncoder         bool
	ResidencySet           bool
	Tensor                 bool
	MachineLearningEncoder bool

	// Notes records non-fatal probe diagnostics returned by the driver.
	Notes []string
}

Capabilities reports the Metal 4 compute and ML features supported by a device.

func Probe

func Probe(dev metal.MTLDevice) Capabilities

Probe inspects dev and tests each Metal 4 and ML primitive without panicking on nil devices or hosts that do not support Metal 4.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/x/metal4"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	caps := metal4.Probe(dev)
	fmt.Println(caps.DeviceName != "")
}
Output:
true

func (Capabilities) Ready

func (c Capabilities) Ready() bool

Ready reports whether the device supports the core Metal 4 compute fast path (command queue, allocator, argument table, compute encoder, and residency set).

type CommandContext

type CommandContext struct {
	// contains filtered or unexported fields
}

CommandContext owns a Metal 4 command queue, compiler, allocator ring, and residency set for low-overhead compute and ML dispatch loops.

Call CommandContext.Close when finished to detach and end the residency set. A CommandContext is not safe for concurrent use by multiple goroutines.

func NewCommandContext

func NewCommandContext(dev metal.MTLDevice, opts Options) (*CommandContext, error)

NewCommandContext initializes a Metal 4 compute execution context on dev.

Example
package main

import (
	"fmt"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/x/metal4"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	if !metal4.Probe(dev).Ready() {
		fmt.Println("ok")
		return
	}

	ctx, err := metal4.NewCommandContext(dev, metal4.Options{
		RingDepth: 3,
		Label:     "example",
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer ctx.Close()

	slot, err := ctx.Acquire(metal4.DefaultTimeout)
	if err != nil {
		fmt.Println(err)
		return
	}
	slot.Begin()
	enc := slot.CommandBuffer.ComputeCommandEncoder()
	enc.EndEncoding()
	slot.End()
	if err := ctx.CommitAndWait(slot, metal4.DefaultTimeout); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("ok")
}
Output:
ok

func (*CommandContext) Acquire

func (c *CommandContext) Acquire(timeout time.Duration) (*Slot, error)

Acquire returns the next slot in the allocator ring, waiting up to timeout if that slot's previous submission is still in flight.

func (*CommandContext) AcquireSlot

func (c *CommandContext) AcquireSlot(index int, timeout time.Duration) (*Slot, error)

AcquireSlot returns slot index in the allocator ring, waiting up to timeout if that slot's previous submission is still in flight.

func (*CommandContext) AddAllocations

func (c *CommandContext) AddAllocations(allocs ...metal.MTLAllocation) error

AddAllocations registers Metal allocations (buffers, tensors, textures, heaps) with the context's residency set and commits the update.

func (*CommandContext) Close

func (c *CommandContext) Close() error

Close drains in-flight work, detaches and ends the residency set, and closes the allocator pool. Close is idempotent and safe on a nil receiver.

func (*CommandContext) Commit

func (c *CommandContext) Commit(slot *Slot) (uint64, error)

Commit submits slot's recorded command buffer to the context's queue and returns the shared-event signal value tracking its completion.

func (*CommandContext) CommitAndWait

func (c *CommandContext) CommitAndWait(slot *Slot, timeout time.Duration) error

CommitAndWait submits slot's command buffer and waits up to timeout for GPU completion.

func (*CommandContext) Compiler

func (c *CommandContext) Compiler() metal.MTL4Compiler

Compiler returns the underlying MTL4Compiler.

func (*CommandContext) Device

func (c *CommandContext) Device() metal.MTLDevice

Device returns the underlying Metal device.

func (*CommandContext) DispatchML

func (c *CommandContext) DispatchML(p *MLPipeline, args metal.MTL4ArgumentTable, timeout time.Duration) error

DispatchML acquires a command slot, encodes a single ML network dispatch for pipeline p with args, commits it, and waits up to timeout for GPU completion.

func (*CommandContext) Drain

func (c *CommandContext) Drain(timeout time.Duration) error

Drain waits for all in-flight submissions on the context to complete.

func (*CommandContext) NewArgumentTable

func (c *CommandContext) NewArgumentTable(label string, buffers ...metal.MTLBuffer) (metal.MTL4ArgumentTable, error)

NewArgumentTable creates an MTL4ArgumentTable sized for buffers and binds each buffer's GPU address at its corresponding index.

func (*CommandContext) NewArgumentTableWithAddresses

func (c *CommandContext) NewArgumentTableWithAddresses(label string, addrs ...metal.MTLGPUAddress) (metal.MTL4ArgumentTable, error)

NewArgumentTableWithAddresses creates an MTL4ArgumentTable and binds each GPU address at its slice index.

func (*CommandContext) NewComputePipeline

func (c *CommandContext) NewComputePipeline(lib metal.MTLLibrary, fnName string) (metal.MTLComputePipelineState, error)

NewComputePipeline compiles the named compute function from lib using the context's MTL4Compiler.

func (*CommandContext) NewMLPipeline

func (c *CommandContext) NewMLPipeline(lib metal.MTLLibrary, opts MLPipelineOptions) (*MLPipeline, error)

NewMLPipeline compiles a machine learning pipeline state from lib using the context's metal.MTL4Compiler, allocates an intermediates metal.MTLHeap sized to metal.MTL4MachineLearningPipelineState.IntermediatesHeapSize, and registers both in the context's residency set.

func (*CommandContext) NewMLPipelineFromURL

func (c *CommandContext) NewMLPipelineFromURL(path string, opts MLPipelineOptions) (*MLPipeline, error)

NewMLPipelineFromURL loads a Metal ML library from path (typically a .mtlpackage directory built by BuildMLPackage) and compiles an MLPipeline.

func (*CommandContext) Pool

func (c *CommandContext) Pool() *AllocatorPool

Pool returns the context's reusable allocator ring.

func (*CommandContext) Queue

Queue returns the underlying MTL4CommandQueue.

func (*CommandContext) RemoveAllocations

func (c *CommandContext) RemoveAllocations(allocs ...metal.MTLAllocation) error

RemoveAllocations removes Metal allocations from the context's residency set and commits the update.

func (*CommandContext) ResidencySet

func (c *CommandContext) ResidencySet() metal.MTLResidencySet

ResidencySet returns the context's MTLResidencySet attached to the queue.

func (*CommandContext) Wait

func (c *CommandContext) Wait(signal uint64, timeout time.Duration) error

Wait blocks until signal completes on the GPU or timeout elapses.

type MLBinding

type MLBinding struct {
	Name   string
	Index  uint
	Access metal.MTLBindingAccess
	DType  metal.MTLTensorDataType
	// Shape is the logical row-major shape (outermost dimension first).
	Shape []int
}

MLBinding describes an input or output tensor binding reported by metal.MTL4MachineLearningPipelineReflection.

type MLEncoder

type MLEncoder struct {
	// contains filtered or unexported fields
}

MLEncoder wraps an metal.MTL4MachineLearningCommandEncoder for encoding machine learning network dispatches into a Slot's command buffer.

func (*MLEncoder) Barrier

func (e *MLEncoder) Barrier()

Barrier inserts a device-visible intra-pass machine learning barrier so subsequent network dispatches observe writes from earlier dispatches.

func (*MLEncoder) Dispatch

func (e *MLEncoder) Dispatch(p *MLPipeline, args metal.MTL4ArgumentTable) error

Dispatch encodes a single network inference using pipeline p and argument table args.

func (*MLEncoder) End

func (e *MLEncoder) End()

End finishes encoding commands into the machine learning pass. End is idempotent and safe on nil.

func (*MLEncoder) Raw

Raw returns the underlying metal.MTL4MachineLearningCommandEncoder.

type MLPipeline

type MLPipeline struct {
	// contains filtered or unexported fields
}

MLPipeline wraps a compiled metal.MTL4MachineLearningPipelineState, its intermediates metal.MTLHeap, and its reflected tensor bindings.

Call MLPipeline.Close when finished to remove the pipeline and heap from the owning CommandContext's residency set.

func (*MLPipeline) Bindings

func (p *MLPipeline) Bindings() []MLBinding

Bindings returns a copy of the reflected tensor bindings for the pipeline.

func (*MLPipeline) Close

func (p *MLPipeline) Close() error

Close removes the pipeline state and intermediates heap from the owning CommandContext's residency set. Close is idempotent and safe on nil.

func (*MLPipeline) IntermediatesHeap

func (p *MLPipeline) IntermediatesHeap() metal.MTLHeap

IntermediatesHeap returns the metal.MTLHeap allocated for network intermediates.

func (*MLPipeline) IntermediatesHeapSize

func (p *MLPipeline) IntermediatesHeapSize() uint

IntermediatesHeapSize returns the minimum intermediates heap size in bytes reported by the compiled pipeline state.

func (*MLPipeline) NewArgumentTable

func (p *MLPipeline) NewArgumentTable(label string, tensors ...*Tensor) (metal.MTL4ArgumentTable, error)

NewArgumentTable creates an metal.MTL4ArgumentTable and binds each tensor's GPU resource ID at its slice index (0, 1, ...).

func (*MLPipeline) NewArgumentTableByIndex

func (p *MLPipeline) NewArgumentTableByIndex(label string, bindings map[uint]*Tensor) (metal.MTL4ArgumentTable, error)

NewArgumentTableByIndex creates an metal.MTL4ArgumentTable and binds each tensor's GPU resource ID at its specified buffer binding index.

func (*MLPipeline) State

State returns the underlying metal.MTL4MachineLearningPipelineState.

type MLPipelineOptions

type MLPipelineOptions struct {
	// FunctionName names the ML entry-point function inside the Metal library.
	// Empty defaults to the first function reported by the library, or "main".
	FunctionName string

	// InputShapes optionally specifies concrete logical row-major shapes
	// (outermost dimension first) for dynamic input tensors, keyed by buffer
	// binding index.
	InputShapes map[int][]int

	// Label assigns an optional Metal debug label to the pipeline and its
	// intermediates heap.
	Label string
}

MLPipelineOptions configures compilation of an MLPipeline.

type Options

type Options struct {
	// RingDepth is the number of reusable allocator/command-buffer slots.
	// Zero defaults to [DefaultRingDepth].
	RingDepth int

	// ResidencyCapacity is the initial capacity of the context's MTLResidencySet.
	// Zero defaults to 16.
	ResidencyCapacity uint

	// Label prefixes Metal object labels created by the context.
	Label string
}

Options configures a CommandContext. The zero value selects sensible defaults.

type Slot

type Slot struct {
	Index         int
	Allocator     metal.MTL4CommandAllocator
	CommandBuffer metal.MTL4CommandBuffer
	// contains filtered or unexported fields
}

Slot pairs a reusable MTL4CommandAllocator with its MTL4CommandBuffer.

func (*Slot) AllocatedSize

func (s *Slot) AllocatedSize() uint64

AllocatedSize reports the current backing memory size in bytes of the slot's allocator.

func (*Slot) Begin

func (s *Slot) Begin()

Begin resets the slot's command allocator and begins recording into its command buffer.

func (*Slot) End

func (s *Slot) End()

End finishes recording into the slot's command buffer.

func (*Slot) NewMLEncoder

func (s *Slot) NewMLEncoder() (*MLEncoder, error)

NewMLEncoder begins a machine learning pass on the slot's command buffer. Call Slot.Begin before NewMLEncoder and MLEncoder.End before Slot.End.

type Tensor

type Tensor struct {
	// contains filtered or unexported fields
}

Tensor wraps a Metal 4 metal.MTLTensor and its optional backing metal.MTLBuffer, registering both in the owning CommandContext's residency set.

Shapes use standard row-major ordering (outermost dimension first, e.g. [batch, features]). Internally, Metal's metal.MTLTensorExtents stores the innermost (contiguous) dimension at index 0; Tensor converts automatically.

Call Tensor.Close when finished to remove the tensor from the residency set. A Tensor's zero value is not usable.

func NewTensor

func NewTensor(ctx *CommandContext, shape []int, dtype metal.MTLTensorDataType, opts TensorOptions) (*Tensor, error)

NewTensor creates a Metal 4 tensor registered with ctx's residency set.

shape is in row-major order (outermost dimension first). Every dimension must be positive; an empty shape creates a rank-0 scalar tensor.

func (*Tensor) AllocatedSize

func (t *Tensor) AllocatedSize() uint

AllocatedSize returns the GPU memory footprint reported by Metal in bytes.

func (*Tensor) Buffer

func (t *Tensor) Buffer() metal.MTLBuffer

Buffer returns the underlying metal.MTLBuffer if the tensor was created with TensorOptions.BufferBacked, or nil for standalone tensors.

func (*Tensor) ByteSize

func (t *Tensor) ByteSize() int

ByteSize returns the packed byte size of the tensor's logical elements.

func (*Tensor) Bytes

func (t *Tensor) Bytes() []byte

Bytes returns the tensor's byte contents for shared-storage tensors.

For buffer-backed shared tensors, Bytes returns a direct zero-copy slice over the backing MTLBuffer's shared memory (note that ML-usage buffer-backed tensors with rank >= 2 may include 64-byte row alignment padding; use Tensor.ReadBytes or Tensor.ReadFloat32 for dense row-major access). For standalone shared tensors, Bytes reads and returns a dense copy of length Tensor.ByteSize. For private or closed tensors, Bytes returns nil.

func (*Tensor) Close

func (t *Tensor) Close() error

Close removes the tensor (and its backing buffer, if any) from the owning CommandContext's residency set. Close is idempotent and safe on nil.

func (*Tensor) DType

func (t *Tensor) DType() metal.MTLTensorDataType

DType returns the tensor's element data type.

func (*Tensor) NumElements

func (t *Tensor) NumElements() int

NumElements returns the total number of elements in the tensor.

func (*Tensor) Raw

func (t *Tensor) Raw() metal.MTLTensor

Raw returns the underlying metal.MTLTensor.

func (*Tensor) ReadBytes

func (t *Tensor) ReadBytes(dst []byte) error

ReadBytes copies packed row-major bytes from the tensor into dst. The tensor must have shared storage mode and len(dst) must equal Tensor.ByteSize.

func (*Tensor) ReadFloat32

func (t *Tensor) ReadFloat32(dst []float32) error

ReadFloat32 copies a float32 shared tensor into dst in row-major order.

func (*Tensor) ResourceID

func (t *Tensor) ResourceID() metal.MTLResourceID

ResourceID returns the tensor's metal.MTLResourceID for binding into an metal.MTL4ArgumentTable.

func (*Tensor) Shape

func (t *Tensor) Shape() []int

Shape returns a copy of the tensor's logical row-major shape.

func (*Tensor) Usage

func (t *Tensor) Usage() metal.MTLTensorUsage

Usage returns the tensor's Metal usage flags.

func (*Tensor) WriteBytes

func (t *Tensor) WriteBytes(src []byte) error

WriteBytes copies packed row-major bytes from src into the tensor. The tensor must have shared storage mode and len(src) must equal Tensor.ByteSize.

func (*Tensor) WriteFloat32

func (t *Tensor) WriteFloat32(src []float32) error

WriteFloat32 copies a row-major float32 slice into a float32 shared tensor.

type TensorOptions

type TensorOptions struct {
	// Usage specifies the Metal tensor usage flags. Zero defaults to
	// MTLTensorUsageMachineLearning | MTLTensorUsageCompute.
	Usage metal.MTLTensorUsage

	// StorageMode specifies the storage mode of the tensor. Zero defaults to
	// MTLStorageModeShared.
	StorageMode metal.MTLStorageMode

	// BufferBacked allocates an explicit backing MTLBuffer and creates the
	// tensor as a strided view over it, making [Tensor.Buffer] non-nil and
	// [Tensor.Bytes] zero-copy when StorageMode is MTLStorageModeShared.
	//
	// When Usage includes MTLTensorUsageMachineLearning and rank >= 2, Metal
	// requires the second stride (row stride) to be aligned to 64 bytes;
	// NewTensor computes that stride automatically.
	BufferBacked bool

	// Label assigns an optional Metal debug label to the tensor.
	Label string
}

TensorOptions configures a Tensor. The zero value selects shared storage with both compute and machine learning usage enabled.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL