bnnsgraph

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: 8 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 bnnsgraph wraps Apple Accelerate's BNNSGraph C API for executing compiled CoreML (.mlmodelc) graphs on CPU and AMX without cgo.

BNNSGraph compiles an .mlmodelc bundle into an immutable Graph, then creates a mutable Context for execution. Passing a caller-owned, page-aligned workspace slice to Context.Execute runs inference with zero heap allocations per step.

Arguments to Context.Execute are ordered with outputs before inputs, matching Graph.ArgumentNames and Graph.ArgumentPosition.

Basic usage:

g, err := bnnsgraph.CompileFromFile(mlmodelcPath, nil)
if err != nil {
	return err
}
defer g.Close()

ctx, err := g.NewContext()
if err != nil {
	return err
}
defer ctx.Close()

ws := bnnsgraph.NewWorkspace(ctx.WorkspaceSize())
args := []bnnsgraph.Argument{
	bnnsgraph.Float32Arg(out),
	bnnsgraph.Float32Arg(in),
}
if err := ctx.Execute(args, ws); err != nil {
	return err
}

Requires macOS 15 or later.

Example
dir, err := os.MkdirTemp("", "bnnsgraph-example-*")
if err != nil {
	panic(err)
}
defer os.RemoveAll(dir)

// Build a minimal ReLU model in pure Go.
vt := f32TensorVT(1, 4)
prog := &coremlcompiler.Program{
	Functions: map[string]*coremlcompiler.Function{
		"main": {
			Inputs: []coremlcompiler.NamedValueType{{Name: "x", Type: vt}},
			OpSet:  "CoreML8",
			BlockSpecializations: map[string]*coremlcompiler.Block{
				"CoreML8": {
					Operations: []*coremlcompiler.Operation{{
						Type:    "relu",
						Inputs:  map[string]*coremlcompiler.Argument{"x": refArg("x")},
						Outputs: []coremlcompiler.NamedValueType{{Name: "y", Type: vt}},
					}},
					Outputs: []string{"y"},
				},
			},
		},
	},
}
inDesc, err := coremlcompiler.TensorFeatureDescription("x", "fp32", []int64{1, 4})
if err != nil {
	panic(err)
}
outDesc, err := coremlcompiler.TensorFeatureDescription("y", "fp32", []int64{1, 4})
if err != nil {
	panic(err)
}
bundle := filepath.Join(dir, "relu.mlmodelc")
err = coremlcompiler.CompileProgram(prog, 9, coremlcompiler.ModelDescription{
	Inputs:  []coremlcompiler.FeatureDescription{inDesc},
	Outputs: []coremlcompiler.FeatureDescription{outDesc},
}, "", bundle)
if err != nil {
	panic(err)
}

g, err := bnnsgraph.CompileFromFile(bundle, &bnnsgraph.CompileOptions{SingleThread: true})
if err != nil {
	panic(err)
}
defer g.Close()

ctx, err := g.NewContext()
if err != nil {
	panic(err)
}
defer ctx.Close()

ws := bnnsgraph.NewWorkspace(ctx.WorkspaceSize())
in := []float32{-2, -0.5, 0, 3.5}
out := make([]float32, 4)
args := []bnnsgraph.Argument{
	bnnsgraph.Float32Arg(out),
	bnnsgraph.Float32Arg(in),
}
if err := ctx.Execute(args, ws); err != nil {
	panic(err)
}
fmt.Printf("inputs=%v outputs=%v y=%v\n", g.InputNames(), g.OutputNames(), out)
Output:
inputs=[x] outputs=[y] y=[0 0 0 3.5]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewWorkspace

func NewWorkspace(size int) []byte

NewWorkspace allocates a page-aligned scratch buffer of at least size bytes suitable for Context.Execute. If size <= 0, it returns nil.

Types

type Argument

type Argument struct {
	Data unsafe.Pointer
	Size uintptr
}

Argument is one input or output binding passed to Context.Execute.

Its layout matches C's bnns_graph_argument_t: either a raw data pointer and byte length (for accelerate.BNNSGraphArgumentTypePointer, the default) or a pointer to an accelerate.BNNSTensor (for accelerate.BNNSGraphArgumentTypeTensor).

func BytesArg

func BytesArg(b []byte) Argument

BytesArg builds a raw-pointer Argument for a byte slice.

func Float32Arg

func Float32Arg(s []float32) Argument

Float32Arg builds a raw-pointer Argument for a float32 slice.

func PointerArg

func PointerArg[T any](s []T) Argument

PointerArg builds a raw-pointer Argument referencing the backing memory of s.

func TensorArg

func TensorArg(t *accelerate.BNNSTensor) Argument

TensorArg builds a tensor Argument pointing at t. Requires Context.SetArgumentType(accelerate.BNNSGraphArgumentTypeTensor).

type CompileOptions

type CompileOptions struct {
	// Function restricts compilation to a single named function in the model.
	// Empty compiles all functions.
	Function string

	// SingleThread compiles the graph to execute on a single thread.
	SingleThread bool

	// GenerateDebugInfo includes debug metadata in the compiled graph.
	GenerateDebugInfo bool

	// OptimizationPreference selects performance (default, 0) or IR size.
	OptimizationPreference accelerate.BNNSGraphOptimizationPreference

	// OutputPath, when non-empty, writes the compiled graph directly to disk
	// and memory-maps it read-only instead of holding it in heap memory.
	OutputPath string
}

CompileOptions configures CompileFromFile. A nil *CompileOptions uses BNNSGraph's defaults (multi-threaded, optimize for performance, compile in memory).

type Context

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

Context holds mutable execution state for a Graph. A Context must only be used by one goroutine at a time, and must be closed before its parent Graph.

func (*Context) Close

func (c *Context) Close() error

Close destroys the execution context. It is safe to call multiple times.

func (*Context) Execute

func (c *Context) Execute(args []Argument, workspace []byte) error

Execute runs the graph synchronously using args and workspace.

args must match the graph's argument order (outputs first, then inputs; see Graph.ArgumentNames and Graph.ArgumentPosition).

workspace must be page-aligned (use NewWorkspace) and at least Context.WorkspaceSize bytes when non-nil. Passing nil lets BNNS allocate a temporary workspace internally. When workspace is preallocated and all output buffers are provided in args, Execute performs zero Go heap allocations.

func (*Context) SetArgumentType

func (c *Context) SetArgumentType(argType accelerate.BNNSGraphArgumentType) error

SetArgumentType selects whether Context.Execute interprets Argument as raw data pointers (accelerate.BNNSGraphArgumentTypePointer, default) or accelerate.BNNSTensor descriptors (accelerate.BNNSGraphArgumentTypeTensor).

func (*Context) SetBatchSize

func (c *Context) SetBatchSize(batchSize uint64) error

SetBatchSize sets the dynamic batch dimension for the context and refreshes Context.WorkspaceSize.

func (*Context) Tensor

func (c *Context) Tensor(name string) (accelerate.BNNSTensor, error)

Tensor returns the accelerate.BNNSTensor metadata (data type, rank, shape, stride) for the named input or output argument.

func (*Context) WorkspaceSize

func (c *Context) WorkspaceSize() int

WorkspaceSize returns the minimum workspace size in bytes required by Context.Execute, or -1 if the graph has unresolved dynamic shapes.

type Graph

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

Graph is an immutable compiled BNNSGraph ready to create execution contexts. The zero value is not usable; create one with CompileFromFile.

func CompileFromFile

func CompileFromFile(mlmodelcPath string, opts *CompileOptions) (*Graph, error)

CompileFromFile compiles the .mlmodelc bundle at mlmodelcPath into a Graph.

func (*Graph) ArgumentNames

func (g *Graph) ArgumentNames() []string

ArgumentNames returns all argument names in the order expected by Context.Execute (outputs followed by inputs).

func (*Graph) ArgumentPosition

func (g *Graph) ArgumentPosition(name string) (int, bool)

ArgumentPosition returns the index into the args slice of Context.Execute for the named input or output argument.

func (*Graph) Close

func (g *Graph) Close() error

Close releases the compiled graph resources. It is safe to call multiple times.

func (*Graph) FunctionNames

func (g *Graph) FunctionNames() []string

FunctionNames returns the callable function names in the graph.

func (*Graph) InputNames

func (g *Graph) InputNames() []string

InputNames returns the input argument names for the graph's function.

func (*Graph) NewContext

func (g *Graph) NewContext() (*Context, error)

NewContext creates an execution Context bound to g. The graph g must remain open for the lifetime of the returned context.

func (*Graph) OutputNames

func (g *Graph) OutputNames() []string

OutputNames returns the output argument names for the graph's function.

func (*Graph) Size

func (g *Graph) Size() int

Size returns the compiled graph size in bytes.

Jump to

Keyboard shortcuts

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