model

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 19 Imported by: 2 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.

README

ml

github.com/webong/ext/res/int/model is the local model package in the reusable github.com/webong/ext/res/int module. It owns portable contracts for model manifests, verified artifact installation, and bounded inference; native model backends (CoreML on Apple platforms, optional TensorFlow Lite on Android, and ONNX Runtime CPU on Windows/Linux) stay beside these contracts as platform implementations or in product adapters.

The boundary is local mechanism, not model policy:

  • callers select the model root and the model bundle to load;
  • artifact installation stages, verifies SHA-256 digests, and atomically publishes only after all checks pass;
  • inference runs through a caller-selected provider against a loaded model;
  • tensor buffers are bounded and caller-owned;
  • no model download, no provider selection, no authorization, no approval UI, no remote endpoint, and no product protocol live here.
Package What it is
ml (module root) Model manifest types, verified artifact store, model inspection, and bounded inference interfaces
ios/ (ExtML) Apple CoreML-backed model provider shipped through pkg/ext-darwin (macOS and iOS)
android/ Optional TensorFlow Lite float32 provider compiled into the pkg/ext-android AAR; NNAPI is an unavailable stub
windows/ Optional ONNX Runtime CPU backend and model.tensor/v1 guest, usable on Windows and Linux
linux/ Linux guest build of the shared ONNX Runtime CPU backend

The shared provider contract and inference schemas live in res/int/inference. Product-specific model registries, download policy, and content adapters belong to each consumer. res/int/model owns none of them.

pkg/ext-go/model exposes a language-neutral model.tensor/v1 process contract for a caller-selected ml.Provider. CTN installs and trusts those provider packages before ctn model run calls them. The Swift CoreML and .NET ONNX guests serve this contract from CTN. The Android SDK includes a ModelTensorGuest binding for app-hosted TensorFlow Lite with caller-supplied identity and authorization.

Documentation

Overview

Package ml inference defines bounded, transport-free interfaces for running on-device models through a caller-selected provider. The package owns the contracts only: it never loads a model, chooses a provider, allocates a tensor, or runs inference itself. Native providers ship beside these contracts as platform implementations (iOS CoreML in res/int/model/ios, Android NNAPI/TensorFlow Lite in res/int/model/android) or as product adapters.

Package ml defines portable, transport-free contracts for on-device model support: model manifests, verified artifact installation, model inspection, and bounded inference through a caller-selected provider.

The package owns manifest and store contracts only. It never downloads a model, chooses a provider, runs inference itself, authorizes access, or exposes a remote protocol. Native model backends ship beside this contract as platform implementations (iOS CoreML in res/int/model/ios, Android NNAPI/TensorFlow Lite in res/int/model/android) or as product adapters.

Package registry provides a thread-safe provider registry for model inference backends. Consumers register providers by name and resolve them when running inference. The registry itself knows nothing about specific provider implementations; those are registered by adapters or the host.

Package ml store implements bounded, caller-selected model artifact installation. A Store is rooted at a directory the caller selects and authorizes; the library never picks the path and never deletes anything the caller did not explicitly name.

Index

Constants

View Source
const (
	// ManifestAPIVersion is the declared version of the manifest contract.
	ManifestAPIVersion = "content.model/v1"

	// MaxManifestBytes bounds a model manifest in bytes.
	MaxManifestBytes = 64 << 10
	// MaxNameLength bounds model names, providers, roles, and file names.
	MaxNameLength = 128
	// MaxCapabilities bounds declared capabilities.
	MaxCapabilities = 32
)
View Source
const (
	// DefaultMaxArtifacts bounds the number of artifacts a model may declare.
	DefaultMaxArtifacts = 64
	// MaxArtifacts is the library ceiling for DefaultMaxArtifacts.
	MaxArtifacts = 256
	// DefaultMaxArtifactBytes bounds one artifact file in bytes.
	DefaultMaxArtifactBytes = 64 << 30
	// MaxArtifactBytes is the library ceiling for DefaultMaxArtifactBytes.
	MaxArtifactBytes = 1 << 40
	// DefaultMaxTotalBytes bounds the total bundle size in bytes.
	DefaultMaxTotalBytes int64 = 1 << 40
	// MaxTotalBytes is the library ceiling for DefaultMaxTotalBytes.
	MaxTotalBytes int64 = 1 << 50
)

Variables

View Source
var (
	// ErrUnavailable reports that a provider or session cannot perform the
	// requested operation on this platform.
	ErrUnavailable = errors.New("inference provider unavailable")
	// ErrNotLoaded reports that a session is not bound to a loaded model.
	ErrNotLoaded = errors.New("model is not loaded")
)
View Source
var (
	// ErrInvalid reports a malformed manifest, artifact, or store value.
	ErrInvalid = errors.New("invalid model value")
	// ErrNotFound reports a model or artifact that is not installed.
	ErrNotFound = errors.New("model not found")
	// ErrExist reports a model that is already installed.
	ErrExist = errors.New("model already installed")
	// ErrDigest reports a SHA-256 digest mismatch during installation or load.
	ErrDigest = errors.New("digest mismatch")
)
View Source
var ManifestAPIVersionPattern = ManifestAPIVersion

ManifestAPIVersionPattern anchors manifest version validation.

Functions

This section is empty.

Types

type Artifact

type Artifact struct {
	Role   string `json:"role"`
	File   string `json:"file"`
	SHA256 string `json:"sha256"`
}

Artifact is one file in a model bundle. Role is the semantic role (for example "model", "labels", "metadata"), File is the portable file name within the bundle directory, and SHA256 is the hex-encoded digest of the file contents.

func (Artifact) Validate

func (a Artifact) Validate() error

Validate checks artifact identity and digest format.

type ArtifactSource

type ArtifactSource interface {
	// Open returns a readable stream for the artifact. The caller must close
	// the returned reader. Open is called once per artifact.
	Open(ctx context.Context) (io.ReadCloser, error)
	// Size returns the declared byte size of the artifact, or -1 if unknown.
	Size() int64
}

ArtifactSource is a bounded, readable source for one model artifact. It is the primary installation API: callers supply streaming sources so that large artifacts can be hashed and staged without ever being held entirely in memory.

type InMemoryArtifactSource

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

InMemoryArtifactSource wraps an in-memory byte slice as an ArtifactSource. It is a convenience wrapper for small artifacts; large artifacts should use a streaming source that reads from disk or network.

func NewInMemoryArtifactSource

func NewInMemoryArtifactSource(data []byte) *InMemoryArtifactSource

NewInMemoryArtifactSource wraps data as an ArtifactSource.

func (*InMemoryArtifactSource) Open

func (*InMemoryArtifactSource) Size

func (s *InMemoryArtifactSource) Size() int64

type InstalledModel

type InstalledModel struct {
	Manifest  Manifest `json:"manifest"`
	Directory string   `json:"directory"`
}

InstalledModel is an inspected, verified model bundle. Directory is the caller-selected store directory containing the bundle.

type Manifest

type Manifest struct {
	APIVersion   string     `json:"apiVersion"`
	Name         string     `json:"name"`
	Version      string     `json:"version"`
	Provider     string     `json:"provider"`
	Capabilities []string   `json:"capabilities"`
	Artifacts    []Artifact `json:"artifacts"`
}

ModelManifest describes one model bundle. Name selects the model, Version selects the release, Provider names the native runtime that can load it, Capabilities declare what the model can do (for example "image.classify", "text.generate", "audio.transcribe"), and Artifacts list the files that make up the bundle with their SHA-256 digests.

func (Manifest) Validate

func (m Manifest) Validate() error

Validate checks manifest identity, version, capabilities, and artifacts.

type Provider

type Provider interface {
	// Name returns the provider identity.
	Name() string
	// Capabilities returns the model kinds this provider can load.
	Capabilities() []string
	// Load binds an installed model to a new session. The session is bound to
	// the exact manifest and directory returned by the store.
	Load(ctx context.Context, model *InstalledModel) (Session, error)
}

Provider is a caller-selected native model inference backend. Name reports the provider identity (for example "coreml", "nnapi", "onnxruntime", "directml"); Capabilities lists the model kinds it can load; Load binds a verified installed model to a Session.

type Reference

type Reference struct {
	Provider string
	Name     string
	Version  string
}

Reference identifies one installed model.

func ReferenceFrom

func ReferenceFrom(value string) (Reference, error)

ReferenceFrom parses a provider/name@version reference string. The provider and name may not contain '/', '@', or whitespace; the version may not contain '@' or whitespace.

func (Reference) CanonicalKey

func (r Reference) CanonicalKey() string

CanonicalKey returns a stable store key for the reference.

func (Reference) String

func (r Reference) String() string

String renders the reference as provider/name@version.

type Registry

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

Registry maps provider names to Provider implementations. It is safe for concurrent use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty provider registry.

func (*Registry) Providers

func (r *Registry) Providers() []string

Providers returns the names of all registered providers.

func (*Registry) Register

func (r *Registry) Register(name string, p Provider)

Register adds a provider to the registry under its name. Registering a provider with the same name replaces the previous one.

func (*Registry) Resolve

func (r *Registry) Resolve(name string) (Provider, error)

Resolve returns the provider registered under the given name, or ErrUnavailable if no such provider is registered.

func (*Registry) Unregister

func (r *Registry) Unregister(name string)

Unregister removes a provider from the registry.

type Session

type Session interface {
	// Infer runs one inference pass over the input tensors and returns the
	// output tensors. Inputs and outputs are bounded by the provider.
	Infer(ctx context.Context, inputs []Tensor) ([]Tensor, error)
	// Close releases the model and any native resources. It is safe to call
	// after an error and idempotent.
	Close() error
}

Session runs bounded inference against one loaded model.

type Store

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

Store manages one caller-selected model root directory. Bundles are stored under <root>/<provider>/<name>/<version>/ with a manifest.json and artifact files. The caller selects and authorizes the root; the library never picks it.

func OpenStore

func OpenStore(root string) (*Store, error)

OpenStore opens an existing caller-selected model root directory. It refuses non-directories, symlinks, and broadly writable directories.

func (*Store) Close

func (s *Store) Close() error

Close releases the directory handle held by the store. Callers should close each store they open after its operations and sessions have finished.

func (*Store) Install

func (s *Store) Install(ctx context.Context, manifest Manifest, files map[string]ArtifactSource) (*InstalledModel, error)

Install stages and installs one model bundle from streaming artifact sources. It never replaces an existing bundle: an identical manifest is reported as already installed; a different one fails with ErrExist.

Each artifact is streamed through a hash and size check as it is copied into the staging directory, so large bundles never need to be held entirely in memory. If any check fails, the staging directory is removed and no partial bundle is visible at the target path.

func (*Store) InstallFromBytes

func (s *Store) InstallFromBytes(ctx context.Context, manifest Manifest, files map[string][]byte) (*InstalledModel, error)

InstallFromBytes is a convenience wrapper around Install for small artifacts that are already in memory. It delegates to Install by wrapping each byte slice in an InMemoryArtifactSource.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]InstalledModel, error)

List returns every installed model, with digests re-verified.

func (*Store) Path

func (s *Store) Path() string

Path returns the absolute model root path.

func (*Store) Remove

func (s *Store) Remove(ctx context.Context, provider, name, version string) error

Remove deletes one installed model bundle and prunes empty provider and name directories. It refuses links and non-directories.

func (*Store) Resolve

func (s *Store) Resolve(ctx context.Context, provider, name, version string) (*InstalledModel, error)

Resolve loads one installed model and re-verifies every artifact digest against its manifest before returning. It fails closed on tampering.

type StoreLimits

type StoreLimits struct {
	MaxArtifacts     int
	MaxArtifactBytes int64
	MaxTotalBytes    int64
}

StoreLimits bound model installation. Zero values select the defaults.

type Tensor

type Tensor struct {
	Shape  []int  `json:"shape"`
	Data   []byte `json:"data"`
	Format string `json:"format"`
}

Tensor is one bounded multi-dimensional array. Shape is the dimension lengths; Data is the row-major little-endian byte buffer; Format names the element encoding (for example "float32").

func FromFloat32

func FromFloat32(shape []int, values []float32) (Tensor, error)

FromFloat32 builds a float32 tensor from a shape and values. The values are copied into little-endian bytes.

func RunModel

func RunModel(ctx context.Context, reg *Registry, store *Store, ref Reference, inputs []Tensor) ([]Tensor, error)

RunModel resolves a model from the store, selects a provider from the registry, loads a session, runs inference, and closes the session. It is the portable helper that product commands (such as ctn model run) build on. ctx is used for cancellation and timeouts.

func (Tensor) Elements

func (t Tensor) Elements() int

Elements returns the total element count of the tensor shape.

func (Tensor) Float32

func (t Tensor) Float32() []float32

Float32 returns the tensor data as float32 values. The caller must not mutate the returned slice if the tensor is shared.

func (Tensor) Validate

func (t Tensor) Validate() error

Validate checks tensor shape, format, and data alignment.

Jump to

Keyboard shortcuts

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