Documentation
¶
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 ¶
- func NewWorkspace(size int) []byte
- type Argument
- type CompileOptions
- type Context
- func (c *Context) Close() error
- func (c *Context) Execute(args []Argument, workspace []byte) error
- func (c *Context) SetArgumentType(argType accelerate.BNNSGraphArgumentType) error
- func (c *Context) SetBatchSize(batchSize uint64) error
- func (c *Context) Tensor(name string) (accelerate.BNNSTensor, error)
- func (c *Context) WorkspaceSize() int
- type Graph
- func (g *Graph) ArgumentNames() []string
- func (g *Graph) ArgumentPosition(name string) (int, bool)
- func (g *Graph) Close() error
- func (g *Graph) FunctionNames() []string
- func (g *Graph) InputNames() []string
- func (g *Graph) NewContext() (*Context, error)
- func (g *Graph) OutputNames() []string
- func (g *Graph) Size() int
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewWorkspace ¶
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 ¶
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 Float32Arg ¶
Float32Arg builds a raw-pointer Argument for a float32 slice.
func PointerArg ¶
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) Execute ¶
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 ¶
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 ¶
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 ¶
ArgumentNames returns all argument names in the order expected by Context.Execute (outputs followed by inputs).
func (*Graph) ArgumentPosition ¶
ArgumentPosition returns the index into the args slice of Context.Execute for the named input or output argument.
func (*Graph) Close ¶
Close releases the compiled graph resources. It is safe to call multiple times.
func (*Graph) FunctionNames ¶
FunctionNames returns the callable function names in the graph.
func (*Graph) InputNames ¶
InputNames returns the input argument names for the graph's function.
func (*Graph) NewContext ¶
NewContext creates an execution Context bound to g. The graph g must remain open for the lifetime of the returned context.
func (*Graph) OutputNames ¶
OutputNames returns the output argument names for the graph's function.