Skip to content

Workflow: train a tiny character language model, then adapt it

Walk through the reference's complete workflow, a small recurrent character model trained and then adapted to a new domain two ways. Every choice is visible, from the split contract to the retention check and the parameter audit.

Advanced ~18 min10 steps

What runs in CodeSplash

You will be able to

  • Set up a split contract with documents as units and a train-only vocabulary
  • Explain why the hidden state resets per document and why checkpoints are chosen on validation data
  • Compare full-head adaptation with a low-rank adapter on target gain, retention and trainable parameters
  • Treat generated samples as a separate evaluation from held-out loss

Read first

01

Two questions, stated first

Read

The reference's language workflow builds a small recurrent character model in NumPy and in base R, each written out in full. It asks two questions, and fixes how they are answered before any training:

  • Learn. Can the model learn next-character probabilities from a source corpus and generalize to held-out documents from the same grammar? Success means lower held-out cross-entropy than the untrained model, sound loss curves and passing gradient checks, not a nice-looking sentence.
  • Adapt. Moving to a target domain, how much does the target improve and how much does the source degrade, when updating the whole output layer versus a low-rank adapter on it?
02

The split contract

Read

The corpus is 576 short authored sentences, half "garden" and half "space", generated by a fixed grammar. Each domain gets 192 training, 48 validation and 48 test documents, from a permutation fixed before fitting. Exact sentences never repeat across splits, but words and templates do: the test checks new combinations within one grammar, not new language.

The vocabulary comes from source training text only: 28 characters plus PAD, BOS, EOS and UNK. Each document is read as BOS plus its characters, predicting its characters plus EOS. The hidden state resets to zero at every document, so no context leaks across a split boundary.

03

Model, loss and training

Read

An Elman recurrent network with 24 hidden units reads one character at a time:

ht=tanh⁡(E[xt]+ht−1W+b),pt=softmax(htU+c)h_t = \tanh(E[x_t] + h_{t-1}W + b), \qquad p_t = \mathrm{softmax}(h_t U + c)

That is 2,168 parameters. The loss is the mean negative log-probability over real target characters, computed through log-sum-expLog-sum-explog Σ exp(xᵢ), computed as m + log Σ exp(xᵢ − m) with m the largest xᵢ, so nothing overflows. so tiny probabilities never round to zero. Backpropagation runs through each whole document; gradients for repeated characters accumulate rather than overwrite. Adam with global gradient clipping updates the weights, and the checkpoint with the best source validation loss is kept. Test documents are scored once, after that choice.

Notebook exercise · ~15 min

A tiny character model, scored honestly

Write the cross-entropy of a next-character model, score it before and after training on held-out sentences, and see how badly it fits a new domain.

  1. Cross-entropy before training

    Write cross_entropy(W, C): the mean negative log-probability per predicted character, that is −Σ C ⊙ log_softmax_rows(W) divided by the number of predicted characters, ΣC. Store the cross-entropy of the untrained model (scores E0 @ U0) on the garden test counts C_src_test in ce_untrained.

    Show a solution
    Python
    def cross_entropy(W, C):
        return -(C * log_softmax_rows(W)).sum() / C.sum()
    ce_untrained = cross_entropy(E0 @ U0, C_src_test)
    R
    cross_entropy <- function(W, C) -sum(C * log_softmax_rows(W)) / sum(C)
    ce_untrained <- cross_entropy(E0 %*% U0, C_src_test)
  2. After training, on held-out sentences

    Store the cross-entropy of the trained model (E @ U) on the garden test counts in ce_trained.

    Show a solution
    Python
    ce_trained = cross_entropy(E @ U, C_src_test)
    R
    ce_trained <- cross_entropy(E %*% U, C_src_test)
  3. The same model on the new domain

    Store the trained garden model's cross-entropy on the space test counts C_tgt_test in ce_target. Compare it with ce_untrained.

    Show a solution
    Python
    ce_target = cross_entropy(E @ U, C_tgt_test)
    R
    ce_target <- cross_entropy(E %*% U, C_tgt_test)

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

04

Two ways to adapt

Read

Both branches start from the source checkpoint, see the same target documents and get the same number of updates.

  • Full head: train the output matrix U and bias c, 800 values, with the recurrent layer frozen.
  • Low-rank head: freeze everything and train U_eff = U0 + AB with A of 24 × 3 and B of 3 × 32, 168 values. B starts at zero, so the adapted model starts exactly at the source model.

Each branch keeps its best target-validation checkpoint. Source test loss is measured afterward, as retained capability, and is never used to pick a checkpoint.

Notebook exercise · ~15 min

Adapt it, and check what it forgets

Count trainable and frozen parameters, then measure target gain and source loss for a full output head and a low-rank adapter.

  1. Trainable parameters

    Store the number of values each branch trains, low-rank first and full head second, in trainable. (The embeddings are frozen in both.)

    Show a solution
    Python
    trainable = [A.size + B.size, U.size]
    R
    trainable <- c(length(A) + length(B), length(U))
  2. What each branch gains on the target

    Store how much each branch lowers the cross-entropy on the space test counts, compared with W_base, low-rank first, in gain.

    Show a solution
    Python
    gain = [cross_entropy(W_base, C_tgt_test) - cross_entropy(W, C_tgt_test) for W in (W_lowrank, W_full)]
    R
    gain <- sapply(list(W_lowrank, W_full), function(W) cross_entropy(W_base, C_tgt_test) - cross_entropy(W, C_tgt_test))
  3. What each branch forgets

    Retained capability is measured on the old domain, after the fact. Store how much each branch raises the cross-entropy on the garden test counts C_src_test, low-rank first, in forgot.

    Show a solution
    Python
    forgot = [cross_entropy(W, C_src_test) - cross_entropy(W_base, C_src_test) for W in (W_lowrank, W_full)]
    R
    forgot <- sapply(list(W_lowrank, W_full), function(W) cross_entropy(W, C_src_test) - cross_entropy(W_base, C_src_test))

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

DExplorable · LoRA: rank, parameters and error

How much of a weight update can a low-rank adapter capture, and what does it save?

3

The toy 24 × 16 update ΔW is built from this many directions, plus noise.

0.10

Small changes in every direction, which no low rank captures.

2

ΔW ≈ BA with B 24 × r and A r × 16; the best such fit is the truncated SVD.

Layer width for counting

Trainable parameters of one square layer, full versus LoRA.

rank 2direction 1 … 16

Toy update: 80 adapter numbers against 384 for the full 24 × 16 matrix. Layer of width 4,096: 16,384 against 16,777,216.

Relative error
0.414
Energy kept
0.828
LoRA parameters (one layer)
16384
Share of full fine-tuning
0.0010
  • Puzzle: Find the smallest rank that keeps 95% of the update's energy.
  • Puzzle: On the 4,096-wide layer, train less than 0.5% of the full layer's parameters.LoRA's count grows with r(d + k), not d × k. The frozen weights still sit in memory, though.
A rank-2 adapter keeps 82.8% of the update's energy (relative error 0.414). On a 4,096-wide layer it trains 16,384 numbers instead of 16,777,216 (0.10%). The update has more directions than the adapter can hold, so some of it is lost.

A rank-2 adapter keeps 82.8% of the update's energy (relative error 0.414). On a 4,096-wide layer it trains 16,384 numbers instead of 16,777,216 (0.10%). The update has more directions than the adapter can hold, so some of it is lost.

05

What happens to the source?

Predict

Predict first

Both branches improve target loss. Which pattern would you expect?

The full head gains more on the target and forgets more of the sourceThe adapter gains more on the target and forgets moreNeither changes the source at all
Reveal

The full head, with more freedom, gains more on the target and loses more on the source; the rank-3 adapter gains less and forgets less. That is what the reference run found, from one seed and one split, so it illustrates a trade-off rather than ranking the methods.

06

What the run showed, and what it didn't

Read

The source model learned its grammar well, and on the target grammar it did worse than the untrained model: confident specialization puts very low probability on unfamiliar continuations. Both adaptations fixed much of that, with the trade-off above.

Generated samples tell a separate story. Even after loss improved, both models produced some malformed strings, kept on purpose in the results. Sampling feeds the model its own choices, so errors compound in ways teacher-forced test loss never sees; temperature and top-k change sampling, not the weights.

DExplorable · Forgetting: fine-tuning, EWC and replay

Why does training on a new task erase an old one, and what can hold on to it?

While learning task B

What, if anything, remembers task A during the second phase.

3.0

L2 and EWC only: how hard the weights are pulled back toward task A's.

0.30

Replay only: share of each batch drawn from task A.

100

Gradient steps on task A, then the same number on task B.

0.10

Step size in both phases.

0.04A before2.80A after0.04B after
  • Task A's loss contours
  • Task B's loss contours
  • Training on A
  • Then on B
Task A loss after B
2.802
Task B loss
0.044
Forgetting (rise in A's loss)
2.758
Fine-tuning's forgetting
2.758
  • Puzzle: Keep task A's loss under 0.15 while bringing task B's under 1.0.
  • Puzzle: With replay, cut forgetting to under a quarter of plain fine-tuning's.
Plain fine-tuning: task A's loss goes from 0.044 to 2.802 while task B's ends at 0.044. Plain fine-tuning would forget 2.76. Task A's Fisher information is 1.35 for the first weight and 0.041 for the second: A barely cares about the second weight, so a pull that treats both weights alike also blocks what B needs.

Plain fine-tuning: task A's loss goes from 0.044 to 2.802 while task B's ends at 0.044. Plain fine-tuning would forget 2.76. Task A's Fisher information is 1.35 for the first weight and 0.041 for the second: A barely cares about the second weight, so a pull that treats both weights alike also blocks what B needs.

07

Run it yourself

Read

The workflow's Python and R programs read the same corpus and initial matrices, so differences between engines come from the code, not the starting point. A shared seed alone would not make their minibatch orders identical.

For your own adaptation experiments, carry the same habits: a fixed split contract, validation-only checkpoint choice, a retention check on the old domain, a count of trainable and frozen parameters, and the base model's identity recorded with every adapter.

08

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Character language model and LoRA head (LNG001, LNG067)The workflow's Python and R programs run in a notebook; Text encoder runs LoRA on MiniLM
Reference · LNG067 · Runs in CodeSplashLow-Rank Adaptation (LoRA)Adapts a pretrained model by learning low-rank updates to selected weight matrices while freezing the original weights.
09

Check: the workflow

Checkpoint

Check yourself

Why is the vocabulary built from source training text only?

Show the answer

Answer: a

Every choice fitted from data, the vocabulary included, must come from training data only. Unseen characters map to UNK explicitly.

Check yourself

Why does the hidden state reset to zero at the start of every document?

Show the answer

Answer: b

Resetting makes each document's prediction depend only on that document, matching the split contract.

Check yourself

In the low-rank head, A starts small and random and B starts at zero. Why not start both at zero?

Show the answer

Answer: b

The gradient of A involves B and the gradient of B involves A. One random factor breaks the symmetry; one zero factor keeps the starting model unchanged.

Check yourself

How is retained capability measured in the workflow?

Show the answer

Answer: b

Retention is a separate held-out measurement. Using it to choose checkpoints would need its own development data and a rule fixed in advance.

Check yourself

Held-out loss improved, but generated samples still contain malformed words. What does that show?

Show the answer

Answer: a

Teacher-forced loss supplies the true previous character; generation feeds back its own choices. Evaluate both, and keep unfavorable samples in the record.

10

Recap

Recap
  • State the questions and the split contract first: documents as units, a train-only vocabulary, resets per document.
  • Choose checkpoints on validation data; score the test once.
  • Full-head adaptation gained more and forgot more than a rank-3 adapter here, from one seed: a trade-off, not a ranking.
  • Generation is its own evaluation; loss gains don't guarantee well-formed output.

Concepts in this lesson