Documentation
¶
Overview ¶
Package metalcache provides a zero-cgo wrapper around Metal's pipeline binary caching APIs (metal.MTLBinaryArchive and, on Metal 4 devices, metal.MTL4PipelineDataSetSerializer and metal.MTL4Archive).
Cache entries are keyed by Key, computed by CacheKey from the GPU device name, macOS build version, SHA-256 of the Metal Shading Language (MSL) source, and any specialization constants or compile options. When an on-disk archive does not match the requested key or fails to load, Open automatically invalidates the stale files and starts a fresh archive. Serialization writes through a temporary file and atomic rename so concurrent readers never observe a partial archive.
Basic usage:
dev := metal.MTLCreateSystemDefaultDevice()
key, err := metalcache.CacheKey(dev, mslSource, metalcache.KeyOptions{Label: "kernels"})
if err != nil {
return err
}
arch, err := metalcache.Open(dev, cacheDir, key)
if err != nil {
return err
}
defer arch.Close()
if !arch.Loaded() {
if err := arch.AddComputePipeline(desc); err != nil {
return err
}
if err := arch.Serialize(); err != nil {
return err
}
}
pso, err := arch.NewComputePipeline(desc)
The zero values of Archive and Metal4Archive are not usable; create them with Open or OpenMetal4 and release the underlying Metal handles with Close.
Example ¶
package main
import (
"fmt"
"os"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/objectivec"
"github.com/tmc/apple/x/metalcache"
)
const exampleMSL = `
#include <metal_stdlib>
using namespace metal;
kernel void scale_f32(device const float *in [[buffer(0)]],
device float *out [[buffer(1)]],
uint id [[thread_position_in_grid]]) {
out[id] = in[id] * 2.0f;
}
`
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
fmt.Println("cold=false warm=true")
return
}
dir, err := os.MkdirTemp("", "metalcache-example-*")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
key, err := metalcache.CacheKey(dev, exampleMSL, metalcache.KeyOptions{Label: "scale"})
if err != nil {
fmt.Println(err)
return
}
lib, err := dev.NewLibraryWithSourceOptionsError(exampleMSL, nil)
if err != nil {
fmt.Println(err)
return
}
defer objectivec.ObjectFromID(lib.GetID()).Release()
fn := lib.NewFunctionWithName("scale_f32")
defer objectivec.ObjectFromID(fn.GetID()).Release()
desc := metal.NewMTLComputePipelineDescriptor()
defer desc.Release()
desc.SetComputeFunction(fn)
cold, err := metalcache.Open(dev, dir, key)
if err != nil {
fmt.Println(err)
return
}
coldLoaded := cold.Loaded()
if err := cold.AddComputePipeline(desc); err != nil {
fmt.Println(err)
return
}
if err := cold.Serialize(); err != nil {
fmt.Println(err)
return
}
cold.Close()
warm, err := metalcache.Open(dev, dir, key)
if err != nil {
fmt.Println(err)
return
}
defer warm.Close()
pso, err := warm.NewComputePipelineStrict(desc)
if err != nil {
fmt.Println(err)
return
}
defer objectivec.ObjectFromID(pso.GetID()).Release()
fmt.Printf("cold=%v warm=%v\n", coldLoaded, warm.Loaded())
}
Output: cold=false warm=true
Index ¶
- Variables
- func SupportsMetal4(dev metal.MTLDevice) bool
- type Archive
- func (a *Archive) AddComputePipeline(desc metal.IMTLComputePipelineDescriptor) error
- func (a *Archive) Close() error
- func (a *Archive) Invalidated() bool
- func (a *Archive) Key() Key
- func (a *Archive) Loaded() bool
- func (a *Archive) NewComputePipeline(desc metal.IMTLComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
- func (a *Archive) NewComputePipelineStrict(desc metal.IMTLComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
- func (a *Archive) Path() string
- func (a *Archive) Raw() metal.MTLBinaryArchive
- func (a *Archive) Serialize() error
- type Key
- type KeyOptions
- type Metal4Archive
- func (m *Metal4Archive) Archive() metal.MTL4Archive
- func (m *Metal4Archive) Close() error
- func (m *Metal4Archive) Compiler() metal.MTL4Compiler
- func (m *Metal4Archive) Invalidated() bool
- func (m *Metal4Archive) Key() Key
- func (m *Metal4Archive) Loaded() bool
- func (m *Metal4Archive) NewComputePipeline(desc metal.IMTL4ComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
- func (m *Metal4Archive) NewComputePipelineFromArchive(desc metal.IMTL4ComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
- func (m *Metal4Archive) Path() string
- func (m *Metal4Archive) Serialize() error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("metalcache: archive closed")
ErrClosed is returned when an operation is attempted on a closed archive.
var ErrMetal4Unsupported = errors.New("metalcache: device does not support Metal 4")
ErrMetal4Unsupported is returned by OpenMetal4 when the Metal device does not support metal.MTLGPUFamilyMetal4.
Functions ¶
func SupportsMetal4 ¶
SupportsMetal4 reports whether dev supports Metal 4 pipeline archiving (metal.MTL4PipelineDataSetSerializer and metal.MTL4Archive).
Types ¶
type Archive ¶
type Archive struct {
// contains filtered or unexported fields
}
Archive wraps an metal.MTLBinaryArchive backed by a keyed file on disk.
Archive is safe for concurrent use by multiple goroutines.
func Open ¶
Open opens or creates a binary pipeline archive in dir keyed by key.
If an archive exists in dir for key's slot and its metadata matches key, Open loads it from disk (Archive.Loaded returns true). If the metadata does not match key (for example after an MSL edit, GPU change, or macOS update) or the archive file is corrupt, Open removes the stale files, marks Archive.Invalidated, and creates a fresh empty archive.
func (*Archive) AddComputePipeline ¶
func (a *Archive) AddComputePipeline(desc metal.IMTLComputePipelineDescriptor) error
AddComputePipeline compiles and adds the compute pipeline described by desc to the archive in memory. Call Archive.Serialize to persist added pipelines to disk.
func (*Archive) Close ¶
Close releases the underlying metal.MTLBinaryArchive. Calling Close more than once is a no-op.
func (*Archive) Invalidated ¶
Invalidated reports whether Open discarded a stale or corrupt archive before creating a fresh one.
func (*Archive) NewComputePipeline ¶
func (a *Archive) NewComputePipeline(desc metal.IMTLComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
NewComputePipeline creates a compute pipeline state from desc using this archive as a binary lookup cache. If the pipeline is not present in the archive, Metal compiles it normally.
func (*Archive) NewComputePipelineStrict ¶
func (a *Archive) NewComputePipelineStrict(desc metal.IMTLComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
NewComputePipelineStrict creates a compute pipeline state from desc and fails with an error if the compiled binary is not present in the archive (metal.MTLPipelineOptionFailOnBinaryArchiveMiss).
func (*Archive) Raw ¶
func (a *Archive) Raw() metal.MTLBinaryArchive
Raw returns the underlying metal.MTLBinaryArchive.
type Key ¶
type Key struct {
// Digest is the lowercase hex SHA-256 digest of all key inputs.
Digest string `json:"digest"`
// Label is the optional cache slot label from KeyOptions.
Label string `json:"label,omitempty"`
// GPUName is the Metal device name reported by MTLDevice.Name.
GPUName string `json:"gpu_name"`
// OSBuild is the macOS product version and build identifier.
OSBuild string `json:"os_build"`
// SourceSHA256 is the lowercase hex SHA-256 of the MSL source.
SourceSHA256 string `json:"source_sha256"`
}
Key identifies a compiled Metal pipeline archive for a specific GPU, macOS build, MSL source, and specialization options.
func CacheKey ¶
CacheKey computes a deterministic Key for dev, mslSource, and opts.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalcache"
)
const exampleMSL = `
#include <metal_stdlib>
using namespace metal;
kernel void scale_f32(device const float *in [[buffer(0)]],
device float *out [[buffer(1)]],
uint id [[thread_position_in_grid]]) {
out[id] = in[id] * 2.0f;
}
`
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
fmt.Println("same=true diff=true")
return
}
k1, err := metalcache.CacheKey(dev, exampleMSL, metalcache.KeyOptions{
Label: "scale",
Constants: map[string]string{"TILE": "16"},
})
if err != nil {
fmt.Println(err)
return
}
k2, err := metalcache.CacheKey(dev, exampleMSL, metalcache.KeyOptions{
Label: "scale",
Constants: map[string]string{"TILE": "16"},
})
if err != nil {
fmt.Println(err)
return
}
k3, err := metalcache.CacheKey(dev, exampleMSL, metalcache.KeyOptions{
Label: "scale",
Constants: map[string]string{"TILE": "32"},
})
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("same=%v diff=%v\n", k1.Digest == k2.Digest, k1.Digest != k3.Digest)
}
Output: same=true diff=true
type KeyOptions ¶
type KeyOptions struct {
// Label distinguishes independent archives stored in the same directory.
// When empty, the default slot name "archive" is used.
Label string
// Constants maps specialization constant names or indices to their
// canonical string values. Map keys are sorted before hashing.
Constants map[string]string
// Extra appends caller-defined discriminators (such as compiler flags
// or math mode settings) to the key hash.
Extra []string
}
KeyOptions configures additional inputs folded into a Key.
type Metal4Archive ¶
type Metal4Archive struct {
// contains filtered or unexported fields
}
Metal4Archive wraps a Metal 4 metal.MTL4Compiler paired with an metal.MTL4PipelineDataSetSerializer (for recording compiled pipelines) and an optional on-disk metal.MTL4Archive (for fast reloads).
Metal4Archive is safe for concurrent use by multiple goroutines.
func OpenMetal4 ¶
OpenMetal4 opens or creates a Metal 4 pipeline archive in dir keyed by key.
If dev does not support Metal 4, OpenMetal4 returns ErrMetal4Unsupported. When a valid on-disk archive matches key, OpenMetal4 loads it as an metal.MTL4Archive (Metal4Archive.Loaded returns true). Stale or corrupt files are automatically removed (Metal4Archive.Invalidated returns true).
func (*Metal4Archive) Archive ¶
func (m *Metal4Archive) Archive() metal.MTL4Archive
Archive returns the loaded metal.MTL4Archive, or nil if none was loaded.
func (*Metal4Archive) Close ¶
func (m *Metal4Archive) Close() error
Close releases the underlying Metal 4 compiler, serializer, and archive objects. Calling Close more than once is a no-op.
func (*Metal4Archive) Compiler ¶
func (m *Metal4Archive) Compiler() metal.MTL4Compiler
Compiler returns the underlying metal.MTL4Compiler attached to the serializer.
func (*Metal4Archive) Invalidated ¶
func (m *Metal4Archive) Invalidated() bool
Invalidated reports whether OpenMetal4 discarded a stale or corrupt archive.
func (*Metal4Archive) Key ¶
func (m *Metal4Archive) Key() Key
Key returns the cache key associated with this Metal 4 archive.
func (*Metal4Archive) Loaded ¶
func (m *Metal4Archive) Loaded() bool
Loaded reports whether OpenMetal4 loaded an existing valid archive from disk.
func (*Metal4Archive) NewComputePipeline ¶
func (m *Metal4Archive) NewComputePipeline(desc metal.IMTL4ComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
NewComputePipeline creates a compute pipeline state from desc.
If an metal.MTL4Archive was loaded from disk, it first attempts to instantiate the pipeline directly from the archive. On a miss, it compiles the pipeline through the Metal 4 compiler (recording the compiled binary into the serializer for subsequent Metal4Archive.Serialize).
func (*Metal4Archive) NewComputePipelineFromArchive ¶
func (m *Metal4Archive) NewComputePipelineFromArchive(desc metal.IMTL4ComputePipelineDescriptor) (metal.MTLComputePipelineState, error)
NewComputePipelineFromArchive instantiates a compute pipeline state strictly from the loaded metal.MTL4Archive without falling back to compilation.
func (*Metal4Archive) Path ¶
func (m *Metal4Archive) Path() string
Path returns the on-disk path of the serialized Metal 4 archive.
func (*Metal4Archive) Serialize ¶
func (m *Metal4Archive) Serialize() error
Serialize flushes all pipelines compiled by this archive's Metal 4 compiler to disk atomically via a temporary file and os.Rename.