# Lab 1 — Nx Optimization: Tilting Solar Panels with Autodiff

## Section

Chapters 17 and 18 explained tensors, `defn`, gradients, and backends. This lab makes you
*use* them on a problem that is not a toy function on a whiteboard:
squeezing daily energy out of a solar tracker. Every example is new — we
optimize the daily energy output of a solar panel by finding its best
tilt angle, then fit the panel's calibration curve from noisy sensor
readings, and finally benchmark backends.

> **From Erlang you know:** `grad/2` is the numerical analogue of writing
> a derivative by hand in a paper you never trust again. You hand over the
> *forward* definition; the machine derives the rest. Nothing here mutates
> state — the ascent loop threads a tensor like a fold over a list.

## What You'll Build

1. **Gradient ascent on tilt angle** — find the tracker angle that
   maximizes daily energy, starting from a bad guess, using only the
   forward model and `grad/2`.
2. **A calibration fit from noisy sensors** — two parameters, one `defn`
   loss, gradients returned in a *map container*.
3. **A backend benchmark** — the same `defn` under `Nx.BinaryBackend` and
   EXLA, timed with Benchee.

```elixir
Mix.install([
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:kino, "~> 0.14"},
  {:vega_lite, "~> 0.1"},
  {:kino_vega_lite, "~> 0.1"},
  {:benchee, "~> 1.3"}
])
```

## Section 1 — Sensor readings as tensors

A solar farm reports hourly readings: panel tilt (degrees) and measured
irradiance (kW/m²). Pack one hour's readings into a tensor and broadcast
a unit-conversion (kJ → kWh) over the whole day.

```elixir
Nx.global_default_backend(EXLA.Backend)

tilts =
  Nx.tensor([
    [20.0, 25.0, 30.0, 35.0],          # morning set-point sweep
    [40.0, 45.0, 50.0, 55.0]           # afternoon set-point sweep
  ])

irradiance =
  Nx.tensor([
    [0.41, 0.62, 0.78, 0.88],
    [0.93, 0.97, 0.91, 0.80]
  ])

# kWh per reading = irradiance * panel_area * 0.25h, broadcast over both axes
panel_area = 2.1

kwh = irradiance |> Nx.multiply(panel_area) |> Nx.multiply(0.25)
Nx.shape(kwh)
```

Named axes remove the "which axis is which?" guesswork:

```elixir
kwh
|> Nx.rename([:rows, :slots])
|> Nx.mean(axes: [:slots])   # per-row average, shape {2}
```

## Section 2 — The energy model and its gradient

A single-axis tracker's daily energy `E(tilt)` rises, peaks, and falls.
We model it with a curve that peaks near the site latitude (40°):

```elixir
defmodule Tracker do
  import Nx.Defn

  # Normalized daily energy for a tilt angle in degrees. Peaks near 40.
  # Scaled by 40 so gradients are O(1) — unscaled models converge slowly.
  defn energy(tilt) do
    x = Nx.divide(tilt, 40.0)
    Nx.multiply(40.0, Nx.multiply(x, Nx.exp(Nx.negate(x))))
  end

  defn energy_grad(tilt) do
    grad(tilt, &energy/1)
  end

  # One gradient-ascent step: move uphill, scaled by the learning rate.
  defn ascent_step(tilt, lr) do
    tilt + lr * grad(tilt, &energy/1)
  end
end

tilts = Nx.linspace(0.0, 120.0, n: 121)
energies = Tracker.energy(tilts)

alias VegaLite, as: Vl

Vl.new(title: "Daily energy vs tilt", width: 720, height: 480)
|> Vl.data_from_values(%{
  tilt: Nx.to_flat_list(tilts),
  energy: Nx.to_flat_list(energies)
})
|> Vl.mark(:line)
|> Vl.encode_field(:x, "tilt", type: :quantitative)
|> Vl.encode_field(:y, "energy", type: :quantitative)
```

Gradient ascent from a bad starting angle — no closed form, just the
derivative. Ascent is descent with a sign flip: no loop library, no
framework, an `Enum.reduce/3` threads the tensor exactly like threading
an accumulator through `lists:foldl/3`:

```elixir
tilt = Nx.tensor(5.0)
lr = 50.0

final_tilt =
  Enum.reduce(1..80, tilt, fn _, t ->
    Tracker.ascent_step(t, lr)
  end)

"Optimal tilt: #{Float.round(Nx.to_number(final_tilt), 2)}°, " <>
  "energy: #{Float.round(Nx.to_number(Tracker.energy(final_tilt)), 4)}"
```

Sweeping all starting points at once — tensors let every row ascend in
parallel:

```elixir
starts = Nx.tensor([2.0, 10.0, 30.0, 80.0, 110.0])

Enum.reduce(1..80, starts, fn _, t -> Tracker.ascent_step(t, 50.0) end)
|> Nx.to_flat_list()
|> Enum.map(&Float.round(&1, 1))
```

All five converge to the same peak regardless of where they started.
Because tensors are data, every candidate angle ascends in parallel —
one compiled program, one gradient per row.

## Section 3 — Fitting a calibration from noisy sensors

Real panels deviate from the ideal model. Field calibration is affine:
`measured ≈ gain * ideal(tilt) + offset`. Fit both parameters by
minimizing squared error. Note the params container: a map in, a map of
gradients out — and the *update* is plain Elixir, outside `defn`. This
division of labor is the contract Axon's optimizers are built on — after
this lab, Chapter 19's `Axon.ModelState` reads as "containers all the
way down."

```elixir
defmodule Calibration do
  import Nx.Defn

  defn model(params, tilt) do
    params[:gain] * Tracker.energy(tilt) + params[:offset]
  end

  defn mse(params, tilt, measured) do
    predicted = model(params, tilt)

    measured
    |> Nx.subtract(predicted)
    |> Nx.pow(2)
    |> Nx.mean()
  end

  # defn computes loss + gradients; it does not perform the update.
  defn loss_and_grads(params, tilt, measured) do
    value_and_grad(params, &mse(&1, tilt, measured))
  end
end
```

Generate noisy "field data" and descend. (Why not update inside `defn`?
Map-building functions are plain-Elixir territory — `defn` computes
numbers, your code orchestrates the loop. Gradient descent is a fold.)

```elixir
key = Nx.Random.key(1337)
{noise, _k} = Nx.Random.normal(key, 0.0, 0.03, shape: {400})

{x_train, _k} = Nx.Random.uniform(key, 0.0, 110.0, shape: {400})

true_gain = 1.05
true_offset = 0.02

y_train =
  Calibration.model(%{gain: Nx.tensor(true_gain), offset: Nx.tensor(true_offset)}, x_train)
  |> Nx.add(noise)

params = %{gain: Nx.tensor(0.6), offset: Nx.tensor(0.4)}
lr = 0.005

{final_loss, fitted} =
  Enum.reduce(1..2000, {Nx.tensor(0.0), params}, fn _, {_, p} ->
    {loss, grads} = Calibration.loss_and_grads(p, x_train, y_train)

    {loss,
     %{
       gain: Nx.subtract(p[:gain], Nx.multiply(lr, grads[:gain])),
       offset: Nx.subtract(p[:offset], Nx.multiply(lr, grads[:offset]))
     }}
  end)

IO.puts("final loss: #{Nx.to_number(final_loss) |> Float.round(6)} (noise floor ≈ 0.0009)")
"gain ≈ #{Nx.to_number(fitted[:gain]) |> Float.round(3)} (true #{true_gain}), " <>
  "offset ≈ #{Nx.to_number(fitted[:offset]) |> Float.round(3)} (true #{true_offset})"
```

Visualize the fit against the data:

```elixir
xs = Nx.linspace(0.0, 110.0, n: 200)
ys = Calibration.model(fitted, xs)

Vl.new(title: "Fitted calibration curve", width: 720, height: 480)
|> Vl.data_from_values(%{
  measured_x: Nx.to_flat_list(x_train),
  measured_y: Nx.to_flat_list(y_train),
  fit_x: Nx.to_flat_list(xs),
  fit_y: Nx.to_flat_list(ys)
})
|> Vl.layers([
  Vl.new()
  |> Vl.mark(:point, opacity: 0.3)
  |> Vl.encode_field(:x, "measured_x", type: :quantitative)
  |> Vl.encode_field(:y, "measured_y", type: :quantitative),
  Vl.new()
  |> Vl.mark(:line, color: "#d62728")
  |> Vl.encode_field(:x, "fit_x", type: :quantitative)
  |> Vl.encode_field(:y, "fit_y", type: :quantitative)
])
```

## Section 4 — Backend benchmark: BinaryBackend vs EXLA

The same `defn`, two execution strategies. The `defn` body never
mentions the backend — backends are an execution decision, not a code
change. Benchee reports what the backend choice is worth on your machine,
and also shows EXLA's *first* call paying a JIT compilation toll. Both
facts shape deployment: compile warmup belongs in release boot, not the
first request:

```elixir
{big, _key} = Nx.Random.uniform(Nx.Random.key(7), 0.0, 1.0, shape: {1_000, 1_000}, type: :f32)

defmodule Bench do
  import Nx.Defn

  defn softmax_rows(t) do
    t
    |> Nx.exp()
    |> Nx.divide(Nx.sum(Nx.exp(t), axes: [-1], keep_axes: true))
  end
end

{binary_time, _} =
  :timer.tc(fn ->
    big |> Nx.backend_copy(Nx.BinaryBackend) |> Bench.softmax_rows()
  end)

{exla_time, _} =
  :timer.tc(fn ->
    Bench.softmax_rows(Nx.backend_copy(big, EXLA.Backend))
  end)

"binary: #{div(binary_time, 1000)} ms, exla (after JIT): #{div(exla_time, 1000)} ms"
```

For a rigorous comparison, let Benchee warm up the EXLA compilation first:

```elixir
exla_input = Nx.backend_copy(big, EXLA.Backend)
Bench.softmax_rows(exla_input)   # trigger JIT before benchmarking

Benchee.run(
  %{
    "binary" => fn -> Bench.softmax_rows(Nx.backend_copy(big, Nx.BinaryBackend)) end,
    "exla" => fn -> Bench.softmax_rows(exla_input) end
  },
  time: 3,
  memory_time: 1
)
```

## Section 5 — Inspect the compiled graph

`print_expr/2` shows what the compiler actually sees — notice how the
gradient was computed for you:

```elixir
defmodule GradInspect do
  import Nx.Defn

  defn probe(t) do
    t
    |> Nx.multiply(2.0)
    |> Nx.tanh()
    |> Nx.sum()
    |> print_expr(label: "forward")
  end

  defn probe_grad(t) do
    grad(t, &probe/1)
    |> print_expr(label: "gradient")
  end
end

GradInspect.probe_grad(Nx.tensor([0.5, -0.5, 2.0]))
```

## Checkpoint

1. Why does starting five tilts at once converge faster *wall-clock* than
   five sequential runs?
2. If you swapped the ascent step to `tilt - lr * grad(...)`, what does
   the optimizer find, and what is that called?
3. Why should the EXLA warmup happen at boot rather than on first request?

**Answers**

1. One compiled `defn` call computes all five gradients in a single fused
   program — the per-call overhead is paid once, and the backend
   vectorizes across the leading axis.
2. The minimum of the energy curve (gradient *descent*). Same code, one
   sign — the loss-minimization default everywhere in Part IV.
3. The first call triggers JIT compilation of a shape-specific program;
   serving that latency to the first real request is a self-inflicted
   timeout.

## Where to next

* Run the cells in order; try changing `lr` in Section 3 and watch the fit
  diverge or crawl.
* Exercise: replace the MSE in `Calibration` with mean absolute error
  (`Nx.mean(Nx.abs(...))`) — does the gradient still flow? Watch how the
  fit responds to outlier sensors differently.
* Exercise: convert the ascent loop in Section 2 to a `defn` `while` loop
  so the whole optimization compiles into one XLA program, then benchmark
  it against the `Enum.reduce` version.
* Section 5 prints the graph `print_expr/2` sees — including the
  synthesized gradient. Follow the `grad` node to see reverse mode made
  concrete.
