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.
What runs in CodeSplash
- LNG067Low-Rank Adaptation (LoRA) Runs in CodeSplash
- LNG001Smoothed n-gram language model 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
Two questions, stated first
ReadThe 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?
The split contract
ReadThe 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.
Model, loss and training
ReadAn Elman recurrent network with 24 hidden units reads one character at a time:
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.
- 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 (scoresE0 @ U0) on the garden test countsC_src_testince_untrained.Show a solution
Pythondef cross_entropy(W, C): return -(C * log_softmax_rows(W)).sum() / C.sum() ce_untrained = cross_entropy(E0 @ U0, C_src_test)Rcross_entropy <- function(W, C) -sum(C * log_softmax_rows(W)) / sum(C) ce_untrained <- cross_entropy(E0 %*% U0, C_src_test) - After training, on held-out sentences
Store the cross-entropy of the trained model (
E @ U) on the garden test counts ince_trained.Show a solution
Pythonce_trained = cross_entropy(E @ U, C_src_test)Rce_trained <- cross_entropy(E %*% U, C_src_test) - The same model on the new domain
Store the trained garden model's cross-entropy on the space test counts
C_tgt_testince_target. Compare it withce_untrained.Show a solution
Pythonce_target = cross_entropy(E @ U, C_tgt_test)Rce_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.
Two ways to adapt
ReadBoth 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.
- 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
Pythontrainable = [A.size + B.size, U.size]Rtrainable <- c(length(A) + length(B), length(U)) - 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, ingain.Show a solution
Pythongain = [cross_entropy(W_base, C_tgt_test) - cross_entropy(W, C_tgt_test) for W in (W_lowrank, W_full)]Rgain <- sapply(list(W_lowrank, W_full), function(W) cross_entropy(W_base, C_tgt_test) - cross_entropy(W, C_tgt_test)) - 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, inforgot.Show a solution
Pythonforgot = [cross_entropy(W, C_src_test) - cross_entropy(W_base, C_src_test) for W in (W_lowrank, W_full)]Rforgot <- 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?
The toy 24 × 16 update ΔW is built from this many directions, plus noise.
Small changes in every direction, which no low rank captures.
Δ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.
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.
What happens to the source?
PredictPredict first
Both branches improve target loss. Which pattern would you expect?
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.
What the run showed, and what it didn't
ReadThe 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.
L2 and EWC only: how hard the weights are pulled back toward task A's.
Replay only: share of each batch drawn from task A.
Gradient steps on task A, then the same number on task B.
Step size in both phases.
- 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.
Run it yourself
ReadThe 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.
Where it stands in CodeSplash
Read| Entry | In 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 |
Check: the workflow
CheckpointCheck 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.
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