# `BB.Inference.ModelCodec`
[🔗](https://github.com/beam-bots/bb_inference/blob/main/lib/bb/inference/model_codec.ex#L5)

Behaviour for converting to and from one artefact's conventions.

Two artefacts of the same model family rarely agree on what they take and
give. Megvii's YOLOX ONNX takes BGR pixels from 0 to 255, letterboxed; a
TFLite conversion of the same network takes RGB with ImageNet's
per-channel mean and standard deviation. So the codec belongs to the
artefact - it is declared on the `model` - and its options carry the
input conventions, with the codec's own defaults for whichever artefact it
was written against:

    model :detector do
      runtime BB.Inference.TFLite
      source "..."
      codec {BB.Estimator.Yolo.YoloX, colour: :rgb, mean: {123.675, 116.28, 103.53}}
    end

## Lifecycle

1. At compile time, the model's codec options are validated against
   `options_schema/0`, and every component naming the model is checked
   against `task/0`.
2. When the model has loaded, its process calls `fit/2` with the runtime's
   description. A codec that doesn't fit stops the model with a
   `BB.Error.Invalid.Inference.CodecMismatch` saying what it expected and
   what it found.
3. For each inference, the component calls `BB.Inference.infer/4`, which
   calls `encode/2`, runs the model and calls `decode/3`, in the component's
   process.

## Tasks

`task/0` is the contract between the codec and the components that use it:
what `encode/2` accepts and what `decode/3` returns are defined by whoever
defines the task. `:object_detection` is defined by
`bb_estimator_object_detection`.

# `context`

```elixir
@type context() :: term()
```

# `state`

```elixir
@type state() :: term()
```

# `tensors`

```elixir
@type tensors() :: %{required(String.t()) =&gt; Nx.Tensor.t()}
```

# `decode`

```elixir
@callback decode(tensors(), context(), state()) :: {:ok, term()} | {:error, term()}
```

Convert the model's named outputs into a task result.

# `encode`

```elixir
@callback encode(input :: term(), state()) ::
  {:ok, tensors(), context()} | {:error, term()}
```

Convert a task input into the model's named inputs, and a context that
`decode/3` will receive with this input's outputs.

# `fit`

```elixir
@callback fit(BB.Inference.Description.t(), opts :: keyword()) ::
  {:ok, state()} | {:error, String.t()}
```

Check the codec fits a model, and prepare whatever it needs to encode and
decode.

`opts` have been validated against `options_schema/0`. On a mismatch,
return a sentence saying what was expected; the caller adds what was found.

# `options_schema`

```elixir
@callback options_schema() :: Spark.Options.t() | keyword()
```

The options the codec accepts on the model's `codec`, with its defaults.

# `task`

```elixir
@callback task() :: atom()
```

The task this codec performs, such as `:object_detection`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
