Documentation
¶
Overview ¶
Package coremlcompiler compiles CoreML model packages (.mlpackage) into compiled model bundles (.mlmodelc) without requiring xcrun or Apple's proprietary coremlcompiler binary.
Only mlprogram models (spec version 5+) are supported. Legacy NeuralNetwork models must first be converted to mlprogram format using coremltools (convert_to="mlprogram").
The compilation path converts mlprogram models: the protobuf-encoded MIL program is serialized to MIL text, weights are copied byte-for-byte, and a coremldata.bin header is generated. The resulting .mlmodelc bundle can be loaded directly by CoreML, but it contains model.mil without an Espresso IR network (model.espresso.net) and is not accepted by x/ane's ModelTypePackage loader. For direct ANE execution via x/ane, pass MIL text with ModelTypeMIL or compile a NeuralNetwork protobuf with x/coremlcompiler/nnproto and CompileMLModelAtURL.
Three entry points cover different use cases:
Compile takes a .mlpackage directory or .mlmodel file on disk and produces a compiled .mlmodelc bundle. This is the simplest path and handles reading the protobuf, locating weights, and writing all output files:
err := coremlcompiler.Compile("model.mlpackage", "model.mlmodelc")
CompileMLProgram accepts raw model protobuf bytes and a weight directory. Use this when you already have the serialized model in memory or need to supply the weight directory separately:
err := coremlcompiler.CompileMLProgram(protoBytes, weightDir, "model.mlmodelc")
CompileMILText takes pre-built MIL text, a ModelDescription, and an optional weight root directory. Use this when you generate MIL text programmatically rather than decoding it from a protobuf:
err := coremlcompiler.CompileMILText(milText, 8, desc, weightRoot, "model.mlmodelc")
A MIL generator reaches CompileMILText through TensorFeatureDescription and StateFeatureDescription, which build the ModelDescription from element types spelled the way MIL spells them ("fp16", "int32"), and WriteWeightRoot, which lays out the weight blobs a program's BLOBFILE paths name. Between them a generator needs no adapter of its own, and this package needs no dependency on the generator.
The Go types in this package model the mlprogram subset of the CoreML specification. Fields outside that subset, such as Model.isUpdatable or an input's shape flexibility, cannot be constructed from Go, but a model decoded from wire bytes keeps them and re-encodes them verbatim.
Index ¶
- Constants
- func Compile(inputPath, outputPath string) error
- func CompileMILText(milText string, specVersion int32, desc ModelDescription, ...) error
- func CompileMLModelAtURL(sourcePath string) (string, error)
- func CompileMLProgram(modelProto []byte, weightDir, outputPath string) error
- func CompileProgram(prog *Program, specVersion int32, desc ModelDescription, ...) error
- func CompileToTemp(inputPath string) (string, error)
- func EncodeModel(m *Model) []byte
- func Float16Bytes(vals []float32) []byte
- func Float16bits(f float32) uint16
- func Float16frombits(h uint16) float32
- func PackSubByte(dt BlobDataType, values []int8) ([]byte, error)
- func SanitizeProgram(m *Model)
- func ShouldUseWeightFile(dt DataType, numElements int, specVersion int32) bool
- func ValidateNames(prog *Program) error
- func ValidateProgram(prog *Program) error
- func ValidateTensorValue(dt DataType, tv *TensorValue) error
- func WriteMILBlob(entries []BlobEntry) (data []byte, offsets []uint64)
- func WriteMLPackage(dir string, modelProto []byte, weightSrc string) error
- func WriteWeightRoot(root string, files []WeightFile) error
- type AffineDequantization
- type Argument
- type ArrayDataType
- type ArrayFeatureType
- type Binding
- type BlobDataType
- type BlobEntry
- type BlobFileValue
- type BlobLayout
- type BlobRef
- type Block
- type ColorSpace
- type CoreMLModel
- type DataType
- type DictionaryFeatureType
- type DictionaryMapEntry
- type DictionaryType
- type DictionaryValue
- type Dimension
- type FeatureDescription
- type FeatureType
- type Function
- type FunctionDescription
- type ImageFeatureType
- type ImmediateValue
- type ListType
- type ListValue
- type Model
- type ModelDescription
- type ModelMetadata
- type MultiArrayDataType
- type NamedValueType
- type Operation
- type PredictInput
- type PredictOutput
- type Program
- type SequenceFeatureType
- type StateType
- type TensorType
- type TensorValue
- type TensorValueField
- type TupleType
- type TupleValue
- type Value
- type ValueType
- type WeightFile
- type WeightTensor
Examples ¶
- AffineDequantization.Dequantize
- AffineDequantization.NumElements
- AffineDequantization.Operation
- AffineDequantization.Validate
- BlobLayout.String
- BuildWeights
- CompileProgram
- DataType.ArrayDataType
- Float16Bytes
- Float16bits
- Float16frombits
- ParseDataType
- QuantizeAffinePerChannel
- StateFeatureDescription
- TensorFeatureDescription
- WriteWeightRoot
Constants ¶
const DefaultWeightDir = "weights"
DefaultWeightDir is the directory BlobLayoutFilePerConst writes into.
const DefaultWeightFileName = "weights/weight.bin"
DefaultWeightFileName is the file BlobLayoutSingleFile writes to, the name coremltools gives a .mlpackage's weight blob.
const ModelPathPrefix = "@model_path/"
ModelPathPrefix is the prefix a BLOBFILE path in MIL text uses to name a location inside the compiled bundle. The runtime resolves it against the bundle directory, so "@model_path/weights/w.bin" is the file "weights/w.bin" in the .mlmodelc.
Variables ¶
This section is empty.
Functions ¶
func Compile ¶
Compile compiles a CoreML model package (.mlpackage) or model file (.mlmodel) into a compiled bundle (.mlmodelc) at outputPath.
Only mlprogram models (spec version 5+) are supported. Legacy NeuralNetwork models must be converted to the mlprogram format before compilation (e.g. via coremltools.convert with convert_to="mlprogram").
func CompileMILText ¶
func CompileMILText(milText string, specVersion int32, desc ModelDescription, weightRoot, outputPath string) error
CompileMILText compiles an already-emitted mlprogram MIL text into a compiled bundle at outputPath.
milText is not validated. This package has no MIL text parser, so there is nothing to check it against: the text is written into the bundle verbatim, and none of the program checks CompileProgram runs apply to it. desc is not checked against it either, so a description disagreeing with the MIL text's own signature is written out and fails at load time instead. A producer that holds a structured program should call CompileProgram, which emits the text itself and validates first.
desc names the model inputs, outputs, and states stored in coremldata.bin and metadata.json. weightRoot, when non-empty, is copied into the bundle preserving relative paths, so BLOBFILE paths like "@model_path/weights/..." resolve correctly at runtime.
func CompileMLModelAtURL ¶ added in v0.5.4
CompileMLModelAtURL uses [MLModel compileModelAtURL:error:] to compile a .mlpackage or .mlmodel to a .mlmodelc directory. Only available on darwin.
func CompileMLProgram ¶
CompileMLProgram compiles an mlprogram model from already-parsed components. This is useful when you have the model proto bytes and weight directory available separately.
func CompileProgram ¶
func CompileProgram(prog *Program, specVersion int32, desc ModelDescription, weightRoot, outputPath string) error
CompileProgram compiles a Program built in Go into a compiled bundle at outputPath.
It is the path for a producer that has a structured program: unlike CompileMILText it validates before emitting, so the program is held to the same rules a model decoded from a .mlpackage is. It runs ValidateProgram, the per-op input specifications, the model interface rules, and the check that desc matches the program's own signature; then emits the MIL text itself, so text and description cannot disagree.
desc names the model inputs, outputs, and states stored in coremldata.bin and metadata.json; TensorFeatureDescription and StateFeatureDescription build its entries. specVersion selects the MIL dialect, defaulting to the iOS18 opset. weightRoot, when non-empty, is the directory holding the weight files the program's BLOBFILE references name, as written by WriteWeightRoot; only referenced files are copied into the bundle.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
err := coremlcompiler.CompileProgram(nil, 0, coremlcompiler.ModelDescription{}, "", "unused.mlmodelc")
fmt.Println(err)
}
Output: coremlcompiler: program is nil
func CompileToTemp ¶
CompileToTemp compiles a model to a temporary directory, returning the path to the compiled .mlmodelc bundle. The directory is placed under os.TempDir() and named by a hash of the input path and content for implicit caching.
func EncodeModel ¶ added in v0.5.0
EncodeModel encodes a Model to protobuf wire format.
The Model type models the mlprogram subset of the CoreML spec. Fields outside that subset cannot be built from Go, but are preserved verbatim on a model that was decoded from wire bytes and are re-emitted after the modeled fields of the message they belong to.
func Float16Bytes ¶
Float16Bytes encodes vals as little-endian binary16, the layout MIL blob storage holds an fp16 tensor in.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
fmt.Printf("%x\n", coremlcompiler.Float16Bytes([]float32{1, 1.5}))
}
Output: 003c003e
func Float16bits ¶
Float16bits returns the IEEE 754 binary16 representation of f, with the sign, exponent, and fraction in the same bit positions the format defines. It rounds to nearest, ties to even, the mode IEEE 754 specifies and the mode coremltools' numpy float16 conversion uses; values too large for binary16 become an infinity of the same sign, and values too small become a subnormal or a signed zero.
It is the inverse of Float16frombits, and the analogue of math.Float32bits for the half-precision weights Core ML models are built from.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
fmt.Printf("%04x\n", coremlcompiler.Float16bits(1.5))
}
Output: 3e00
func Float16frombits ¶
Float16frombits returns the float32 value of the IEEE 754 binary16 number h. Every binary16 value is exactly representable in float32, so the conversion is lossless. It is the inverse of Float16bits.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
fmt.Println(coremlcompiler.Float16frombits(0x3e00))
}
Output: 1.5
func PackSubByte ¶ added in v0.6.17
func PackSubByte(dt BlobDataType, values []int8) ([]byte, error)
PackSubByte packs values of a sub-byte blob element type into the byte payload MILBlob stores. Element i occupies bits [i*bits, (i+1)*bits) of the stream, little-endian within each byte; for widths that do not divide 8 an element straddling a byte boundary continues in the low bits of the next byte. This mirrors MILBlob's PackSubByteVec.
func SanitizeProgram ¶ added in v0.6.17
func SanitizeProgram(m *Model)
SanitizeProgram rewrites every function, variable and block name in m's MIL program into a legal MIL identifier, and applies the same rewrite to the matching ModelDescription feature names so the description and the MIL stay in sync. Names that are already valid are left untouched.
func ShouldUseWeightFile ¶ added in v0.6.17
ShouldUseWeightFile reports whether a constant of the given element type and element count belongs in the weight file rather than inline in MIL text. It mirrors coremltools' should_use_weight_file: at least 10 elements and an element type the target specification version stores in a blob.
func ValidateNames ¶ added in v0.6.17
ValidateNames reports the first identifier in prog that is not a legal MIL identifier. Invalid names are emitted verbatim by the MIL text writer and produce a syntactically invalid program that only fails, opaquely, inside Apple's compiler. Use SanitizeProgram to repair them.
func ValidateProgram ¶ added in v0.6.17
ValidateProgram validates structural requirements of an MIL Program.
func ValidateTensorValue ¶ added in v0.6.17
func ValidateTensorValue(dt DataType, tv *TensorValue) error
ValidateTensorValue reports whether tv stores its data in the one field the MIL reader consults for element type dt.
func WriteMILBlob ¶ added in v0.5.4
WriteMILBlob builds a MIL Blob Storage v2 weight file from the given entries. Returns the complete file bytes and the BLOBFILE offsets (one per entry) that should be used in MIL text.
func WriteMLPackage ¶ added in v0.5.0
WriteMLPackage creates a .mlpackage directory at dir containing the given model protobuf and optional weights. The directory can be read back by readMLPackage or passed to MLModel.compileModelAtURL:.
The layout matches Apple's coremltools format:
dir/
├── Manifest.json
└── Data/
└── com.apple.CoreML/
├── model.mlmodel (modelProto bytes)
└── weights/ (copied from weightSrc if provided)
Manifest paths use "com.apple.CoreML/..." (without Data/ prefix); the Data/ directory is implicit when resolving paths on disk.
If weightSrc is a directory, it is treated as the weights directory itself: its contents are copied under weights/ preserving relative paths, so a weightSrc containing weight.bin produces weights/weight.bin and BLOBFILE references of the form @model_path/weights/... resolve. If weightSrc is a single file, it is copied as weights/weight.bin.
func WriteWeightRoot ¶
func WriteWeightRoot(root string, files []WeightFile) error
WriteWeightRoot writes files into root under the relative paths their MIL BLOBFILE paths name, creating directories as needed.
root is then a weight root suitable for CompileMILText, which copies it into the compiled bundle so that "@model_path/..." resolves at load time.
Example ¶
package main
import (
"fmt"
"os"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
root, err := os.MkdirTemp("", "weight-root-example-")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
err = coremlcompiler.WriteWeightRoot(root, []coremlcompiler.WeightFile{{
Path: "@model_path/weights/w.bin", Blob: []byte{1, 2},
}})
fmt.Println(err)
}
Output: <nil>
Types ¶
type AffineDequantization ¶
type AffineDequantization struct {
// Shape is the shape of the quantized data, which is also the shape of
// the dequantized output.
Shape []int64
// QuantizedType is the stored element type: [DataTypeInt8] or
// [DataTypeUInt8].
QuantizedType DataType
// OutputType is the type the data dequantizes to: [DataTypeFloat16] or
// [DataTypeFloat32].
OutputType DataType
// Axis is the dimension Scale and ZeroPoint vary along. It is ignored
// when they hold a single value.
Axis int32
// Scale and ZeroPoint hold either one value, or Shape[Axis] values.
// They must be the same length as each other.
Scale []float32
ZeroPoint []int64
}
An AffineDequantization describes a weight tensor stored quantized to 8 bits and the parameters that recover it, following the equation constexpr_affine_dequantize is defined by (ops/defs/iOS16/constexpr_ops.py):
unquantized = scale * (quantized_data - zero_point)
Scale and ZeroPoint are either one value each, quantizing the whole tensor, or one per slice along Axis. Per-output-channel quantization of a projection matrix shaped [out, in] is the latter with Axis 0.
func QuantizeAffinePerChannel ¶
func QuantizeAffinePerChannel(values []float32, shape []int64, axis int32, quantizedType DataType) (AffineDequantization, []byte, error)
QuantizeAffinePerChannel quantizes values, laid out row-major in shape, to 8 bits with one scale and zero point per slice along axis. It returns the descriptor and the packed quantized payload, ready for a WeightTensor.
Quantizing a projection matrix per output channel means axis 0 of an [out, in] matrix: each output row gets the scale and zero point that spread its own range across the full 8-bit range.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
q, packed, err := coremlcompiler.QuantizeAffinePerChannel([]float32{0, 1}, []int64{1, 2}, 0, coremlcompiler.DataTypeInt8)
fmt.Println(q.NumElements(), len(packed), err)
}
Output: 2 2 <nil>
func (AffineDequantization) Dequantize ¶
func (q AffineDequantization) Dequantize(packed []byte) ([]float32, error)
Dequantize recovers the values q describes from its packed payload. It is the inverse of QuantizeAffinePerChannel up to quantization error, and exists so a caller can measure that error before shipping a model.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
q := coremlcompiler.AffineDequantization{
Shape: []int64{2}, QuantizedType: coremlcompiler.DataTypeInt8,
OutputType: coremlcompiler.DataTypeFloat32, Scale: []float32{0.5}, ZeroPoint: []int64{0},
}
values, err := q.Dequantize([]byte{2, 4})
fmt.Println(values, err)
}
Output: [1 2] <nil>
func (AffineDequantization) NumElements ¶
func (q AffineDequantization) NumElements() int
NumElements returns the number of elements the quantized tensor holds. It returns zero if the shape is invalid or its element count overflows int.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
q := coremlcompiler.AffineDequantization{Shape: []int64{2, 3}}
fmt.Println(q.NumElements())
}
Output: 6
func (AffineDequantization) Operation ¶
func (q AffineDequantization) Operation(name string, data BlobRef) (*Operation, error)
Operation returns the constexpr_affine_dequantize operation producing a tensor named name from quantized data held at data.
The parameters go in the operation's attributes, not its inputs, whatever opset the enclosing function declares. coremltools chooses between the two on op.opset_version -- the opset the op class itself was declared at, not the program's (mil/operation.py:571-577, backend/mil/load.py translate_constexpr). constexpr_affine_dequantize is declared only in ops/defs/iOS16 and is not among the constexpr ops iOS18 redefines, so it is always an iOS16 op and always takes attributes. The Core ML runtime agrees and names it that way: a program that puts these in inputs is rejected with "Attribute quantized_data is undefined for ios16.constexpr_affine_dequantize".
The constexpr ops introduced at iOS18 -- constexpr_blockwise_shift_scale and the rest of ops/defs/iOS18/compression.py -- are the ones that take inputs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
q := coremlcompiler.AffineDequantization{
Shape: []int64{2}, QuantizedType: coremlcompiler.DataTypeInt8,
OutputType: coremlcompiler.DataTypeFloat32, Scale: []float32{0.5}, ZeroPoint: []int64{0},
}
op, err := q.Operation("w", coremlcompiler.BlobRef{Path: "@model_path/weights/w.bin", Offset: 64})
fmt.Println(op.Type, op.Outputs[0].Name, err)
}
Output: constexpr_affine_dequantize w <nil>
func (AffineDequantization) Validate ¶
func (q AffineDequantization) Validate() error
Validate reports whether q satisfies constexpr_affine_dequantize's constraints on its parameters.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
q := coremlcompiler.AffineDequantization{
Shape: []int64{2}, QuantizedType: coremlcompiler.DataTypeInt8,
OutputType: coremlcompiler.DataTypeFloat32, Scale: []float32{0.5}, ZeroPoint: []int64{0},
}
fmt.Println(q.Validate())
}
Output: <nil>
type Argument ¶
type Argument struct {
Bindings []Binding // field 1
}
Argument is an Operation input (list of bindings). Proto: MILSpec.Argument
type ArrayDataType ¶
type ArrayDataType int32
ArrayDataType identifies Core ML multi-array element types.
const ( ArrayDataTypeInvalid ArrayDataType = 0 ArrayDataTypeFloat16 ArrayDataType = 65552 ArrayDataTypeFloat32 ArrayDataType = 65568 ArrayDataTypeDouble ArrayDataType = 65600 ArrayDataTypeInt32 ArrayDataType = 131104 ArrayDataTypeInt8 ArrayDataType = 131080 )
type ArrayFeatureType ¶
type ArrayFeatureType struct {
Shape []int64
DataType ArrayDataType
// contains filtered or unexported fields
}
ArrayFeatureType describes a Core ML multi-array feature.
type Binding ¶
Binding is either a name reference or an inline value. Exactly one of Name and Value is set; if both are, Value wins. Name has no presence bit, so an empty name is indistinguishable from an unset one and is never emitted. Proto: MILSpec.Argument.Binding
type BlobDataType ¶ added in v0.5.4
type BlobDataType uint32
BlobDataType identifies element types in MIL blob storage.
const ( BlobDataTypeFloat16 BlobDataType = 1 BlobDataTypeFloat32 BlobDataType = 2 BlobDataTypeUInt8 BlobDataType = 3 BlobDataTypeInt8 BlobDataType = 4 BlobDataTypeBFloat16 BlobDataType = 5 BlobDataTypeInt16 BlobDataType = 6 BlobDataTypeUInt16 BlobDataType = 7 BlobDataTypeInt4 BlobDataType = 8 BlobDataTypeUInt1 BlobDataType = 9 BlobDataTypeUInt2 BlobDataType = 10 BlobDataTypeUInt4 BlobDataType = 11 BlobDataTypeUInt3 BlobDataType = 12 BlobDataTypeUInt6 BlobDataType = 13 BlobDataTypeInt32 BlobDataType = 14 BlobDataTypeUInt32 BlobDataType = 15 BlobDataTypeFloat8E4M3 BlobDataType = 16 BlobDataTypeFloat8E5M2 BlobDataType = 17 )
func DataTypeToBlobDataType ¶ added in v0.5.4
func DataTypeToBlobDataType(dt DataType) (BlobDataType, error)
MILBlobDataTypeName returns the MIL DataType enum for a BlobDataType.
type BlobEntry ¶ added in v0.5.4
type BlobEntry struct {
DType BlobDataType
Data []byte
// NumElements is the logical element count. It is required for sub-byte
// element types, where the trailing partial byte must be reported in the
// metadata's padding_size_in_bits; it is ignored for byte-sized types.
NumElements int
}
BlobEntry describes a single tensor to write into a MILBlob weight file.
type BlobFileValue ¶
BlobFileValue references weight data in a blob file. Proto: MILSpec.BlobFileValue
type BlobLayout ¶
type BlobLayout int
A BlobLayout selects how a program's weights are distributed across files. Both layouts hold the same MIL Blob Storage v2 format written by WriteMILBlob; they differ only in how many blobs go in a file.
const ( // BlobLayoutSingleFile puts every tensor in one file, each at its own // offset. This is the layout coremltools produces and the one a // .mlpackage normally carries. BlobLayoutSingleFile BlobLayout = iota // BlobLayoutFilePerConst gives each tensor its own file, named for the // const that reads it. Every tensor is then the sole entry in its file and // so always sits at offset 64. BlobLayoutFilePerConst )
func (BlobLayout) String ¶
func (l BlobLayout) String() string
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
fmt.Println(coremlcompiler.BlobLayoutSingleFile)
fmt.Println(coremlcompiler.BlobLayoutFilePerConst)
}
Output: single-file file-per-const
type BlobRef ¶
A BlobRef locates one tensor's blob: the BLOBFILE path and offset the const reading it must name.
type Block ¶
type Block struct {
Inputs []NamedValueType // field 1
Outputs []string // field 2
Operations []*Operation // field 3
}
Block is a sequence of operations. Proto: MILSpec.Block
type ColorSpace ¶ added in v0.6.17
type ColorSpace int32
ColorSpace identifies an image feature's pixel format. Proto: CoreML.Specification.ImageFeatureType.ColorSpace
const ( ColorSpaceInvalid ColorSpace = 0 ColorSpaceGrayscale ColorSpace = 10 ColorSpaceRGB ColorSpace = 20 ColorSpaceBGR ColorSpace = 30 ColorSpaceGrayscaleFloat16 ColorSpace = 40 )
type CoreMLModel ¶ added in v0.5.4
type CoreMLModel struct{}
CoreMLModel wraps a loaded MLModel for inference. Only functional on darwin.
func LoadCoreMLModel ¶ added in v0.5.4
func LoadCoreMLModel(modelcPath string) (*CoreMLModel, error)
LoadCoreMLModel loads a compiled .mlmodelc from disk. Only available on darwin.
func (*CoreMLModel) Close ¶ added in v0.5.4
func (m *CoreMLModel) Close()
Close releases the CoreML model reference.
func (*CoreMLModel) Predict ¶ added in v0.5.4
func (m *CoreMLModel) Predict(inputs []PredictInput, outputName string) (*PredictOutput, error)
Predict runs inference. Only available on darwin.
type DataType ¶
type DataType int32
DataType identifies element types in MIL. Proto: MILSpec.DataType
const ( DataTypeFloat16 DataType = 10 DataTypeFloat32 DataType = 11 DataTypeFloat64 DataType = 12 DataTypeBFloat16 DataType = 13 DataTypeInt8 DataType = 21 DataTypeInt16 DataType = 22 DataTypeInt32 DataType = 23 DataTypeInt64 DataType = 24 DataTypeInt4 DataType = 25 DataTypeUInt8 DataType = 31 DataTypeUInt16 DataType = 32 DataTypeUInt32 DataType = 33 DataTypeUInt64 DataType = 34 // The sub-byte block is deliberately non-monotonic in MIL.proto; these // numbers are the wire contract, not a sorted sequence. DataTypeUInt4 DataType = 35 DataTypeUInt2 DataType = 36 DataTypeUInt1 DataType = 37 DataTypeUInt6 DataType = 38 DataTypeUInt3 DataType = 39 DataTypeFloat8E4M3FN DataType = 40 DataTypeFloat8E5M2 DataType = 41 DataTypeBool DataType = 1 DataTypeString DataType = 2 )
func ParseDataType ¶
ParseDataType returns the MIL data type spelled name, the inverse of DataType.String. It reports an error for a name MIL does not define.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
dt, err := coremlcompiler.ParseDataType("fp16")
fmt.Println(dt, err)
}
Output: fp16 <nil>
func (DataType) ArrayDataType ¶
func (dt DataType) ArrayDataType() (ArrayDataType, error)
ArrayDataType returns the Core ML multi-array element type corresponding to dt.
A multi-array carries far fewer element types than MIL has: MIL's integer widths other than int32 and int8, its sub-byte types, and its float8 types have no multi-array spelling, and dt is rejected rather than widened. A program may still use those types internally; they just cannot appear on a model input, output, or state.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
dt, err := coremlcompiler.DataTypeFloat16.ArrayDataType()
fmt.Println(dt == coremlcompiler.ArrayDataTypeFloat16, err)
}
Output: true <nil>
func (DataType) FieldForDataType ¶ added in v0.6.17
func (dt DataType) FieldForDataType() (TensorValueField, error)
FieldForDataType reports which TensorValue field an immediate constant of this element type must use, mirroring coremltools' _tensor_field_by_type. Note the asymmetry: uint32 goes to Bytes while int32 goes to Ints, and int16/uint16 go to Ints widened to int32.
type DictionaryFeatureType ¶ added in v0.6.17
type DictionaryFeatureType struct {
KeyType string
}
DictionaryFeatureType describes a dictionary boundary feature.
type DictionaryMapEntry ¶ added in v0.6.17
DictionaryMapEntry represents a key/value pair in a dictionary constant.
type DictionaryType ¶ added in v0.6.17
DictionaryType describes a MIL dictionary type.
type DictionaryValue ¶ added in v0.6.17
type DictionaryValue struct {
Entries []DictionaryMapEntry
}
DictionaryValue holds structured dictionary constants.
type Dimension ¶
type Dimension struct {
Constant uint64 // from ConstantDimension.size (field 1.1)
Unknown bool // true if UnknownDimension
Variadic bool // true if UnknownDimension.variadic is true
}
Dimension is a tensor Dimension (constant, unknown, or variadic). Proto: MILSpec.Dimension
type FeatureDescription ¶
type FeatureDescription struct {
Name string // field 1
Type *FeatureType // field 3
// contains filtered or unexported fields
}
FeatureDescription is a named, typed model feature. Proto: CoreML.Specification.FeatureDescription
func StateFeatureDescription ¶
func StateFeatureDescription(name, dataType string, shape []int64) (FeatureDescription, error)
StateFeatureDescription describes a model state, the tensor a program reads with read_state and writes with write_state.
Core ML accepts only fp16 and int8 states; a state of any other element type is rejected here rather than at load time.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
state, err := coremlcompiler.StateFeatureDescription("cache", "fp16", []int64{1, 8})
fmt.Println(state.Name, state.Type.StateArrayType.Shape, err)
}
Output: cache [1 8] <nil>
func TensorFeatureDescription ¶
func TensorFeatureDescription(name, dataType string, shape []int64) (FeatureDescription, error)
TensorFeatureDescription describes a model input or output holding a tensor of the given static shape whose element type is named the way MIL names it.
Example ¶
This example builds a compiled bundle from artifacts a MIL generator produced: the program text, the weight blobs it references, and the type of each feature named the way MIL names it.
A generator such as github.com/tmc/modelir already carries all three, so the whole adapter is the two loops below; nothing in this package needs to know the generator's types.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
// What the generator emitted.
milText := `program(1.3) {
func main<ios18>(tensor<fp16, [1, 1, 8]> x) {
tensor<fp16, [8, 8]> w = const()[name=string("w"), val=tensor<fp16, [8, 8]>(BLOBFILE(path=string("@model_path/weights/w.bin"), offset=uint64(64)))];
tensor<fp16, [1, 1, 8]> y = linear(bias=None, weight=w, x=x)[name=string("y")];
} -> (y);
}`
weights := []coremlcompiler.WeightFile{
{Path: "@model_path/weights/w.bin", Blob: make([]byte, 192)},
}
type tensor struct {
name string
dtype string // as MIL spells it
shape []int64
}
inputs := []tensor{{"x", "fp16", []int64{1, 1, 8}}}
outputs := []tensor{{"y", "fp16", []int64{1, 1, 8}}}
// The adapter.
var desc coremlcompiler.ModelDescription
for _, t := range inputs {
fd, err := coremlcompiler.TensorFeatureDescription(t.name, t.dtype, t.shape)
if err != nil {
log.Fatal(err)
}
desc.Inputs = append(desc.Inputs, fd)
}
for _, t := range outputs {
fd, err := coremlcompiler.TensorFeatureDescription(t.name, t.dtype, t.shape)
if err != nil {
log.Fatal(err)
}
desc.Outputs = append(desc.Outputs, fd)
}
tmpDir, err := os.MkdirTemp("", "coremlcompiler-example-*")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(tmpDir)
weightRoot := filepath.Join(tmpDir, "weights")
if err := coremlcompiler.WriteWeightRoot(weightRoot, weights); err != nil {
log.Fatal(err)
}
out := filepath.Join(tmpDir, "model.mlmodelc")
if err := coremlcompiler.CompileMILText(milText, 9, desc, weightRoot, out); err != nil {
log.Fatal(err)
}
_, err = os.Stat(filepath.Join(out, "weights", "w.bin"))
fmt.Println("weight in bundle:", err == nil)
// An element type Core ML multi-arrays cannot express is an error, not a
// silently substituted fp32.
_, err = coremlcompiler.TensorFeatureDescription("x", "bf16", []int64{1, 8})
fmt.Println("bf16 input:", err)
}
Output: weight in bundle: true bf16 input: coremlcompiler: feature "x": MIL type bf16 has no Core ML multi-array element type
type FeatureType ¶
type FeatureType struct {
MultiArrayType *ArrayFeatureType
ImageType *ImageFeatureType
StringType bool
Int64Type bool
DoubleType bool
DictionaryType *DictionaryFeatureType
SequenceType *SequenceFeatureType
StateArrayType *ArrayFeatureType
IsOptional bool
// contains filtered or unexported fields
}
FeatureType describes a Core ML model feature type.
type Function ¶
type Function struct {
Inputs []NamedValueType // field 1
OpSet string // field 2
BlockSpecializations map[string]*Block // field 3
Attributes map[string]*Value // field 4
}
Function is an MIL Function. Proto: MILSpec.Function
type FunctionDescription ¶ added in v0.6.17
type FunctionDescription struct {
Name string // field 1
Inputs []FeatureDescription // field 2
Outputs []FeatureDescription // field 3
States []FeatureDescription // field 6
// contains filtered or unexported fields
}
FunctionDescription describes one entry point of a multi-function model. Proto: CoreML.Specification.FunctionDescription
type ImageFeatureType ¶ added in v0.6.17
type ImageFeatureType struct {
Width int64 // field 1
Height int64 // field 2
ColorSpace ColorSpace // field 3
// contains filtered or unexported fields
}
ImageFeatureType describes an image boundary feature.
type ImmediateValue ¶
type ImmediateValue struct {
// Exactly one of these is set.
Tensor *TensorValue // field 1
Tuple *TupleValue // field 2
List *ListValue // field 3
Dictionary *DictionaryValue // field 4
}
ImmediateValue holds inline constant data. Proto: MILSpec.ImmediateValue
type ListValue ¶ added in v0.6.17
type ListValue struct {
Values []*Value // field 1
}
ListValue holds structured list constants.
type Model ¶
type Model struct {
SpecVersion int32 // field 1
Description ModelDescription // field 2
MLProgram *Program // field 502 (oneof)
// contains filtered or unexported fields
}
Model is the top-level CoreML model container. Proto: CoreML.Specification.Model
type ModelDescription ¶
type ModelDescription struct {
// Functions and DefaultFunctionName describe multi-function models.
// When Functions is non-empty the model-level Inputs/Outputs/States
// must be empty: the proto reserves them for the single-function case.
Functions []FunctionDescription // field 20
DefaultFunctionName string // field 21
Inputs []FeatureDescription // field 1
Outputs []FeatureDescription // field 10
States []FeatureDescription // field 13
Metadata *ModelMetadata // field 100
// contains filtered or unexported fields
}
ModelDescription describes model inputs, outputs, and metadata. Proto: CoreML.Specification.ModelDescription
type ModelMetadata ¶ added in v0.6.17
type ModelMetadata struct {
ShortDescription string // field 1
VersionString string // field 2
Author string // field 3
License string // field 4
UserDefined map[string]string // field 100
}
ModelMetadata carries informational model metadata. Proto: CoreML.Specification.Metadata
type MultiArrayDataType ¶
type MultiArrayDataType int
MultiArrayDataType is the CoreML multi-array element data type.
type NamedValueType ¶
NamedValueType is a (name, type) pair. Proto: MILSpec.NamedValueType
type Operation ¶
type Operation struct {
Type string // field 1
Inputs map[string]*Argument // field 2
Outputs []NamedValueType // field 3
Blocks []*Block // field 4
Attributes map[string]*Value // field 5
}
Operation is a single MIL Operation. Proto: MILSpec.Operation
type PredictInput ¶ added in v0.5.4
type PredictInput struct {
Name string
Data unsafe.Pointer
Shape []int
Strides []int
DType MultiArrayDataType
}
PredictInput is a named tensor input for CoreML prediction.
type PredictOutput ¶ added in v0.5.4
type PredictOutput struct {
Bytes []byte // copied from CoreML output buffer
Shape []int
DType MultiArrayDataType
}
PredictOutput holds the result of a CoreML prediction.
type Program ¶
type Program struct {
Version int64 // field 1
Functions map[string]*Function // field 2
Attributes map[string]*Value // field 4
}
Program is an MIL Program. Proto: MILSpec.Program
type SequenceFeatureType ¶ added in v0.6.17
type SequenceFeatureType struct {
ElementType *FeatureType
}
SequenceFeatureType describes a sequence boundary feature.
type StateType ¶
type StateType struct {
WrappedType *ValueType // field 1
}
StateType wraps a ValueType for stateful operations. Proto: MILSpec.StateType
type TensorType ¶
type TensorType struct {
DataType DataType // field 1
Rank int64 // field 2
Dimensions []Dimension // field 3
}
TensorType describes a tensor's element type and shape. Proto: MILSpec.TensorType
type TensorValue ¶
type TensorValue struct {
// Exactly one of these is set.
Floats []float32 // field 1
Ints []int32 // field 2
Bools []bool // field 3
Strings []string // field 4
Longs []int64 // field 5
Doubles []float64 // field 6
Bytes []byte // field 7
}
TensorValue holds tensor data inline. Proto: MILSpec.TensorValue
func (*TensorValue) SetField ¶ added in v0.6.17
func (tv *TensorValue) SetField() TensorValueField
SetField reports which field of tv holds data, or 0 if none does.
type TensorValueField ¶ added in v0.6.17
type TensorValueField int
TensorValueField identifies the TensorValue oneof field a MIL immediate constant of a given element type must use. Which field carries the data is fixed by the element type, not free choice: the MIL reader picks the field from the tensor's declared dtype, so a mismatch is read as an empty value.
const ( TensorValueFloats TensorValueField = iota + 1 TensorValueInts TensorValueBools TensorValueStrings TensorValueLongs TensorValueDoubles TensorValueBytes )
type TupleType ¶ added in v0.6.17
type TupleType struct {
Types []*ValueType // field 1
}
TupleType describes a MIL tuple type.
type TupleValue ¶ added in v0.6.17
type TupleValue struct {
Values []*Value // field 1
}
TupleValue holds structured tuple constants.
type Value ¶
type Value struct {
Type *ValueType // field 2
// Exactly one of these is set.
Immediate *ImmediateValue // field 3
BlobFile *BlobFileValue // field 5
}
value is an MIL value (immediate or blob reference). Proto: MILSpec.Value
type ValueType ¶
type ValueType struct {
// Exactly one of these is set.
TensorType *TensorType // field 1
ListType *ListType // field 2
TupleType *TupleType // field 3
DictionaryType *DictionaryType // field 4
StateType *StateType // field 5
}
ValueType describes a MIL value's type. Proto: MILSpec.ValueType
type WeightFile ¶
A WeightFile is one weight payload addressed by the MIL text that reads it. Path is the BLOBFILE path as it appears in the MIL text, normally rooted at ModelPathPrefix; Blob is the file's contents.
func BuildWeights ¶
func BuildWeights(tensors []WeightTensor, layout BlobLayout) ([]WeightFile, map[string]BlobRef, error)
BuildWeights places tensors into weight files according to layout. It returns the files, ready for WriteWeightRoot, and the BlobRef for each tensor keyed by name, to be used as the BLOBFILE path and offset of the const that reads it.
Tensor order is preserved, so the returned files are byte-for-byte reproducible for a given input.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/x/coremlcompiler"
)
func main() {
files, refs, err := coremlcompiler.BuildWeights([]coremlcompiler.WeightTensor{{
Name: "w", DType: coremlcompiler.BlobDataTypeFloat16,
Data: coremlcompiler.Float16Bytes([]float32{1, 2}),
}}, coremlcompiler.BlobLayoutSingleFile)
fmt.Println(len(files), refs["w"].Path, refs["w"].Offset, err)
}
Output: 1 @model_path/weights/weight.bin 64 <nil>
type WeightTensor ¶
type WeightTensor struct {
Name string
DType BlobDataType
Data []byte
NumElements int
}
A WeightTensor is one tensor to place in a program's weights.
Name is the MIL const that reads it, and names the file under BlobLayoutFilePerConst. Data is the tensor's raw little-endian payload; Float16Bytes produces it for an fp16 tensor. NumElements is required only for sub-byte element types, where the trailing partial byte has to be reported in the blob metadata.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
opschema
Package opschema holds the per-op input specifications MIL ops are declared with in coremltools.
|
Package opschema holds the per-op input specifications MIL ops are declared with in coremltools. |
|
Package nnproto encodes CoreML NeuralNetwork models (specification version 1) as .mlmodel protobuf bytes.
|
Package nnproto encodes CoreML NeuralNetwork models (specification version 1) as .mlmodel protobuf bytes. |