Chapter 15
Supervised Adaptation and Low-Rank Training
On this page
A useful fine-tuning run begins with a reproducible data-to-gradient path. Understand which targets are learned, which parameters move, and which evaluation would reveal that the adaptation damaged the base model.
Choose between continued pretraining and instruction learning¶
Continued pretraining learns from the next-token structure of a domain corpus. SFT learns from demonstrations of desired responses under an explicit interaction format. They can use the same cross-entropy machinery while supervising different targets. A repository dump does not automatically teach a model to follow a debugging request; a short answer demonstration does not expose the full distribution of a technical domain.
For a documentation assistant, distinguish domain knowledge from current facts. Fine-tuning can teach terminology, tool-call syntax, and answer conventions. Frequently changing permissions and policies should remain in a governed retrieval system. Putting them into weights does not create reliable deletion or authorization semantics.
Begin with a base or instruction model that already fits the required language and task family. Establish a no-training baseline with the intended prompt and retrieval. If the failure is a missing document or a wrong access filter, model training attacks the wrong layer. If examples consistently show a learnable output or decision pattern, adaptation becomes a testable intervention.
Make one supervised batch completely visible¶
Take a serialized exchange containing a user question, host-supplied tool evidence, and a final assistant answer. For assistant-only supervision, mark targets belonging to the assistant response, including whichever delimiters the deployment must generate. If an assistant tool call precedes the evidence, declare that additional supervised span explicitly. Leave user and tool-result targets unscored while keeping them visible as context. The serialization below makes this chapter self-contained; template delimiters and assistant tool-call spans must be declared for the actual deployment.
For the compact fixture [BOS, USER, u, TOOL, observation, ASSISTANT, answer, END], assign token IDs [0,1,7,2,8,3,9,4]. Train on inputs ids[:-1] and targets ids[1:]. The target mask is [0,0,0,0,0,1,1]: the answer and END are supervised; the assistant delimiter is deliberately excluded. User and tool content remain visible to attention. An assistant tool-call message would receive its own explicitly selected target span rather than inheriting the tool-result role.
Example status: Runnable target-alignment reference; standard library only.
ids = [0, 1, 7, 2, 8, 3, 9, 4]
inputs, targets = ids[:-1], ids[1:]
target_mask = [False, False, False, False, False, True, True]
assert [t for t, use in zip(targets, target_mask) if use] == [9, 4]
assert inputs[5] == 3 and targets[5] == 9
examples/decoder_lab.py checks the tensor loss and its gradients, performs an actual attention-model update, and verifies a LoRA branch's initial equality and frozen-base behavior. Run it in the optional PyTorch environment described in the experiment index. These are implementation checks, not evidence that a tiny fixture generalizes.
For each batch, retain the number of valid target tokens. Across unequal microbatches, accumulate the sum of token losses and divide by the global supervised-token count. Averaging each microbatch mean equally implements a different weighting when the target counts differ. For example, a two-target microbatch and a 100-target microbatch should not receive equal weight under a token-mean objective.
Inspect a tiny overfitting test before a full run: can the model drive loss down on a handful of valid demonstrations, and does decoded behavior match the target format? If not, first check token shifts, masks, frozen parameters, optimizer membership, and gradient flow. Success on this test establishes plumbing, not generalization. A held-out split must separate related documents, templates, or tasks to avoid measuring memorized variants.
LoRA reduces trainable state, not all training memory¶
A frozen base projection and a trainable low-rank branch contribute to the same output. The diagram uses row-vector notation; the adapter scale multiplies the low-rank branch before addition.
LoRA freezes a base matrix and learns a low-rank update. Using the book's row-vector convention, let W have shape [d_in,d_out], A shape [d_in,r], and B shape [r,d_out]:
Only the low-rank matrices are trained when the base weight W is frozen.
The adapter contains r(d_in+d_out) parameters instead of d_in*d_out. For a 4096-by-4096 matrix and rank 16, that is 131,072 versus 16,777,216 parameters: 128 times fewer trainable parameters for this matrix. This does not mean 128 times less total GPU memory. The frozen weights still reside somewhere; activations must support backward; temporary GEMMs and communication buffers still exist.
A common initialization sets one factor randomly and the other to zero so the initial update is zero. If both factors were zero, their product's gradients would also be zero and the adapter would not begin learning. Scaling conventions vary, so record the actual scale rather than assuming the rank alone defines the update.
Target-module selection matters. Attention-only adapters and adapters on all large linear layers have different capacity and memory cost. Increase rank only after separating underfitting from poor data or incorrect targets. Measure broad capability and domain behavior, not only training loss. Adapter merging forms W+sAB for a fixed adapter; serving many adapters simultaneously generally preserves the factors instead.
QLoRA separates storage precision from the gradient path¶
QLoRA combines a frozen quantized base with trainable low-rank adapters, including NF4 storage, quantized scale metadata, and memory-management techniques. It does not backpropagate updates into the packed four-bit base weights as if those integers were ordinary trainable floating-point parameters.
The layer reconstructs or otherwise consumes the base weights in the supported compute path, adds the adapter contribution, and propagates gradients to the adapter and required activations. Four-bit storage therefore does not imply every multiplication or gradient uses four bits. NF4 is a nonuniform quantization codebook, not the same format as hardware FP4.
A memory ledger needs packed base weights, scales and metadata, adapters, their gradients and optimizer states, activations, temporary dequantization/workspaces, and allocator reserve. On a nominal 7B model, ideal four-bit weight payload is 3.5 GB before metadata. Use that only as a lower bound; it is not a promised device-memory requirement.
Merging a trained adapter into a low-bit checkpoint requires care. Forming a higher-precision merged matrix and requantizing can introduce a different error from serving the unmerged quantized base plus adapter. Evaluate the exact deployment artifact, not just the training-time representation.
A controlled adaptation experiment¶
Use an illustrative 2,000-example domain task set with a separate held-out group split. Compare the unchanged model, prompt/retrieval-only improvements, SFT with LoRA, and full fine-tuning if resources permit. Keep the source corpus, serialization, target masks, evaluation prompts, and generation policy fixed. Sweep a small learning-rate/rank grid instead of changing every variable together.
Report target-task accuracy, schema validity, unsupported claims, broad-capability retention, and training/serving cost. Add early stopping based on validation, but do not repeatedly tune against the final test set. Test multiple random seeds when differences are small. These are experiment instructions and illustrative counts, not results already measured for a particular model.
If the adapter improves answer style while factuality is unchanged, say so. If a full fine-tune improves the domain but loses multilingual behavior, the release decision must include that regression. Parameter efficiency is useful only when the retained behavior meets the product contract.
Exercises and worked answers¶
- Why not update only an embedding table for every adaptation? The failure may require changed transformations or decisions, not just different token vectors; choose trainable modules from the task and compare controls.
- Why can a frozen base still require activations for backward? Gradients must traverse its operations to reach earlier trainable adapters even though the base's own weights are not updated.
- What breaks when loss is averaged by microbatch? Unequal supervised-token counts receive unintended equal weight. Accumulate numerators and denominators consistently with the intended objective.
- When is retrieval preferable to memorizing documents? When evidence changes frequently, must be cited, or has deletion/access requirements that weights cannot enforce reliably.