BB.Inference.Runtime behaviour (bb_inference v0.1.0)

Copy Markdown View Source

Behaviour for loading and executing a model artefact.

A runtime is only ever called from the model's own process, BB.Inference.ModelController: load/2 once, then describe/1 and run/2 for as long as the process lives, and unload/1, if the runtime defines it, when the process stops.

Raw values

run/2 takes and returns tensors in the model's own types. A quantised model takes and gives raw integers: the runtime reports each tensor's scale and zero point through describe/1, and never quantises or dequantises. The model's codec does that, where it is cheap - see BB.Inference.Quantisation.

Capabilities

can?/1 answers questions about what the runtime supports, after Ash.DataLayer.can?/2. Capabilities in use:

  • :describe_names, :describe_shapes, :describe_types, :describe_layout, :describe_quantisation - whether describe/1 reports that field
  • {:format, format} - whether it loads artefacts in format, such as :onnx or :tflite
  • {:accelerator, accelerator} - whether it can confirm it is running on accelerator
  • :unload - whether unloading frees the model's resources deterministically

An unknown capability is false.

Summary

Callbacks

Whether the runtime supports capability.

Describe the loaded model. Fields the runtime cannot report are nil.

Load the artefact at path, with the options given on the model's runtime.

Run the model on named inputs, returning named outputs, in the model's own types.

Release what load/2 acquired. Called when the model's process stops, including when its supervisor shuts it down. A runtime whose resources are only released by garbage collection leaves it undefined.

Types

capability()

@type capability() :: atom() | {atom(), term()}

handle()

@type handle() :: term()

Callbacks

can?(capability)

@callback can?(capability()) :: boolean()

Whether the runtime supports capability.

describe(handle)

@callback describe(handle()) :: BB.Inference.Description.t()

Describe the loaded model. Fields the runtime cannot report are nil.

load(path, opts)

@callback load(path :: Path.t(), opts :: keyword()) :: {:ok, handle()} | {:error, term()}

Load the artefact at path, with the options given on the model's runtime.

run(handle, map)

@callback run(handle(), %{required(String.t()) => Nx.Tensor.t()}) ::
  {:ok, %{required(String.t()) => Nx.Tensor.t()}} | {:error, term()}

Run the model on named inputs, returning named outputs, in the model's own types.

unload(handle)

(optional)
@callback unload(handle()) :: :ok

Release what load/2 acquired. Called when the model's process stops, including when its supervisor shuts it down. A runtime whose resources are only released by garbage collection leaves it undefined.