Documentation
¶
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 ¶
- Constants
- Variables
- func BuildMLPackage(mlpackagePath, mtlpackagePath string) error
- func DispatchBarrier(enc metal.MTL4ComputeCommandEncoder)
- type AllocatorPool
- func (p *AllocatorPool) Acquire(timeout time.Duration) (*Slot, error)
- func (p *AllocatorPool) AcquireSlot(index int, timeout time.Duration) (*Slot, error)
- func (p *AllocatorPool) AllocatedSize() uint64
- func (p *AllocatorPool) Close() error
- func (p *AllocatorPool) Commit(queue metal.MTL4CommandQueue, slot *Slot) (uint64, error)
- func (p *AllocatorPool) Depth() int
- func (p *AllocatorPool) Drain(timeout time.Duration) error
- func (p *AllocatorPool) Event() metal.MTLSharedEvent
- func (p *AllocatorPool) LastSignal() uint64
- func (p *AllocatorPool) SlotAllocatedSize(index int) uint64
- func (p *AllocatorPool) Wait(signal uint64, timeout time.Duration) error
- type Capabilities
- type CommandContext
- func (c *CommandContext) Acquire(timeout time.Duration) (*Slot, error)
- func (c *CommandContext) AcquireSlot(index int, timeout time.Duration) (*Slot, error)
- func (c *CommandContext) AddAllocations(allocs ...metal.MTLAllocation) error
- func (c *CommandContext) Close() error
- func (c *CommandContext) Commit(slot *Slot) (uint64, error)
- func (c *CommandContext) CommitAndWait(slot *Slot, timeout time.Duration) error
- func (c *CommandContext) Compiler() metal.MTL4Compiler
- func (c *CommandContext) Device() metal.MTLDevice
- func (c *CommandContext) DispatchML(p *MLPipeline, args metal.MTL4ArgumentTable, timeout time.Duration) error
- func (c *CommandContext) Drain(timeout time.Duration) error
- func (c *CommandContext) NewArgumentTable(label string, buffers ...metal.MTLBuffer) (metal.MTL4ArgumentTable, error)
- func (c *CommandContext) NewArgumentTableWithAddresses(label string, addrs ...metal.MTLGPUAddress) (metal.MTL4ArgumentTable, error)
- func (c *CommandContext) NewComputePipeline(lib metal.MTLLibrary, fnName string) (metal.MTLComputePipelineState, error)
- func (c *CommandContext) NewMLPipeline(lib metal.MTLLibrary, opts MLPipelineOptions) (*MLPipeline, error)
- func (c *CommandContext) NewMLPipelineFromURL(path string, opts MLPipelineOptions) (*MLPipeline, error)
- func (c *CommandContext) Pool() *AllocatorPool
- func (c *CommandContext) Queue() metal.MTL4CommandQueue
- func (c *CommandContext) RemoveAllocations(allocs ...metal.MTLAllocation) error
- func (c *CommandContext) ResidencySet() metal.MTLResidencySet
- func (c *CommandContext) Wait(signal uint64, timeout time.Duration) error
- type MLBinding
- type MLEncoder
- type MLPipeline
- func (p *MLPipeline) Bindings() []MLBinding
- func (p *MLPipeline) Close() error
- func (p *MLPipeline) IntermediatesHeap() metal.MTLHeap
- func (p *MLPipeline) IntermediatesHeapSize() uint
- func (p *MLPipeline) NewArgumentTable(label string, tensors ...*Tensor) (metal.MTL4ArgumentTable, error)
- func (p *MLPipeline) NewArgumentTableByIndex(label string, bindings map[uint]*Tensor) (metal.MTL4ArgumentTable, error)
- func (p *MLPipeline) State() metal.MTL4MachineLearningPipelineState
- type MLPipelineOptions
- type Options
- type Slot
- type Tensor
- func (t *Tensor) AllocatedSize() uint
- func (t *Tensor) Buffer() metal.MTLBuffer
- func (t *Tensor) ByteSize() int
- func (t *Tensor) Bytes() []byte
- func (t *Tensor) Close() error
- func (t *Tensor) DType() metal.MTLTensorDataType
- func (t *Tensor) NumElements() int
- func (t *Tensor) Raw() metal.MTLTensor
- func (t *Tensor) ReadBytes(dst []byte) error
- func (t *Tensor) ReadFloat32(dst []float32) error
- func (t *Tensor) ResourceID() metal.MTLResourceID
- func (t *Tensor) Shape() []int
- func (t *Tensor) Usage() metal.MTLTensorUsage
- func (t *Tensor) WriteBytes(src []byte) error
- func (t *Tensor) WriteFloat32(src []float32) error
- type TensorOptions
Examples ¶
Constants ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
func (c *CommandContext) Queue() metal.MTL4CommandQueue
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.
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 ¶
func (e *MLEncoder) Raw() metal.MTL4MachineLearningCommandEncoder
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 ¶
func (p *MLPipeline) State() metal.MTL4MachineLearningPipelineState
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 ¶
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) NewMLEncoder ¶
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 ¶
AllocatedSize returns the GPU memory footprint reported by Metal in bytes.
func (*Tensor) Buffer ¶
Buffer returns the underlying metal.MTLBuffer if the tensor was created with TensorOptions.BufferBacked, or nil for standalone tensors.
func (*Tensor) Bytes ¶
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 ¶
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 ¶
NumElements returns the total number of elements in the tensor.
func (*Tensor) Raw ¶
Raw returns the underlying metal.MTLTensor.
func (*Tensor) ReadBytes ¶
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 ¶
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) Usage ¶
func (t *Tensor) Usage() metal.MTLTensorUsage
Usage returns the tensor's Metal usage flags.
func (*Tensor) WriteBytes ¶
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 ¶
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.