Documentation
¶
Overview ¶
Package metal provides high-level Metal compute ergonomics built on github.com/tmc/apple/metal.
It offers:
- Device for managing a Metal device and default command queue
- Compiler for compiling and caching compute pipelines by source digest
- SetScalar, Threads, and Threadgroups for safe kernel dispatch
- WaitCommandBuffer and CommandBufferError for terminal wait handling
- GPUTiming and CommandBufferTiming for zero-overhead GPU timestamps
- StartCapture and CaptureSession for programmatic .gputrace capture
Basic usage:
dev, err := metal.NewDevice()
if err != nil {
return err
}
defer dev.Close()
compiler, err := metal.NewCompiler(dev.Raw())
if err != nil {
return err
}
defer compiler.Close()
pso, err := compiler.Compile(mslSource, "my_kernel")
if err != nil {
return err
}
The zero values of Device, Compiler, and CaptureSession are not usable; construct them with NewDevice/WrapDevice, NewCompiler, and StartCapture respectively.
Related Packages ¶
Sibling packages under github.com/tmc/apple/x accept github.com/tmc/apple/metal.MTLDevice directly (obtained via Device.Raw) and cover specialized Metal features:
- github.com/tmc/apple/x/metal4: Metal 4 command buffers, tensors, and residency
- github.com/tmc/apple/x/metalcache: on-disk MTLBinaryArchive pipeline caching
- github.com/tmc/apple/x/metalcounters: GPU hardware counter sampling
- github.com/tmc/apple/x/metalheap: MTLHeap sub-allocation and residency sets
- github.com/tmc/apple/x/metalicb: indirect command buffer graphs
- github.com/tmc/apple/x/metalio: Metal fast resource loading (MTLIOCommandQueue)
- github.com/tmc/apple/x/metalmem: typed unified-memory buffers, arenas, and tracking
- github.com/tmc/apple/x/gpureplay: headless MTLReplayer trace profiling
Index ¶
- Variables
- func SetScalar[T Scalar](enc apple.MTLComputeCommandEncoder, v T, index int)
- func Threadgroups(n, group int) apple.MTLSize
- func Threads(n int) apple.MTLSize
- func WaitCommandBuffer(cb apple.MTLCommandBuffer) error
- type CaptureSession
- type CommandBufferError
- type CommandBufferFailure
- type CommandBufferTiming
- type Compiler
- type Device
- func (d *Device) AllocBuffer(bytes int) (apple.MTLBuffer, error)
- func (d *Device) AllocBufferBytes(data []byte) (apple.MTLBuffer, error)
- func (d *Device) Close() error
- func (d *Device) CompileLibrary(source string) (apple.MTLLibrary, error)
- func (d *Device) Name() string
- func (d *Device) NewComputePipeline(lib apple.MTLLibrary, name string) (apple.MTLComputePipelineState, error)
- func (d *Device) Queue() apple.MTLCommandQueue
- func (d *Device) Raw() apple.MTLDevice
- type Scalar
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("metal: closed")
ErrClosed is returned by operations on a closed Device or Compiler.
Functions ¶
func SetScalar ¶
func SetScalar[T Scalar](enc apple.MTLComputeCommandEncoder, v T, index int)
SetScalar binds v into enc's argument table at index. Kernel scalars are small and change on every dispatch, so copying them inline is cheaper than allocating a buffer per argument per dispatch. It is a no-op if enc is nil, uninitialized, or index is negative.
func Threadgroups ¶
Threadgroups returns the one-dimensional size covering n threads in groups of group threads each, rounding up so a partial final group still runs. A group below one is treated as one.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/metal"
)
func main() {
groups := metal.Threadgroups(1000, 64)
fmt.Println(groups.Width, groups.Height, groups.Depth)
}
Output: 16 1 1
func Threads ¶
Threads returns the one-dimensional size covering n threads, for dispatching by thread count. An n below one becomes one: Metal rejects an empty grid.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/metal"
)
func main() {
size := metal.Threads(256)
fmt.Println(size.Width, size.Height, size.Depth)
}
Output: 256 1 1
func WaitCommandBuffer ¶
func WaitCommandBuffer(cb apple.MTLCommandBuffer) error
WaitCommandBuffer waits until Metal reaches a terminal status and returns an error if the command buffer did not complete successfully.
Types ¶
type CaptureSession ¶
type CaptureSession struct {
// contains filtered or unexported fields
}
CaptureSession tracks an active programmatic Metal GPU trace capture. The zero value is not usable; start a session with StartCapture and stop it with CaptureSession.Close.
func StartCapture ¶
func StartCapture(dev apple.MTLDevice, outputPath string) (*CaptureSession, error)
StartCapture initiates programmatic capture of Metal GPU workloads on dev to a .gputrace directory at outputPath.
Metal only inserts the capture layer when the process starts with MTL_CAPTURE_ENABLED=1 in its environment; without it StartCapture reports that the capture layer is not enabled. Only one capture session may be active per process at a time.
func (*CaptureSession) Close ¶
func (cs *CaptureSession) Close() error
Close terminates the active GPU capture session and flushes the .gputrace archive to disk. It is idempotent and safe to call on a nil receiver.
type CommandBufferError ¶
type CommandBufferError struct {
Failure CommandBufferFailure
Status apple.MTLCommandBufferStatus
DeviceTerminal bool
DetailAvailable bool
DeviceErrorCode int
DeviceErrorDomain string
DeviceErrorText string
// contains filtered or unexported fields
}
CommandBufferError reports why a committed command buffer did not produce a usable result. DeviceTerminal is true once Metal has reached a terminal status (Completed or Error).
func (*CommandBufferError) Error ¶
func (e *CommandBufferError) Error() string
type CommandBufferFailure ¶
type CommandBufferFailure uint8
CommandBufferFailure classifies an unsuccessful command buffer wait.
const ( CommandBufferFailed CommandBufferFailure = iota + 1 CommandBufferDeviceTimeout CommandBufferUnexpectedStatus )
func (CommandBufferFailure) String ¶
func (f CommandBufferFailure) String() string
String returns a human-readable name for f.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/metal"
)
func main() {
fmt.Println(metal.CommandBufferDeviceTimeout)
}
Output: device timeout
type CommandBufferTiming ¶
type CommandBufferTiming struct {
Start time.Duration // GPUStartTime, relative to an arbitrary origin
End time.Duration // GPUEndTime, on the same origin as Start
}
CommandBufferTiming is the GPU execution window of one completed command buffer, as reported by Metal itself.
func GPUTiming ¶
func GPUTiming(cb apple.MTLCommandBuffer) (CommandBufferTiming, bool)
GPUTiming reports the GPU execution window of a completed command buffer and whether the window is valid.
The timestamps come from Metal's own GPUStartTime and GPUEndTime, so unlike a capture they cost nothing and do not perturb what they measure. Call it after the command buffer has completed; before that both timestamps are zero and ok is false.
Subtracting this from wall-clock time around a submission attributes the remainder to host work: allocation, encoding, submission, and copy-back.
func (CommandBufferTiming) GPU ¶
func (t CommandBufferTiming) GPU() time.Duration
GPU reports how long the GPU spent executing the command buffer.
func (CommandBufferTiming) Valid ¶
func (t CommandBufferTiming) Valid() bool
Valid reports whether the timing describes a real execution window. Metal leaves both timestamps at zero for a command buffer that has not completed, and a scheduling error can leave End before Start.
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler owns compute pipelines compiled for one Metal device. Pipelines returned by Compiler.Compile are borrowed and remain valid until Compiler.Close. The device must outlive the Compiler. The zero value is not usable. Compiler methods are safe for concurrent use.
func NewCompiler ¶
NewCompiler returns a pipeline compiler bound to dev.
func (*Compiler) Close ¶
Close releases cached pipelines and prevents new compilation. It is idempotent and waits for an in-progress Compiler.Compile call. Callers must finish submitted work using borrowed pipelines before calling Close.
func (*Compiler) Compile ¶
func (c *Compiler) Compile(source, kernelName string) (apple.MTLComputePipelineState, error)
Compile compiles source and returns the named compute pipeline, caching the result by the SHA-256 digest of source and kernelName. Cache identity is scoped to the Compiler's Metal device.
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device represents an Apple Metal GPU device and its default command queue. The zero value is not usable; construct one with NewDevice or WrapDevice.
func WrapDevice ¶
WrapDevice adopts an existing Metal device, retaining it and creating a command queue so that Device.Close can safely release its own reference without invalidating the caller's reference.
func (*Device) AllocBuffer ¶
AllocBuffer allocates a shared Metal buffer owned by the caller. A negative byte count returns an error. A byte count of 0 allocates a 4-byte placeholder buffer because Metal rejects zero-length buffers.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/objectivec"
"github.com/tmc/apple/x/metal"
)
func main() {
dev, err := metal.NewDevice()
if err != nil {
fmt.Println(err)
return
}
defer dev.Close()
buf, err := dev.AllocBuffer(16)
if err != nil {
fmt.Println(err)
return
}
defer objectivec.ObjectFromID(buf.GetID()).Release()
fmt.Println(buf.Length())
}
Output: 16
func (*Device) AllocBufferBytes ¶
AllocBufferBytes copies host data into a shared Metal buffer owned by the caller. If data is empty, it allocates a 4-byte placeholder buffer.
func (*Device) Close ¶
Close releases the command queue and Metal device. It is idempotent. The caller must complete all command buffers and release device-derived objects before calling Close. Close waits for Device methods already in progress; borrowed values returned by Device.Raw and Device.Queue must not be used concurrently with Close.
func (*Device) CompileLibrary ¶
func (d *Device) CompileLibrary(source string) (apple.MTLLibrary, error)
CompileLibrary compiles MSL source into a library owned by the caller. The caller must release the library after creating its functions and pipelines.
func (*Device) Name ¶
Name returns the device name, or an empty string if the device is nil or closed.
func (*Device) NewComputePipeline ¶
func (d *Device) NewComputePipeline(lib apple.MTLLibrary, name string) (apple.MTLComputePipelineState, error)
NewComputePipeline creates a pipeline owned by the caller. The temporary function used to create the pipeline is released before the method returns.
func (*Device) Queue ¶
func (d *Device) Queue() apple.MTLCommandQueue
Queue returns the device's borrowed default command queue. It returns nil after Device.Close. Before Close it is non-nil because NewDevice and WrapDevice reject a device that cannot create a queue. The result must not be used concurrently with Close.
type Scalar ¶
type Scalar interface {
~int8 | ~uint8 |
~int16 | ~uint16 |
~int32 | ~uint32 |
~int64 | ~uint64 |
~float32
}
Scalar is the set of types a Metal kernel scalar argument may have.
Go's int, uint, and float64 are deliberately absent. Go's int and uint are 64 bits wide on Apple silicon while MSL's int and uint are 32, and MSL has no double (float64) type on Apple GPUs. Convert to a fixed-width MSL-compatible type at the call site instead.