Documentation
¶
Overview ¶
Package metalmem provides typed unified-memory slices, zero-copy file mappings, arena lifetimes, and allocation accounting for Apple Metal GPUs.
All constructors accept a raw metal.MTLDevice directly and allocate in shared unified memory (metal.MTLResourceStorageModeShared).
Basic usage:
dev := metal.MTLCreateSystemDefaultDevice()
s, err := metalmem.AllocFromSlice(dev, []float32{1, 2, 3, 4})
if err != nil {
return err
}
defer s.Close()
enc.SetBufferWithOffsetAtIndex(s.Buffer(), s.Offset(), 0)
Use AllocMMapZeroCopy to map a file into a Metal buffer without copying; the underlying mapping is unmapped from Metal's buffer deallocator once the GPU has finished with it.
Use Arena to group allocations that share a single error check and lifetime, and Tracker to record explicit byte and allocation counts.
The zero Slice is valid, empty, and binds a nil buffer. The zero Tracker is ready for concurrent use. The zero Arena is not usable; construct one with NewArena or NewTrackedArena.
Index ¶
- type Arena
- type Element
- type Slice
- func Alloc[T Element](dev metal.MTLDevice, count int) (Slice[T], error)
- func AllocFromSlice[T Element](dev metal.MTLDevice, data []T) (Slice[T], error)
- func AllocIn[T Element](a *Arena, count int) Slice[T]
- func AllocMMapZeroCopy[T Element](dev metal.MTLDevice, f *os.File, offset int64, count int) (Slice[T], error)
- func UploadIn[T Element](a *Arena, data []T) Slice[T]
- func (s Slice[T]) Buffer() metal.MTLBuffer
- func (s Slice[T]) ByteLen() int
- func (s Slice[T]) Cap() int
- func (s Slice[T]) Close() error
- func (s Slice[T]) CopyFromHost(src []T) error
- func (s Slice[T]) CopyToHost(dst []T) error
- func (s Slice[T]) HostSlice() []T
- func (s Slice[T]) Len() int
- func (s Slice[T]) Offset() uint
- func (s Slice[T]) Slice(low, high int) (Slice[T], error)
- type Tracker
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Arena ¶
type Arena struct {
// contains filtered or unexported fields
}
Arena groups allocations that share a lifetime. Allocations made through AllocIn and UploadIn are checked once with Arena.Err and released together by Arena.Close, so a structure holding many buffers needs one error check and one cleanup path.
The zero Arena is not usable; obtain one from NewArena or NewTrackedArena. An Arena is not safe for concurrent use.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalmem"
)
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
return
}
var tracker metalmem.Tracker
a, err := metalmem.NewTrackedArena(dev, &tracker)
if err != nil {
fmt.Println(err)
return
}
defer a.Close()
weights := metalmem.UploadIn(a, []float32{1, 2, 3, 4})
scratch := metalmem.AllocIn[float32](a, 8)
if err := a.Err(); err != nil {
fmt.Println(err)
return
}
fmt.Printf("weights=%d scratch=%d bytes=%d live=%d\n",
weights.Len(), scratch.Len(), tracker.AllocatedBytes(), tracker.LiveAllocations())
}
Output: weights=4 scratch=8 bytes=48 live=2
func NewTrackedArena ¶
NewTrackedArena returns an Arena whose successful allocations are charged to tracker until their shared Slice owner is closed. If tracker is nil, allocations are untracked.
func (*Arena) Close ¶
Close releases every allocation the arena still holds, in reverse allocation order. Close is idempotent and safe to call on a nil Arena.
type Element ¶
type Element interface {
~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~float32 | ~float64
}
Element constrains Slice to fixed-width numeric types containing no Go pointers.
Platform-sized int and uint are excluded because Metal Shading Language uses fixed-width integer types.
type Slice ¶
type Slice[T Element] struct { // contains filtered or unexported fields }
Slice is a typed, contiguous run of elements in Apple unified memory.
A Slice is a value: copying one shares the underlying MTLBuffer rather than duplicating it, and so does Slice.Slice. Every copy shares one owner, so the buffer is released by the first Slice.Close and later calls are no-ops.
The zero Slice has no buffer and no elements. Slice.Buffer returns nil for it, which binds a null pointer into a kernel's argument table, so a kernel that accepts an optional input can be given a zero Slice directly.
func Alloc ¶
Alloc allocates a Slice of count elements in shared unified memory. A count of zero allocates no Metal buffer and returns the zero Slice.
func AllocFromSlice ¶
AllocFromSlice allocates a Slice holding a copy of data in shared unified memory. An empty data slice allocates no Metal buffer and returns the zero Slice.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalmem"
)
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
return
}
s, err := metalmem.AllocFromSlice(dev, []uint32{2, 3, 5})
if err != nil {
fmt.Println(err)
return
}
defer s.Close()
dst := make([]uint32, s.Len())
if err := s.CopyToHost(dst); err != nil {
fmt.Println(err)
return
}
fmt.Println(dst)
}
Output: [2 3 5]
func AllocIn ¶
AllocIn allocates a Slice of count elements from a and records it for release by Arena.Close.
After the first failure, AllocIn allocates nothing further and returns the zero Slice, so callers may defer error handling to a single Arena.Err check. Calling AllocIn on a nil Arena returns the zero Slice.
func AllocMMapZeroCopy ¶
func AllocMMapZeroCopy[T Element](dev metal.MTLDevice, f *os.File, offset int64, count int) (Slice[T], error)
AllocMMapZeroCopy maps count elements of f starting at byte offset and wraps the mapping in a shared Metal buffer without copying.
The mapping is private (MAP_PRIVATE), so host or GPU writes do not modify the underlying file. Offset must be non-negative and aligned to the byte size of T, and the requested byte range must lie within the current file size. Offset need not be page-aligned: the mapping starts at the preceding page boundary and the returned Slice reports its byte offset through Slice.Offset.
The mapping is unmapped from Metal's buffer deallocator block when the underlying MTLBuffer is deallocated, so calling Slice.Close while an in-flight command buffer still retains the buffer will not unmap pages out from under the GPU.
func UploadIn ¶
UploadIn allocates a Slice holding a copy of data and records it for release by Arena.Close.
After the first failure, UploadIn allocates nothing further and returns the zero Slice. Calling UploadIn on a nil Arena returns the zero Slice.
func (Slice[T]) Buffer ¶
Buffer returns the underlying MTLBuffer, or nil for the zero or closed Slice. Bind it at Slice.Offset, not at zero.
func (Slice[T]) Cap ¶
Cap returns the number of elements from the slice's first element to the end of the allocation.
func (Slice[T]) Close ¶
Close releases the allocation the slice came from. Every slice derived from one allocation shares its owner, so the first Close releases the underlying buffer and subsequent calls are no-ops. Closing the zero Slice is a no-op.
func (Slice[T]) CopyFromHost ¶
CopyFromHost copies src into the slice. It reports an error if the slice is closed or src is longer than the slice.
func (Slice[T]) CopyToHost ¶
CopyToHost copies the slice into dst. It reports an error if the slice is closed or dst is shorter than the slice.
func (Slice[T]) HostSlice ¶
func (s Slice[T]) HostSlice() []T
HostSlice returns a Go slice aliasing the unified buffer, or nil if the slice is empty or closed. Writes through the returned slice are visible to the GPU.
Lifetime: the returned Go slice points directly into non-Go Metal buffer memory and is valid only while the Slice (and any owning Arena) has not been closed and no GPU command buffer is concurrently accessing the memory. Using the returned slice after Slice.Close is a use-after-free. Prefer Slice.CopyFromHost and Slice.CopyToHost when direct aliasing is not required.
func (Slice[T]) Offset ¶
Offset returns the byte offset of the slice's first element within Slice.Buffer. It may be non-zero for slices created by Slice.Slice or AllocMMapZeroCopy.
func (Slice[T]) Slice ¶
Slice returns the elements of s in [low:high]. The result shares s's allocation and owner, and reports its position within the buffer through Slice.Offset.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalmem"
)
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
return
}
s, err := metalmem.AllocFromSlice(dev, []int32{10, 20, 30, 40})
if err != nil {
fmt.Println(err)
return
}
defer s.Close()
sub, err := s.Slice(1, 3)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("len=%d offset=%d values=%v\n", sub.Len(), sub.Offset(), sub.HostSlice())
}
Output: len=2 offset=4 values=[20 30]
type Tracker ¶
type Tracker struct {
// contains filtered or unexported fields
}
Tracker accounts explicit Metal buffer allocations. It does not measure driver caches, residency, compression, or other opaque device memory.
The zero Tracker is ready for concurrent use. All methods are nil-receiver safe.
func (*Tracker) AllocatedBytes ¶
AllocatedBytes returns the currently live explicitly allocated bytes.
func (*Tracker) LiveAllocations ¶
LiveAllocations returns the number of currently live explicit allocations.
func (*Tracker) PeakBytes ¶
PeakBytes returns the high-water mark of explicitly allocated bytes since creation or the last Tracker.ResetPeak.