metalio

package
v0.6.21 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 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 metalio provides a zero-cgo wrapper around Metal's asynchronous storage I/O APIs (metal.MTLIOCommandQueue, metal.MTLIOFileHandle, and metal.MTLIOCommandBuffer) for streaming data directly from storage into GPU-accessible metal.MTLBuffer memory.

Construct a Queue with NewQueue and open files with OpenFile (or OpenCompressedFile), then stream single regions with Queue.LoadBuffer or multi-tensor batches with Queue.LoadBatch:

dev := metal.MTLCreateSystemDefaultDevice()
q, err := metalio.NewQueue(dev, metalio.Options{Label: "weights"})
if err != nil {
	return err
}
defer q.Close()

f, err := metalio.OpenFile(dev, "model.bin")
if err != nil {
	return err
}
defer f.Close()

buf := dev.NewBufferWithLengthOptions(uint(f.Size()), metal.MTLResourceStorageModeShared)
if err := q.LoadBuffer(ctx, f, 0, buf, 0, uint64(f.Size())); err != nil {
	return err
}

The zero values of Queue and File are not usable; create them with NewQueue and OpenFile and release the underlying Metal handles with Close.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"unsafe"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/objectivec"
	"github.com/tmc/apple/x/metalio"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	if dev.GetID() == 0 {
		fmt.Println("ok")
		return
	}

	dir, err := os.MkdirTemp("", "metalio-example-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "weights.bin")
	payload := []byte("metalio-weights!")
	if err := os.WriteFile(path, payload, 0o600); err != nil {
		fmt.Println(err)
		return
	}

	q, err := metalio.NewQueue(dev, metalio.Options{Label: "example"})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer q.Close()

	f, err := metalio.OpenFile(dev, path)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	buf := dev.NewBufferWithLengthOptions(uint(len(payload)), metal.MTLResourceStorageModeShared)
	defer objectivec.ObjectFromID(buf.GetID()).Release()

	if err := q.LoadBuffer(context.Background(), f, 0, buf, 0, uint64(len(payload))); err != nil {
		fmt.Println(err)
		return
	}

	got := unsafe.Slice((*byte)(buf.Contents()), len(payload))
	fmt.Println(string(got))
}
Output:
metalio-weights!

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is returned when an operation is attempted on a closed [Queue] or [File].
	ErrClosed = errors.New("metalio: closed")

	// ErrCancelled is wrapped by [StatusError] when an I/O command buffer
	// finishes with [metal.MTLIOStatusCancelled].
	ErrCancelled = errors.New("metalio: command buffer cancelled")
)

Functions

This section is empty.

Types

type File

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

File wraps an metal.MTLIOFileHandle opened on a Metal device. A File is safe for concurrent read operations by multiple goroutines.

func OpenCompressedFile

func OpenCompressedFile(dev metal.MTLDevice, path string, method metal.MTLIOCompressionMethod) (*File, error)

OpenCompressedFile opens a compressed file at path for Metal I/O on dev using the given metal.MTLIOCompressionMethod.

func OpenFile

func OpenFile(dev metal.MTLDevice, path string) (*File, error)

OpenFile opens an uncompressed file at path for Metal I/O on dev.

func (*File) Close

func (f *File) Close() error

Close releases the underlying metal.MTLIOFileHandle. Close is idempotent.

func (*File) Path

func (f *File) Path() string

Path returns the resolved absolute path of the file.

func (*File) Raw

func (f *File) Raw() metal.MTLIOFileHandle

Raw returns the underlying metal.MTLIOFileHandle, or nil if closed.

func (*File) SetLabel

func (f *File) SetLabel(label string)

SetLabel sets the optional debug label on the underlying metal.MTLIOFileHandle.

func (*File) Size

func (f *File) Size() int64

Size returns the file size in bytes observed when the file was opened.

type LoadRequest

type LoadRequest struct {
	// File is the open source file handle.
	File *File

	// FileOffset is the byte offset in File to read from.
	FileOffset uint64

	// Buffer is the destination Metal buffer.
	Buffer metal.MTLBuffer

	// BufferOffset is the byte offset in Buffer to write into.
	BufferOffset uint64

	// Size is the number of bytes to copy. A zero size is a no-op.
	Size uint64

	// BarrierAfter encodes an intra-command-buffer barrier after this load so
	// subsequent commands in the same batch wait for it to complete.
	BarrierAfter bool
}

LoadRequest describes a single file-to-buffer copy encoded into an metal.MTLIOCommandBuffer by Queue.LoadBatch.

type Options

type Options struct {
	// Priority sets the queue scheduling priority.
	// Zero is [metal.MTLIOPriorityHigh].
	Priority metal.MTLIOPriority

	// Type selects concurrent or serial command execution.
	// Zero is [metal.MTLIOCommandQueueTypeConcurrent].
	Type metal.MTLIOCommandQueueType

	// MaxCommandBufferCount limits outstanding command buffers on the queue.
	// Zero uses Metal's default.
	MaxCommandBufferCount uint

	// MaxCommandsInFlight limits concurrent I/O commands executed by the queue.
	// Zero lets Metal choose based on available memory.
	MaxCommandsInFlight uint

	// Label is an optional debug label attached to the queue.
	Label string
}

Options configures an [MTLIOCommandQueue] created by NewQueue. The zero value selects metal.MTLIOPriorityHigh, metal.MTLIOCommandQueueTypeConcurrent, and Metal's default buffer and in-flight command limits.

type Queue

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

Queue manages a Metal metal.MTLIOCommandQueue for streaming file regions into GPU buffers. A Queue is safe for concurrent use by multiple goroutines.

func NewQueue

func NewQueue(dev metal.MTLDevice, opts Options) (*Queue, error)

NewQueue creates an [MTLIOCommandQueue] on dev using opts.

func (*Queue) Close

func (q *Queue) Close() error

Close releases the underlying metal.MTLIOCommandQueue. Close is idempotent.

func (*Queue) EnqueueBarrier

func (q *Queue) EnqueueBarrier() error

EnqueueBarrier appends a queue-level barrier so subsequent command buffers wait for all previously submitted command buffers to finish.

func (*Queue) LoadBatch

func (q *Queue) LoadBatch(ctx context.Context, reqs []LoadRequest) error

LoadBatch encodes all reqs into a single metal.MTLIOCommandBuffer, commits it, and waits until completion. If ctx is canceled before completion, LoadBatch requests cancellation via TryCancel and returns either ctx.Err() or a *StatusError.

Example
package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"unsafe"

	"github.com/tmc/apple/metal"
	"github.com/tmc/apple/objectivec"
	"github.com/tmc/apple/x/metalio"
)

func main() {
	dev := metal.MTLCreateSystemDefaultDevice()
	if dev.GetID() == 0 {
		fmt.Println("ok")
		return
	}

	dir, err := os.MkdirTemp("", "metalio-batch-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	path := filepath.Join(dir, "tensors.bin")
	if err := os.WriteFile(path, []byte("AAAABBBBCCCC"), 0o600); err != nil {
		fmt.Println(err)
		return
	}

	q, err := metalio.NewQueue(dev, metalio.Options{})
	if err != nil {
		fmt.Println(err)
		return
	}
	defer q.Close()

	f, err := metalio.OpenFile(dev, path)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	buf := dev.NewBufferWithLengthOptions(8, metal.MTLResourceStorageModeShared)
	defer objectivec.ObjectFromID(buf.GetID()).Release()

	err = q.LoadBatch(context.Background(), []metalio.LoadRequest{
		{File: f, FileOffset: 8, Buffer: buf, BufferOffset: 0, Size: 4},
		{File: f, FileOffset: 0, Buffer: buf, BufferOffset: 4, Size: 4},
	})
	if err != nil {
		fmt.Println(err)
		return
	}

	got := unsafe.Slice((*byte)(buf.Contents()), 8)
	fmt.Println(string(got))
}
Output:
CCCCAAAA

func (*Queue) LoadBuffer

func (q *Queue) LoadBuffer(ctx context.Context, file *File, fileOffset uint64, dstBuf metal.MTLBuffer, dstOffset uint64, size uint64) error

LoadBuffer streams size bytes from file starting at fileOffset into dstBuf starting at dstOffset and waits until the transfer completes.

func (*Queue) Raw

func (q *Queue) Raw() metal.MTLIOCommandQueue

Raw returns the underlying metal.MTLIOCommandQueue, or nil if closed.

type StatusError

type StatusError struct {
	Status metal.MTLIOStatus
	Err    error
}

StatusError reports a non-complete metal.MTLIOStatus returned by an metal.MTLIOCommandBuffer after execution finishes.

func (*StatusError) Error

func (e *StatusError) Error() string

func (*StatusError) Is

func (e *StatusError) Is(target error) bool

func (*StatusError) Unwrap

func (e *StatusError) Unwrap() error

Jump to

Keyboard shortcuts

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