<!--
SPDX-FileCopyrightText: 2026 James Harton

SPDX-License-Identifier: Apache-2.0
-->

# BB.Inference Usage Rules

`bb_inference` lets a [Beam Bots](https://hexdocs.pm/bb) robot declare
machine-learning models, fetches their artefacts at build time, and runs
them through a runtime from another package. For framework basics see
`bb`'s rules. This file covers only what is specific here.

## Core principles

1. **A model is a controller.** Each `model` becomes a robot-level
   controller of the same name. Its name must be unique among every
   controller, sensor, actuator, link and joint, and its restarts count
   against the topology's budget.
2. **The codec belongs to the model.** How to prepare inputs and read
   outputs depends on the artefact, not on the model family. Put input
   conventions (colour order, mean, standard deviation, letterboxing) in the
   model's `codec` options, never in the component.
3. **Components name a model; they don't configure one.** A component takes
   the model's name through an option typed `BB.Inference.model_ref(task)`,
   and gets everything else from `BB.Inference.loaded_model/2`.
4. **Artefacts are fetched by the build.** The `:bb_inference` compiler must
   be in `compilers:`, after the Elixir compiler. A model whose download
   failed builds with a warning and fails to load at runtime.
5. **Runtimes pass raw values.** A quantised model takes and gives raw
   integers. The codec quantises and dequantises, and should dequantise only
   what it reads.
6. **Models are omitted in simulation** unless declared `simulation :start`.

## Wiring it in

```elixir
defmodule MyRobot do
  use BB, extensions: [BB.Inference]

  inference do
    model :detector do
      runtime BB.Inference.OpenCV
      source "https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_nano.onnx"
      sha256 "c789161ed43c8269fcd4e67c67eeeb4e80c622da2eb296a20bc6007bd18a0b7d"
      codec BB.Estimator.Yolo.YoloX
    end
  end
end
```

```elixir
# mix.exs
compilers: Mix.compilers() ++ [:bb_inference]
```

A component naming a model:

```elixir
use BB.Estimator,
  options_schema: [
    model: [type: BB.Inference.model_ref(:object_detection), required: true]
  ]

# in handle_continue/2, not init/1 - loading may still be in progress
{:ok, loaded} = BB.Inference.loaded_model(robot, model)

# per input
{:ok, result} = BB.Inference.infer(robot, loaded, input)
```

## The model

| Option | | |
|---|---|---|
| `runtime` | required | `Module` or `{Module, opts}` implementing `BB.Inference.Runtime` |
| `source` | required | URL or project-relative path |
| `sha256` | required for URLs | Hex SHA-256 of the artefact (of the member, for an archive) |
| `archive_member` | for archives | Path inside a `.zip`, `.tar`, `.tar.gz` or `.tgz` |
| `codec` | required | `Module` or `{Module, opts}` implementing `BB.Inference.ModelCodec`; opts validated at compile time |
| `labels` | `[]` | Class labels by index |
| `simulation` | `:omit` | `:omit` or `:start` |

## Writing a runtime

Implement `load/2`, `describe/1`, `run/2` and `can?/1`, and `unload/1` if
your resources can be released deterministically. Report what you can in
`describe/1` and leave the rest `nil`; report outputs in the model's order.
Return `{:error, reason}` from `load/2` rather than raising.

## Writing a codec

Implement `task/0`, `options_schema/0`, `fit/2`, `encode/2` and `decode/3`.
`fit/2` returns `{:error, "what I expected"}` on a mismatch; the caller adds
what was found. Read the task's contract from the package that defines it.

## Anti-patterns

- **Calling `BB.Inference.loaded_model/2` in `init/1`.** It waits for the
  model to load, which blocks the robot's start-up. Use `handle_continue/2`.
- **Converting whole tensors in Nx.** Quantising a camera frame in Nx's
  binary backend takes hundreds of milliseconds. Use OpenCV, or read values
  lazily.
- **Putting input conventions in a component.** Swapping the artefact then
  means editing every component that uses it.
- **Declaring `simulation :start` to silence a simulation failure** for a
  model that needs hardware to load. The component will fail differently.
- **Leaving `sha256` off a local artefact you also ship elsewhere.** Without
  it, nothing checks the file the build placed is the one you meant.

## Further reading

- [Hexdocs](https://hexdocs.pm/bb_inference)
- `BB.Inference`, `BB.Inference.Runtime`, `BB.Inference.ModelCodec`,
  `BB.Inference.ModelController`, `Mix.Tasks.Compile.BbInference`
