Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 19 — Training Models with Axon

Axon builds neural networks as composable Nx.Defn functions. Models are data — an init function plus a predict function — not mutable objects.

# Model = {init_fn, predict_fn}
{init_fn, predict_fn} = Axon.build(model, compiler: EXLA)
flowchart LR
    SPEC["Axon model spec<br/>(composable data)"] --> BUILD["Axon.build"]
    BUILD --> INIT["init_fn<br/>shape → params"]
    BUILD --> PRED["predict_fn<br/>params + input → output"]
    INIT --> LOOP["Axon.Loop.trainer<br/>grad → optimizer step<br/>per batch · per epoch"]
    PRED --> LOOP
    LOOP --> STATE["trained_state<br/>params + optimizer_state"]
    STATE -->|"resume anytime"| LOOP
    PRED --> EVAL["Axon.Loop.evaluator<br/>no gradients"]

If you’ve written gen_server state loops, this shape is familiar: pure functions threaded through an explicit state value — no hidden training session object, no side effects between steps.

19.0 Setup

Every example in this chapter needs these. In a Livebook cell, or in mix.exs for a project:

Mix.install([
  {:axon, "~> 0.8"},
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:scidata, "~> 0.1"},      # MNIST downloads (§19.1)
  {:polaris, "~> 0.1"},      # optimizers and schedules (§19.1)
  {:vega_lite, "~> 0.1"}     # loss curves (§19.5)
  # {:bumblebee, "~> 0.7"}   # §19.4 fine-tuning only
])

Axon.Loop.run/4 requires a real compiler — passing Nx.BinaryBackend as the compiler raises expected compiler callback __jit__/5 is missing. Use EXLA, or drop compiler: and let the default apply.

19.1 MNIST End-to-End (The Canonical Walkthrough)

Step 1 — Data

# Livebook/IEx: global, so Tasks and spawned processes inherit it.
# In a Mix project use `config :nx, :default_backend, EXLA.Backend` instead.
Nx.global_default_backend(EXLA.Backend)

{images, labels} = Scidata.MNIST.download()   # 60k 28x28 grayscale digits
{image_data, image_type, _shape} = images
{label_data, label_type, label_shape} = labels

images =
  image_data
  |> Nx.from_binary(image_type)
  |> Nx.divide(255)                 # normalize to [0,1]
  |> Nx.as_type(:f32)               # u8→f32 explicitly; loss fns expect floats
  |> Nx.reshape({60000, 784})       # flatten 28x28 → 784

labels =                             # one-hot: {60000, 10}
  label_data
  |> Nx.from_binary(label_type)
  |> Nx.reshape(label_shape)
  |> Nx.new_axis(-1)
  |> Nx.equal(Nx.tensor(Enum.to_list(0..9)))
  |> Nx.as_type(:f32)               # comparison yields u8 — cast it

Why each step matters:

  • Nx.from_binary/2 turns raw bytes into a typed tensor.
  • /255 normalization helps gradient descent converge.
  • One-hot via a broadcast Nx.equal/2 producing {60000, 10} of 0.0/1.0.
  • The two as_type(:f32) calls are not decoration: /255 on a u8 tensor yields f32 already, but Nx.equal/2 returns u8 (0/1). Loss functions want floats, and an implicit promotion there is exactly the silent step Erlang developers distrust. (Nx.iota({1, 10}) also works, but the explicit tensor reads closer to Scidata’s own README.)

Scidata deserves a nod for Erlang veterans: it downloads, verifies, and decodes the dataset into raw binaries — the “fetch bytes, parse once, share everywhere” pattern as file:read_file plus a cached table, except the cache is the tensor itself. Normalization is not cosmetic: inputs in [0, 1] keep gradients well-scaled; raw 0–255 magnitudes make SGD oscillate before it learns anything.

Step 2 — Split & batch lazily

# Scidata.MNIST.download() returns the 60k TRAIN set only. The canonical
# 10k test set is a separate call: Scidata.MNIST.download_test().
#
# The manual split below stays self-contained (one download, and it exercises
# slice_along_axis) at the cost of not being the official split — fine for a
# first run, wrong for a number you intend to publish.
train_images = Nx.slice_along_axis(images, 0, 50_000)
train_labels = Nx.slice_along_axis(labels, 0, 50_000)

test_images = Nx.slice_along_axis(images, 50_000, 10_000)
test_labels = Nx.slice_along_axis(labels, 50_000, 10_000)

batch_size = 64

train_data =
  train_images
  |> Nx.to_batched(batch_size, leftover: :discard)   # lazy Stream of batches
  |> Stream.zip(Nx.to_batched(train_labels, batch_size, leftover: :discard))

test_data =
  test_images
  |> Nx.to_batched(batch_size, leftover: :discard)
  |> Stream.zip(Nx.to_batched(test_labels, batch_size, leftover: :discard))

Stream.zip yields {image_batch, label_batch} tuples; only one batch is in memory at a time.

Peek at the mechanics, because they shape everything downstream. Nx.to_batched/3 takes a :leftover option:

# default: leftover: :repeat — a short final batch is padded up to full size
Nx.to_batched(t, 64)
# :discard — drop the tail instead, so every batch is exactly 64
Nx.to_batched(t, 64, leftover: :discard)

There is no discard: true option — keyword! rejects it with unknown key :discard. That distinction decides whether your training loop recompiles: with the default padding you get constant shapes, so the kernel compiled for batch one serves every batch and you recompile zero times mid-epoch. Be explicit either way rather than relying on the default.

Peak activation memory is batch_size × 784 × 4 bytes, not dataset-sized; the lazy stream is the whole reason.

Step 3 — Model

mnist_model =
  Axon.input("input", shape: {nil, 784})   # nil = dynamic batch dim
  |> Axon.dense(128, activation: :relu)
  |> Axon.dropout(rate: 0.2)
  |> Axon.dense(64, activation: :relu)
  |> Axon.dropout(rate: 0.2)
  |> Axon.dense(10, activation: :softmax)

template = Nx.template({1, 784}, :f32)
Axon.Display.as_graph(mnist_model, template)   # Mermaid graph in Livebook
LayerPurpose
Axon.input/2Input spec with dynamic batch
Axon.dense/3activation(x @ W + b)
Axon.dropout/2Regularization during training

Parameter counting is a useful literacy exercise — multiply connected dims, add biases:

dense 784→128:  784 × 128 + 128 = 100,480
dense 128→64:   128 ×  64 +  64 =   8,256
dense 64→10:     64 ×  10 +  10 =     650
                                --------
total                           109,386

Roughly 109k trainable floats ≈ 437KB in f32 — small enough to train on a laptop CPU, which is why MNIST remains the canonical first run. Dropout zeroes a random fraction (rate) of activations per training step — noise that discourages co-adaptation — and disables itself at inference time.

Step 4 — Train & evaluate with Axon.Loop

trained_state =
  mnist_model
  |> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.run(train_data, %{}, epochs: 10, compiler: EXLA)

mnist_model
|> Axon.Loop.evaluator()          # no gradients, no optimizer state
|> Axon.Loop.metric(:accuracy)
|> Axon.Loop.run(test_data, trained_state, compiler: EXLA)

The builder pipeline reads top-down, and each stage is just data:

  1. trainer/3 fixes loss + optimizer and installs the gradient step.
  2. metric/3 accumulates named statistics per iteration.
  3. run/4 drives the loop: batch → forward → grad → update → report.

Nothing hides in macro magic — the loop is a reduction over your stream with a state struct threaded through. That is why you can inject callbacks anywhere (§19.5) or abandon it for §19.2’s manual version.

Two contract details worth pinning down:

  • run/4 returns an %Axon.ModelState{} — params, trainable state, and the data/telemetry counters — not an Axon.Loop.State. The struct has no :step_state field. Passing that return value straight back into evaluator |> run(data, ...) is correct, and the evaluator needs exactly this: a container the model can use as its parameters.

  • Passing %{} as init is deprecated — you will see passing parameter map to initialization is deprecated, use %Axon.ModelState{} instead. There is no ModelState.init/1. To build one from a parameter map, use Axon.ModelState.new/1:

    # resuming: you already HAVE a ModelState from a previous run/4
    trained_state = Axon.Loop.run(loop, data, previous_state, epochs: 5)
    
    # building from raw params: new/1 takes a map of tensors, not the model
    state = Axon.ModelState.new(%{"dense_0" => %{kernel: w, bias: b}})
    

    For a from-scratch run %{} still works; for code you intend to keep, thread the ModelState returned by run/4.

Because run/4 hands back the model state directly, trained_state can be passed into run/4 again to resume training later.

Optimizers beyond SGD come from Polaris: Polaris.Optimizers.adam(learning_rate: 0.001).

Defaults before dogma:

Problem shapeLossOptimizer starting point
Multi-class classificationcategorical cross entropyAdam @ 1e-3
Binary / sigmoid outputbinary cross entropySGD + momentum @ 1e-2
Regressionmean squared errorAdam @ 1e-3
Fine-tuning pre-trainedtask lossAdamW @ 1e-5–1e-4

Adam converges with little tuning; SGD rewards schedules and momentum with slightly better generalization. On MNIST-scale problems either clears 95% quickly — the engineering margin lives in data handling, metrics, and serving (Ch 21), not in optimizer micro-choice.

Step 5 — Single-image inference

{_, predict_fn} = Axon.build(mnist_model, compiler: EXLA)

{test_batch, _} = Enum.at(test_data, 0)
test_image = Nx.slice_along_axis(test_batch, 0, 1)    # keep batch dim {1, 784}

test_image
|> predict_fn.(trained_state)     # params first, then input
|> Nx.argmax()
#=> 7 (predicted digit)

predict_fn/2 takes (params, input) — no then/2 needed, and no pipe required. Models always expect batched input, which is why the slice keeps the {1, 784} dimension rather than flattening it to {784}.

19.2 Custom Training Loop With defn + grad

When you need non-standard losses or full control over the update:

defmodule CustomTrainer do
  import Nx.Defn

  defn train_step(x, y, w, b, lr) do
    {w, b} =
      grad({w, b}, fn {w, b} ->
        y_pred = Nx.dot(x, w) + b
        Nx.mean(Nx.pow(y_pred - y, 2))
      end)
      |> then(fn {grad_w, grad_b} -> {w - lr * grad_w, b - lr * grad_b} end)

    {w, b}
  end
end

key = Nx.Random.key(42)
{x, key} = Nx.Random.normal(key, 0.0, 1.0, shape: {128, 3})
{y, _key} = Nx.Random.normal(key, 0.0, 1.0, shape: {128})

w = Nx.broadcast(0.0, {3})
b = Nx.tensor(0.0)
lr = Nx.tensor(0.01)

# thread the parameters through the loop — a `for` body rebinds only
# within its own iteration, so plain `for` would train ONE step 100 times:
{w, b} =
  Enum.reduce(1..100, {w, b}, fn _, {w, b} ->
    CustomTrainer.train_step(x, y, w, b, lr)
  end)

Three details repay attention. The update is pure: parameters in, new parameters out — the reduce threads them explicitly, nothing mutates. The learning rate is a tensor, not a float, so it joins the compiled graph instead of forcing a host round-trip per step. And the whole step compiles as one kernel chain: gradient, scale, and subtract fuse under EXLA exactly as written.

When to use which:

  • Axon.Loop → standard supervised learning (batching, metrics, callbacks)
  • defn + grad → custom losses, gradient surgery, RL, research experiments

19.3 CNNs for Spatial Data

cnn_model =
  Axon.input("images", shape: {nil, 28, 28, 1})
  |> Axon.conv(32, kernel_size: {3, 3}, activation: :relu)
  |> Axon.max_pool(kernel_size: {2, 2})
  |> Axon.conv(64, kernel_size: {3, 3}, activation: :relu)
  |> Axon.max_pool(kernel_size: {2, 2})
  |> Axon.flatten()
  |> Axon.dense(128, activation: :relu)
  |> Axon.dropout(rate: 0.5)
  |> Axon.dense(10, activation: :softmax)

Shape flow (NHWC):

LayerInOut
input{? ,28,28,1}same
conv 32×3×3 (valid pad){? ,28,28,1}{? ,26,26,32}
max_pool 2×2{? ,26,26,32}{? ,13,13,32}
conv 64×3×3{? ,13,13,32}{? ,11,11,64}
max_pool 2×2{? ,11,11,64}{? ,5,5,64}
flatten{? ,5,5,64}{? ,1600}
dense 128 / dropout / dense 10{? ,1600}{? ,10}

Reshape flat data first: Nx.reshape(train_images, {50000, 28, 28, 1}). Train exactly as in Step 4 with the reshaped data.

Two rules regenerate the whole shape table: valid convolution subtracts kernel − 1 from each spatial dim (28 → 26, 13 → 11), and pooling floors a division by the stride (26 → 13, 11 → 5). Channel count moves only where conv declares it. Walk any architecture through those numbers before compiling — shape errors surface at trace time, and reading such tables fluently turns cryptic messages into ten-second fixes.

Why convolutions beat dense on images: flattening destroys locality, forcing a dense layer to relearn that neighboring pixels correlate. Convolutions hard-code local receptive fields with few weights (3×3×channels) and pool for shift tolerance — one function applied across positions, the same reuse-over-copy instinct as good Erlang.

19.4 Transfer Learning With Bumblebee Weights

Ch 20 is the full Bumblebee tour; here it appears only as a source of pre-trained weights. The data pipeline must be rewired — §19.1’s MNIST stream yields {images {B, 784}, one_hot_labels}, and a ViT expects {B, 224, 224, 3} with integer class labels. Reusing train_data here fails on shape before it ever reaches the loss.

num_classes = 2

# 1. Load spec with a classification head, set your label count.
# id_to_label drives Bumblebee's own postprocessing — an empty map yields
# "LABEL_0"/"LABEL_1" placeholders.
{:ok, spec} =
  Bumblebee.load_spec({:hf, "google/vit-base-patch16-224"},
    architecture: :for_image_classification
  )

spec = Bumblebee.configure(spec, num_labels: num_classes,
                                 id_to_label: %{0 => "cat", 1 => "dog"})

# 2. Load pre-trained weights; head is freshly initialized
{:ok, model_info} =
  Bumblebee.load_model({:hf, "google/vit-base-patch16-224"}, spec: spec)

%{model: vit_model, params: params} = model_info

# 3. Extract logits output
logits_model = Axon.nx(vit_model, & &1.logits)

# 4. Train with Axon.Loop.
# sparse: true expects INTEGER labels {B}, not one-hot {B, C}. If your stream
# yields one-hot, drop sparse: and pass the dense matrix instead.
loss = &Axon.Losses.categorical_cross_entropy(&1, &2,
  reduction: :mean, from_logits: true, sparse: true)

optimizer = Polaris.Optimizers.adam(learning_rate: 5.0e-5)

loop =
  logits_model
  |> Axon.Loop.trainer(loss, optimizer, log: 1)
  |> Axon.Loop.metric(:accuracy)

# train_data here is a NEW stream yielding {images {B,224,224,3} f32, labels {B} s32}
# — not §19.1's MNIST stream.
Axon.Loop.run(loop, image_data, params, epochs: 3, compiler: EXLA)

strict?: false is off by default; leaving it on means the loop raises on any JIT cache miss. Keep it on unless you are deliberately tolerating per-shape recompiles.

Backbone stays pre-trained; only the new head learns — the standard fine-tuning entry point.

Fine-tune in phases: a freshly initialized head emits large gradients that would wreck pre-trained backbone weights on contact.

  1. Warm up the head. Train a few epochs with the backbone effectively frozen — a tiny learning rate on the whole state, or per-parameter updates that skip backbone tensors.
  2. Unfreeze gently. Continue full-state training at a much lower rate (1e-5 territory) so pre-trained representations drift, not jump.

Head-only training solves most adaptation tasks; escalate to phase two only when validation accuracy plateaus below target. Every epoch spent relearning general features is an epoch wasted.

19.5 Watching Training: Metrics History

alias VegaLite, as: Vl
{:ok, history_agent} = Agent.start_link(fn -> [] end)

trained_state =
  mnist_model
  |> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.handle_event(:iteration_completed, fn state ->
    Agent.update(history_agent, &[state.metrics | &1])
    {:continue, state}
  end)
  |> Axon.Loop.run(train_data, %{}, epochs: 10)

history = Agent.get(history_agent, & &1) |> Enum.reverse()

# `state.metrics` is a string-keyed map of *tensors* — convert before plotting,
# or VegaLite receives `%Nx.Tensor{}` structs it cannot serialize.
losses     = Enum.map(history, &Nx.to_number(&1["loss"]))
accuracies = Enum.map(history, &Nx.to_number(&1["accuracy"]))

Plot with VegaLite’s fold trick (wide → long format):

Vl.new(title: "Training Metrics", width: 600, height: 300)
|> Vl.data_from_values(
     epoch: Enum.to_list(1..length(losses)),   # one entry per recorded metric
     loss: losses,
     accuracy: accuracies
   )
|> Vl.transform(fold: ["loss", "accuracy"], as: ["metric", "value"])
|> Vl.mark(:line, point: true)
|> Vl.encode_field(:x, "epoch", type: :quantitative)
|> Vl.encode_field(:y, "value", type: :quantitative)
|> Vl.encode_field(:color, "metric", type: :nominal)
|> Kino.VegaLite.new()

In Livebook, Axon.Loop.kino_vega_lite_plot/4 pushes each iteration’s metric to a Kino.VegaLite plot in one call — worth using instead of the hand-rolled history agent when you only want a curve. Keep the manual version when you need the history for something else (checkpoint decisions, exports).

Reading a Confusion Matrix

Loss curves say how much the model is learning; a confusion matrix says what it confuses. Collect {true, predicted} pairs on the test set and plot counts as a heatmap:

labels = Enum.map(0..9, &Integer.to_string/1)
counts = [
  [972,   0,   1,   0,   0,   2,   3,   1,   1,   0],
  [  0,1121,   3,   2,   0,   1,   2,   2,   4,   0],
  [  1,   2, 986,   6,   2,   1,   3,   6,   3,   0],
  # … rows = true digit, columns = predicted digit
]

rows =
  for {row, i} <- Enum.with_index(counts),
      {v, j} <- Enum.with_index(row),
      v > 0 do
    %{actual: Enum.at(labels, i), predicted: Enum.at(labels, j), count: v}
  end

Vl.new(width: 400, height: 300)
|> Vl.data_from_values(rows)
|> Vl.mark(:rect)
|> Vl.encode_field(:x, "predicted", type: :nominal)
|> Vl.encode_field(:y, "actual", type: :nominal)
|> Vl.encode_field(:color, "count", type: :quantitative)
|> Vl.config(view: [stroke: nil])

The bright diagonal is correct predictions; off-diagonal mass is the error budget. A dark cell at (true 4, predicted 9) points at specific data (4s that look like 9s) rather than generic underfitting — which tells you whether the fix is more data for that pair, augmentation, or capacity.

Overfitting: Signs and Remedies

Train accuracy climbing while test accuracy stalls or falls is the signature of memorization. Remedies, ordered by usual payoff: more or more diverse data, then regularization (dropout, weight decay), then a smaller model, then stopping earlier. Read the plotted gap: widening means memorizing; both curves low means underfitting — the answer there is capacity or training time, not regularization.

When NOT to Use Axon: Scholar and the Manual Loop

Axon is for neural networks. For classical ML — logistic regression, decision trees, k-means, a tabular model with a few thousand rows — the right tool is Scholar, which implements scikit-learn’s algorithms as defn functions on the same backends (Ch 13 §13.4, lab LAB2):

model = Scholar.Linear.LogisticRegression.fit(x, y, num_classes: 2)

Reach for Axon when the architecture is what you are designing (convolutions, attention, embeddings). Reach for Scholar when the algorithm is the thing and the architecture is a row of coefficients.

Validation Split and Early Stopping

Axon.Loop.validate/3 evaluates the model on held-out data after each epoch, emitting validation_* metrics:

{:ok, best} = Agent.start_link(fn -> %{loss: :infinity, epoch: 0} end)

trained_state =
  mnist_model
  |> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.validate(mnist_model, val_data)
  |> Axon.Loop.handle_event(:epoch_completed, fn state ->
    val_loss = state.metrics["validation_loss"]

    if val_loss < Agent.get(best, & &1.loss) do
      Agent.update(best, fn _ -> %{loss: val_loss, epoch: state.epoch} end)
      persist_checkpoint(state)   # your save call — see §19.7
    end

    {:continue, state}
  end)
  |> Axon.Loop.run(train_data, %{}, epochs: 30)

Keep the best-seen ModelState (not merely its loss) and restore it after the run — late epochs often regress past the optimum.

Halt atoms. An event handler must return {status, state} where status is one of exactly three atoms:

:continue     # continue this epoch and keep looping
:halt_epoch   # end this epoch, start the next
:halt_loop    # stop entirely

There is no {:halt, state} — {:halt, state} is not a valid return and will not stop the loop. {:halt_loop, state} is the hard stop you want.

And you probably should not hand-roll it: Axon ships both of these, and they handle the metric comparison and patience bookkeeping correctly.

mnist_model
|> Axon.Loop.trainer(:categorical_cross_entropy, :sgd)
|> Axon.Loop.validate(mnist_model, val_data)
|> Axon.Loop.early_stop("validation_loss", mode: :min, patience: 3)
|> Axon.Loop.checkpoint(criteria: "validation_loss",
                        path: "checkpoints",
                        mode: :min, patience: 5)
|> Axon.Loop.run(train_data, %{}, epochs: 30)

Axon.Loop.checkpoint/2 is also the right answer to “how do I persist the best model” — see §19.7.

19.6 Custom Layers

gelu_plus_act = fn x, _key -> Axon.Activations.gelu(x) end

dense_with_bias = fn x, w, b, _key -> Nx.add(Nx.dot(x, w), b) end

input = Axon.input("input", shape: {nil, 128})
w = Axon.param("w", {128, 64}, initializer: :glorot_uniform)
b = Axon.param("b", {64})

model =
  input
  |> then(&Axon.layer(gelu_plus_act, [&1]))           # input only
  |> then(&Axon.layer(dense_with_bias, [&1, w, b]))   # input + params
  |> Axon.dense(10, activation: :softmax)

Rules: layer functions receive inputs plus a trailing random key; Axon.param/2 declares learnable parameters (initializers: :glorot_uniform, :he_normal, :zeros, …). Use for novel activations, attention variants, or wrapping raw Nx ops.

19.7 Saving and Loading Trained Models

An Axon.ModelState is tensors plus the model spec, so persistence reduces to serialization — with one non-negotiable step. You must copy every tensor to Nx.BinaryBackend first. Axon.ModelState derives Nx.Container, so the built-in copy walks the whole parameter tree for you (verified on axon 0.8.1 / nx 0.13.1):

host_state = Nx.backend_copy(trained_state, Nx.BinaryBackend)

File.write!("mnist_state.term", :erlang.term_to_binary(host_state))

restored = "mnist_state.term" |> File.read!() |> :erlang.binary_to_term()

Skip the copy and it appears to work — term_to_binary succeeds, the file has bytes, and the reload produces a struct. Then the first inference raises:

** (RuntimeError) Invalid buffer passed to Execute() ... Buffer has been deleted or donated.

Because the serialized payload was an EXLA device reference, not data. Nx.backend_copy/2 and Nx.backend_transfer/2 both recurse through Nx.Container structs, maps, and tuples, so the single call above reaches every nested parameter (Nx.Container is the protocol for exactly this job).

Prefer Axon’s own facility when you can — it handles the serialization for you:

|> Axon.Loop.checkpoint(criteria: "validation_loss", path: "checkpoints", mode: :min)

Caveats separating toys from production:

  • Tensor payloads survive term_to_binary as plain binaries (stable across OTP releases), but treat the wrapper as a BEAM-internal format.
  • Ch 21’s ML.Persistence goes further with explicit type+shape encoding so loads are backend-agnostic.
  • Store the model spec alongside the parameters; parameters without their graph are opaque bytes. Pair saved model blobs with JSON metadata (saved_at, shapes, training config) — Ch 21’s blueprint shows the pattern.

For cross-language interop, export raw tensors (Nx.to_binary/1 per parameter plus a manifest) rather than hoping for framework-level formats.

Explore More

Checkpoint

  1. What two functions does Axon.build/2 return?
  2. Why keep the batch dimension when predicting on one image?
  3. Where does the classification head’s initial weight come from in transfer learning?
Answers
  1. {init_fn, predict_fn} — parameter initialization and pure forward pass.
  2. Compiled graphs are shape-specialized for batched inputs; {1, 784} preserves the expected rank.
  3. It doesn’t — it is randomly initialized (spec: load keeps only backbone weights); you train it on your labels.

Next: Chapter 20 — Bumblebee: Pre-trained Models