API reference

Compiling and running

AppleNeuralEngine.compile — Function
compile(mil; input_shapes, output_shapes, weight_blob=nothing,
        input_types=Float32, output_types=Float32)

Compile one MIL program with the private ANE runtime and load it onto the Neural Engine. Inputs and outputs are contiguous buffers of Float32 or Float16 (one type for all, or one per tensor, matching the MIL program); each shape gives the size of the Julia array that is copied in or out, and its memory layout must match the tensor in the MIL program.

weight_blob is the program's weight file, @model_path/weights/weight.bin, usually made with build_weight_blob or, for several tensors, pack_weights.

The runtime binds MIL inputs and outputs to buffer indices in sorted name order, not declaration order.

source
compile(g::MIL.Graph) -> ANEProgram

Compile a program built with the MIL graph builder. Its inputs and outputs are Julia arrays with the MIL dimensions reversed and singleton dimensions dropped: a MIL [1, C, 1, S] tensor is a Julia (S, C) matrix.

source
compile(f, inputs...; frontend=:builtin) -> ANEProgram

Trace f (see trace for the two front ends) and compile it for the Neural Engine. The program is callable: program(x...) returns the output (or a tuple of outputs).

W = randn(Float32, 512, 2048)
program = compile(x -> max.(x * W, 0), randn(Float16, 256, 512))
y = program(x)
source
AppleNeuralEngine.trace — Function
trace(f, inputs...; frontend=:builtin) -> MIL.Graph

Record f applied to placeholders for inputs (example arrays, or sizes (n,) / (m, n), which mean Float16 inputs) as a MIL graph. f returns an array or a tuple of arrays.

With frontend=:reactant, f is traced by Reactant.jl instead (load it first with using Reactant), and the optimized StableHLO module is translated to MIL. This covers far more of Julia than the built-in tracer, and loops are unrolled. Arrays may have up to 3 dimensions.

source
AppleNeuralEngine.ANEProgram — Type
ANEProgram

A MIL program compiled and loaded onto the Neural Engine, with its input and output buffers. Create one with compile; run it with evaluate! or by calling it, program(inputs...). A program holds Neural Engine resources until close! is called or it is garbage collected.

source
AppleNeuralEngine.evaluate! — Function
evaluate!(program, inputs...) -> Vector{Array}
evaluate!(outputs, program, inputs...) -> outputs

Copy inputs into the program's input buffers, run it on the Neural Engine and copy the results out. The first form returns freshly allocated output arrays. The second writes them into preallocated outputs, a tuple or vector with one dense Array per program output (or that Array alone for a one-output program), and allocates nothing: use it in loops. Any earlier result has the right arrays:

y = program(x)              # allocates
evaluate!(y, program, x)    # reuses y
source
AppleNeuralEngine.close! — Function
close!(program::ANEProgram)

Unload program from the Neural Engine and free its buffers. Safe to call more than once; afterwards the program cannot be evaluated.

source
Base.isopen — Function
isopen(program::ANEProgram) -> Bool

Whether program is still loaded (not yet close!d).

source
AppleNeuralEngine.functional — Function
functional() -> Bool

Whether programs can run on a Neural Engine here: Apple Silicon, the private framework present, and a physical (not virtualized) ANE.

source
AppleNeuralEngine.device_info — Function
device_info() -> NamedTuple

Properties of this machine's Neural Engine, as reported by the ANE framework: has_ane, virtual_machine, num_ane, num_cores, architecture (e.g. "h14g") and subtype.

source
AppleNeuralEngine.ANEError — Type
ANEError(msg)

Raised when the ANE runtime rejects a model or fails to run it. msg includes the runtime's own NSError description when one is available.

source

Weights

AppleNeuralEngine.WeightFile — Type
WeightFile()

An ANE weight file that tensors are appended to one at a time with push!(file, array), which returns the offset a MIL BLOBFILE uses to refer to the tensor. bytes(file) returns the file contents for compile.

Arrays are stored in MIL (row-major) order: element A[i, j, k] is MIL element [i, j, k], so a conv weight [Cout, Cin, kh, kw] is the Julia array W[cout, cin, kh, kw]. The element type is kept; supported types are Float16, Float32, Int16, Int32, Int8, UInt16, UInt8.

source
AppleNeuralEngine.pack_weights — Function
pack_weights(tensors...; transposed=false) -> (blob, offsets)

Encode several Float32 matrices as fp16 tensors in one ANE weight file. Pass blob to compile as weight_blob and refer to tensor i in the MIL program as

BLOBFILE(path = string("@model_path/weights/weight.bin"), offset = uint64(offsets[i]))

Each tensor is stored in row-major order, so a conv weight [Cout, Cin, 1, 1] is the matrix W[cout, cin]; with transposed=true every tensor is stored transposed. A vector (e.g. a per-channel scale) can be passed as a 1×n matrix. See WeightFile for tensors of other ranks and element types.

source
AppleNeuralEngine.build_weight_blob — Function
build_weight_blob(weights::AbstractMatrix{Float32}; transposed=false)

Encode one Float32 matrix as an fp16 ANE weight file, referred to in MIL as BLOBFILE(path = string("@model_path/weights/weight.bin"), offset = uint64(64)). See pack_weights for several tensors and for the storage order.

source

MIL graph builder

AppleNeuralEngine.MIL — Module
MIL

A builder for MIL programs, the input language of the ANE compiler. Ops are Julia functions on Vars that infer output types and shapes, so the generated program is always well-typed:

using AppleNeuralEngine, AppleNeuralEngine.MIL
g = MIL.Graph()
x = MIL.input(g, :x, Float16, (1, 64, 1, 32))
W = MIL.constant(g, randn(Float32, 64, 64, 1, 1))
MIL.output!(g, MIL.relu(MIL.conv(x, W)))
program = compile(g)

Function names and arguments follow the MIL op set as documented by coremltools; several shadow Base names (exp, reshape, ...), so call them qualified (MIL.exp) rather than using the module.

source
AppleNeuralEngine.MIL.input — Function
input(g, name, T, shape; julia_shape=nothing) -> Var

Declare a program input of element type T (Float32 or Float16) and MIL shape shape. Inputs are passed to evaluate! in declaration order, as Julia arrays of size julia_shape; by default that is shape reversed with singleton dimensions dropped, the array with the same memory layout.

source
AppleNeuralEngine.MIL.output! — Function
output!(g, v, name=v.name; julia_shape=nothing)

Mark v as a program output. Outputs are returned by evaluate! in the order they are marked, as Julia arrays of size julia_shape (see input). They must be Float32 or Float16.

source
AppleNeuralEngine.MIL.constant — Function
constant(g, value; eltype=Float16) -> Var

A constant tensor. Arrays are stored in the program's weight file, converted to eltype and indexed the MIL way (A[i, j] is MIL element [i, j]); see WeightFile. Numbers become scalar constants.

source
AppleNeuralEngine.MIL.constant_int8 — Function
constant_int8(g, W; axis=0) -> Var

A constant stored as int8 with one fp16 scale per slice along axis (symmetric quantization), dequantized by the ANE when the program is loaded (constexpr_affine_dequantize). Halves the weight memory of fp16 constants.

source
AppleNeuralEngine.MIL.op! — Function
op!(g, op, args, outputs; name=op) -> Var or Tuple{Var...}

Append the MIL operation op to g. args are name => value pairs (values are Vars or literals; nothing omits an optional argument) and outputs are (eltype, shape) pairs, one per result. This is the escape hatch for ops that have no wrapper; the wrappers in this module call it after inferring shapes.

source

Ops

AppleNeuralEngine.MIL.constant_int8 — Method
constant_int8(g, W; axis=0) -> Var

A constant stored as int8 with one fp16 scale per slice along axis (symmetric quantization), dequantized by the ANE when the program is loaded (constexpr_affine_dequantize). Halves the weight memory of fp16 constants.

source
AppleNeuralEngine.MIL.conv — Method
conv(x, weight; bias=nothing, strides=1, pad_type="valid", pad=nothing, dilations=1, groups=1)

x is [N, Cin, spatial...], weight is [Cout, Cin ÷ groups, kernel...]. pad_type is "valid", "same", "same_lower" or "custom" (then pad gives [begin, end] per spatial dimension).

source
AppleNeuralEngine.MIL.einsum — Method
einsum(equation, values...)

MIL supports a fixed set of equations, e.g. "nchw,nwhu->nchu" (batched matmul over the last two dimensions), for two rank-3 or rank-4 inputs.

source
AppleNeuralEngine.MIL.gather — Method
gather(x, indices; axis=0, batch_dims=0, validate_indices=false)
gather_along_axis(x, indices; axis=0, validate_indices=false)
gather_nd(x, indices; batch_dims=0, validate_indices=false)

Gather slices of x at indices. On the ANE, indices must be Int16 or UInt16 (int32 tensors are rejected); indices computed in the program must be UInt16, e.g. cast(i, UInt16) of an fp16 input. The gathered axis can have at most 2048 elements.

source
AppleNeuralEngine.MIL.gather_along_axis — Method
gather(x, indices; axis=0, batch_dims=0, validate_indices=false)
gather_along_axis(x, indices; axis=0, validate_indices=false)
gather_nd(x, indices; batch_dims=0, validate_indices=false)

Gather slices of x at indices. On the ANE, indices must be Int16 or UInt16 (int32 tensors are rejected); indices computed in the program must be UInt16, e.g. cast(i, UInt16) of an fp16 input. The gathered axis can have at most 2048 elements.

source
AppleNeuralEngine.MIL.gather_nd — Method
gather(x, indices; axis=0, batch_dims=0, validate_indices=false)
gather_along_axis(x, indices; axis=0, validate_indices=false)
gather_nd(x, indices; batch_dims=0, validate_indices=false)

Gather slices of x at indices. On the ANE, indices must be Int16 or UInt16 (int32 tensors are rejected); indices computed in the program must be UInt16, e.g. cast(i, UInt16) of an fp16 input. The gathered axis can have at most 2048 elements.

source
AppleNeuralEngine.MIL.lstm — Method
lstm(x, initial_h, initial_c, weight_ih, weight_hh; bias=nothing, output_sequence=false, ...) -> (output, h, c)

x is [T, B, I]; the weights are [4H, I] and [4H, H] (gate order i, f, o, g).

source
AppleNeuralEngine.MIL.matmul — Method
matmul(x, y; transpose_x=false, transpose_y=false)

Batched matrix product over the last two dimensions, with broadcasting over the rest.

source
AppleNeuralEngine.MIL.pad — Method
pad(x, pad; mode="constant", constant_val=0)

pad lists [begin, end] amounts for the last length(pad) ÷ 2 dimensions.

On the ANE (measured on M2, fp16), mode="reflect" copies every value exactly, but mode="constant" does not: values with |x| < 2^-7 snap to multiples of 2^-17 (subnormals flush to zero), the 2^-7 binade is off by up to 1 ulp, and |x| ≥ 2^15 becomes ±Inf. Values from 2^-6 up to 2^15 pass through unchanged.

source
AppleNeuralEngine.MIL.reduce_argmax — Function
reduce_argmax(x; axis=-1, keep_dims=false, output_dtype=Int32)
reduce_argmin(x; axis=-1, keep_dims=false, output_dtype=Int32)

Index of the largest (smallest) element along axis. The ANE rejects int32 tensors, so pass output_dtype=UInt16 to run on it. The ANE then produces fp16 bit patterns labelled uint16: decode a result y = cast(i, Float16) on the host with reinterpret(Float16, UInt16(y)). See the op support page for the axes and sizes that work.

source
AppleNeuralEngine.MIL.reduce_argmin — Function
reduce_argmax(x; axis=-1, keep_dims=false, output_dtype=Int32)
reduce_argmin(x; axis=-1, keep_dims=false, output_dtype=Int32)

Index of the largest (smallest) element along axis. The ANE rejects int32 tensors, so pass output_dtype=UInt16 to run on it. The ANE then produces fp16 bit patterns labelled uint16: decode a result y = cast(i, Float16) on the host with reinterpret(Float16, UInt16(y)). See the op support page for the axes and sizes that work.

source
AppleNeuralEngine.MIL.slice_by_index — Method
slice_by_index(x, begin_, end_; stride=nothing, begin_mask=nothing, end_mask=nothing, squeeze_mask=nothing)

Python-style half-open slices begin_:stride:end_ per dimension (0-based).

source
AppleNeuralEngine.MIL.topk — Method
topk(x; k=1, axis=-1, ascending=false, sort=true, return_indices=true, indices_dtype=Int32)
    -> (values, indices), or values alone when `return_indices=false`

indices_dtype is Int32 or UInt16 (MIL output_indices_dtype, iOS17+; MIL validation then requires sort and return_indices, which are always written). The ANE compiler does not support topk: int32 indices fail MIL validation, and with uint16 indices or return_indices=false the compiler backend rejects it.

source

Tracing

AppleNeuralEngine.Traced — Type
Traced

A placeholder for a Julia vector or matrix while a function is traced by compile(f, inputs...). Supports broadcasting with arbitrary scalar functions built from arithmetic, exp, log, sqrt, tanh, abs, max, min, comparisons and ifelse; matrix products and adjoint; and sum, maximum, minimum with dims.

source