# Lab 5 — Character-Level LSTM: A Tiny Text Generator

Everything before this lab *classified*. This lab *generates*: a small LSTM that
reads a public-domain book one character at a time and then writes
plausible continuations. It is the smallest possible tour of sequence
modeling — the same machinery that, scaled up, powers the transformers of
Chapter 28. All-new examples: we train a small LSTM to model a
public-domain book, one character at a time, then sample new text with a
temperature knob. This lab replaces vocabulary-of-words classification
with *sequence modeling over characters*.

> **From Erlang you know:** the sliding-window dataset is just
> `Enum.chunk_every/4` with a stride — list processing you have written a
> hundred times, pointed at characters instead of log lines.

## What You'll Build

1. **A character vocabulary** — no tokenizer library; the set of distinct
   characters, `id 0` reserved for padding.
2. **A windowed dataset** — every 64-character window predicts the
   character that follows, with overlapping windows (stride 8) to
   multiply the data.
3. **The LSTM** — embedding → LSTM(128) → last time-step → dense over
   the vocabulary, trained with categorical cross-entropy.
4. **Temperature-controlled sampling** — Gumbel-max sampling entirely in
   Nx, with the temperature knob demonstrated at 0.5 and 1.2.

```elixir
Mix.install([
  {:axon, "~> 0.8"},
  {:nx, "~> 0.13"},
  {:exla, "~> 0.13"},
  {:polaris, "~> 0.1"},
  {:req, "~> 0.7"},
  {:kino, "~> 0.14"}
])
```

## Section 1 — Fetch a small corpus

A single public-domain text keeps the download small and training fast.
(Any text works — swap in your own file to see the model mimic it.)

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

%Req.Response{status: 200, body: raw_text} =
  Req.get!("https://www.gutenberg.org/cache/epub/11/pg11.txt")

corpus =
  raw_text
  |> String.graphemes()
  |> Enum.take(120_000)
  |> Enum.join()

String.length(corpus)
```

## Section 2 — Character vocabulary

A char-level model needs no tokenizer library: the vocabulary is the set
of distinct characters. Reserve `0` for padding.

```elixir
chars =
  corpus
  |> String.graphemes()
  |> Enum.uniq()
  |> Enum.sort()

char_to_id = chars |> Enum.with_index(1) |> Map.new()
id_to_char = chars |> Enum.with_index(1) |> Map.new(fn {c, i} -> {i, c} end)

vocab_size = length(chars) + 1     # +1 for the padding id 0
"#{vocab_size} distinct characters"
```

## Section 3 — Build fixed-length training windows

Every window of `seq_len` characters predicts the character that follows
it. One book becomes tens of thousands of overlapping supervised
examples: the model never sees the "document" — only shifted frames of
it, which is exactly how next-token prediction frames language.
Overlapping windows multiply the amount of data:

```elixir
seq_len = 64
stride = 8

ids = corpus |> String.graphemes() |> Enum.map(&Map.fetch!(char_to_id, &1))

windows =
  ids
  |> Enum.chunk_every(seq_len + 1, stride, :discard)
  |> Enum.map(fn window ->
    {input, [target]} = Enum.split(window, seq_len)
    {input, target}
  end)

num_windows = length(windows)
"#{num_windows} training windows"
```

Batch them:

```elixir
batch_size = 64

{input_batches, target_batches} =
  windows
  |> Enum.shuffle()
  |> Enum.chunk_every(batch_size, batch_size, :discard)
  |> Enum.map(fn batch_windows ->
    inputs = batch_windows |> Enum.map(&elem(&1, 0)) |> Nx.tensor()
    targets = batch_windows |> Enum.map(&elem(&1, 1)) |> Nx.tensor()

    onehot_targets =
      targets
      |> Nx.new_axis(-1)
      |> Nx.equal(Nx.iota({1, vocab_size}))

    {inputs, onehot_targets}
  end)
|> Enum.unzip()

train_data = Stream.zip(input_batches, target_batches)
{Nx.shape(hd(input_batches)), Nx.shape(hd(target_batches))}
```

(Inputs stay as integer ids for the embedding layer; only the targets are
one-hot encoded for the loss.)

## Section 4 — The LSTM model

Embedding → LSTM → take the last time-step → dense over the vocabulary.
`Axon.lstm/3` returns `{sequence, state}`; the sequence is
`{batch, seq_len, features}` and the final position carries the summary
the dense head consumes. This indexing pattern — slice the last step of
the middle axis — recurs in every sequence model you will read:

```elixir
model =
  Axon.input("chars", shape: {nil, seq_len})
  |> Axon.embedding(vocab_size, 96)
  |> Axon.lstm(128, unroll: :static)
  |> then(fn {seq, _state} -> seq end)
  |> Axon.nx(fn s -> s[[.., -1]] end)
  |> Axon.dense(vocab_size)

# Compact summary — Axon.Display.as_table/2 is broken in Axon 0.8.1
# for LSTM graphs, so use the model inspect instead.
IO.inspect(model, label: "char-lstm model")
```

## Section 5 — Train

```elixir
trained_state =
  model
  |> Axon.Loop.trainer(
    # the dense head emits raw logits — the loss must know, or log(prob)
    # goes negative and the loss becomes NaN mid-training
    &Axon.Losses.categorical_cross_entropy(&1, &2, from_logits: true, reduction: :mean),
    Polaris.Optimizers.adam(learning_rate: 2.0e-3)
  )
  |> Axon.Loop.metric(:accuracy)
  |> Axon.Loop.run(train_data, %{}, epochs: 15, compiler: EXLA)
```

Per-character accuracy will look modest — language modeling is hard — but
the *relative* quality of samples is what matters.

## Section 6 — Sample text with temperature

Temperature reshapes the distribution: near 0 the model repeats its most
confident choice (safe, boring); near 1.5 it takes risks (fun, gibberish).
Dividing logits by a temperature before adding Gumbel noise reshapes the
sampling distribution, so the knob is demonstrated at 0.5 and 1.2 below.
Sampling uses the Gumbel-max trick, so the whole draw stays inside Nx —
no per-character round-trip to host-side randomness:

```elixir
defmodule Sample do
  import Nx.Defn

  # Gumbel-max trick: adding Gumbel noise to logits and taking argmax is
  # equivalent to sampling from softmax(logits / temp) — all inside Nx.
  # The key is threaded out: reusing one key would add the *same* noise
  # vector every step and lock the sampler into a repeating bias.
  defn gumbel_sample(logits, temp, key) do
    {gumbel, key2} = Nx.Random.gumbel(key, shape: Nx.shape(logits))
    {Nx.argmax(logits / temp + gumbel), key2}
  end
end
```

```elixir
generate = fn prompt, num_chars, temp ->
  seed_ids =
    prompt
    |> String.graphemes()
    |> Enum.map(&Map.get(char_to_id, &1, char_to_id[" "]))

  init_ids =
    if length(seed_ids) >= seq_len do
      Enum.take(seed_ids, -seq_len)
    else
      List.duplicate(char_to_id[" "], seq_len - length(seed_ids)) ++ seed_ids
    end

  init_window = init_ids |> Nx.tensor() |> Nx.reshape({1, seq_len})

  {_win, _key, generated} =
    for _ <- 1..num_chars, reduce: {init_window, Nx.Random.key(42), []} do
      {win, k, acc} ->
        logits = Axon.predict(model, trained_state, win)
        {next_id, k2} = Sample.gumbel_sample(logits, Nx.tensor(temp), k)
        next_char = Map.fetch!(id_to_char, Nx.to_number(next_id))

        next_window =
          win
          |> Nx.to_flat_list()
          |> tl()
          |> Kernel.++([Nx.to_number(next_id)])
          |> Nx.tensor()
          |> Nx.reshape({1, seq_len})

        {next_window, k2, [next_char | acc]}
    end

  prompt <> Enum.join(Enum.reverse(generated))
end

with_temp_05 = generate.("Alice was beginning to", 300, 0.5)
with_temp_12 = generate.("Alice was beginning to", 300, 1.2)

Kino.Layout.grid([
  Kino.Markdown.new("**temperature 0.5**"),
  Kino.Markdown.new(with_temp_05),
  Kino.Markdown.new("**temperature 1.2**"),
  Kino.Markdown.new(with_temp_12)
])
```

## Checkpoint

1. Why keep inputs as integer ids but one-hot encode only the targets?
2. What does `unroll: :static` trade for the LSTM, and why does a fixed
   `seq_len` make it possible?
3. Per-character training accuracy is modest. Why is sample quality, not
   accuracy, the honest metric for a generator?

**Answers**

1. The embedding layer consumes ids and looks up dense vectors; one-hot
   targets feed the cross-entropy directly. One-hot inputs would waste
   the embedding's purpose and blow memory.
2. Static unroll compiles the recurrence as a fixed graph — faster, and
   only possible because every window has the same length; variable
   lengths would need dynamic unroll or padding tricks.
3. Cross-entropy measures confidence calibration, not coherence. A model
   can have middling per-character likelihoods and still produce
   fluent text — read the samples.

## Where to next

* Exercise: switch the corpus to your own text file; compare how few
  characters the vocabulary needs before the model overfits, and watch
  how few epochs a tiny vocabulary needs before samples sound like it.
* Exercise: replace the dense head + sampling with a `:softmax` output and
  `:categorical_cross_entropy` on softmax probabilities — notice you must
  set `from_logits: false` and why logit outputs are preferred.
* Exercise: stack a second `Axon.lstm(128)` layer and compare sample
  quality per epoch against the training-time cost.
* Exercise: seed the sampler with several prompts and log outputs to a
  `Kino.Frame` as the model trains, to watch the generator improve live.
