Free self-study · No account needed · Progress stays in this browser. Back it up before clearing site data or changing devices.

← Week 22: Fine-Tuning and Adaptation

Week 22 / Lesson 2

Training low-rank adapters

Explain low-rank updates and run a small reproducible adapter-training job.

Section 2.1 1 of 7

Overview

Focus

Explain low-rank updates and run a small reproducible adapter-training job.

Your route through the lesson

  • 2.2 Frozen base weights and low-rank parameter counts
  • 2.3 Data collation, optimizer, and adapter checkpoints
  • 2.4 Quantized low-rank adaptation and hardware limits
  • 2.5 Put it into practice
  • 2.6 Guided comparison
  • 2.7 An adapter loaded against the wrong base

All required teaching is included here. Review selections are saved. Choose a correct answer for every question to continue; retries are unlimited. Study time and personal notes are optional.

Section 2.2 2 of 7

Frozen base weights and low-rank parameter counts

Focus

Calculate low-rank updates and verify why freezing the base changes training scope.

Low-rank adaptation, abbreviated LoRA, learns a small additive change to a frozen weight matrix. If the base matrix W has d output rows and k input columns, write the adapted matrix as W + B×A. A has r rows and k columns; B has d rows and r columns. The rank r limits the update's independent directions. A full update has d×k trainable values; the two factors have r×(d+k).

For a 1024-by-1024 layer, full training changes 1,048,576 values. Rank eight uses 8×(1024+1024), or 16,384 adapter values. The base weights still occupy memory; the saving concerns trainable parameters and associated training state. The original low-rank paper explains the method's motivation and experiments.

The lab uses a deliberately tiny two-by-two identity base and rank one. Its adapter has four values, equal to the full matrix count, so this teaching example offers no parameter-count saving. It does provide real gradients, updates, a frozen-base assertion, and a reload test without downloading a language model. Its numeric inputs have a feature schema rather than a tokenizer.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A 100-by-80 layer uses rank 2. How many adapter parameters are there?
2. What does freezing W mean during adapter training?
3. A two-by-two rank-one adapter has four values. What saving does this tiny case provide?

Section 2.3 3 of 7

Data collation, optimizer, and adapter checkpoints

Focus

Teach tensors, collation, gradients, optimizer steps, and safe checkpoint identity before execution.

PyTorch is a numeric library that tracks operations for automatic differentiation. A tensor stores an array; torch.tensor constructs one from nested Python lists. torch.nn.Parameter marks a tensor as model state. requires_grad=False prevents gradient accumulation for the frozen base. The @ operator performs matrix multiplication, and .T transposes rows and columns. A batch groups several examples into one tensor; the lab collates four numeric rows with two features each.

The loss is mean squared error: subtract predicted and target arrays, square each difference, then average. optimizer.zero_grad() clears old gradients, loss.backward() computes current gradients, and optimizer.step() updates only the supplied adapter parameters. Passing [model.A, model.B] to stochastic gradient descent keeps the base outside the optimizer.

A checkpoint stores learned factors plus exact base identity and feature schema. torch.save writes it; torch.load with map_location="cpu" and weights_only=True reloads this trusted local dictionary. A new model copies the factors and must reproduce outputs. The PyTorch save/load tutorial adds framework context; never load an untrusted serialized object merely because its filename ends in .pt.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Why call zero_grad before each backward pass?
2. The optimizer receives only A and B. Which values should remain unchanged?
3. An adapter checkpoint lacks its base identity. What is missing?

Section 2.4 4 of 7

Quantized low-rank adaptation and hardware limits

Focus

Distinguish quantized low-rank adaptation from the processor-only full-precision core.

Quantized low-rank adaptation, commonly written QLoRA, combines a quantized frozen base with trainable low-rank factors. The base uses a compact representation, while training still needs supported operations, activation storage, and optimizer state. The original quantized-adapter paper describes four-bit base training and its memory techniques.

Quantizing the base is not the same as quantizing every intermediate computation or every adapter value. Libraries and hardware determine which formats and kernels are supported. A four-bit inference file cannot automatically be used for training with an arbitrary optimizer. Memory planning must include gradients for adapters, activations, temporary workspace, and the selected optimizer.

The core lab therefore uses ordinary floating-point tensors on the processor. It genuinely trains the low-rank factors but does not implement quantized training. An optional extension may use a compatible quantized-training stack after checking its current hardware requirements and measuring memory. If unavailable, a prepared comparison can teach parameter and memory interpretation while the quantized execution competency remains uncompleted. Do not describe the core numeric adapter as a quantized language-model training job.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. What is quantized in the defining quantized-adapter setup?
2. A four-bit inference artifact loads in one runtime. Does it guarantee training support elsewhere?
3. The processor lab uses floating-point base tensors. What method does it actually execute?

Section 2.5 5 of 7

Put it into practice

Focus

Install the processor dependency explicitly and execute real factor training and reload checks.

Use a dedicated environment: python -m venv .venv-adapter. In PowerShell, run ./.venv-adapter/Scripts/python.exe -m pip install torch --index-url https://download.pytorch.org/whl/cpu. This explicit command downloads PyTorch packages; consult official platform setup if your Python version lacks a compatible wheel. No pretrained model or credentials are needed.

Save week22.py, then run ./.venv-adapter/Scripts/python.exe week22.py --lesson 2 --train. Without --train, the script prints arithmetic and explicitly leaves training pending. The real path uses one processor thread, four synthetic rows, rank one, and 160 optimizer steps. Budget tens of seconds for this tiny job after installation; measure actual elapsed time on your machine rather than treating that budget as a benchmark.

Expected assertions show changed A and B, an exactly unchanged base, reduced training loss, and equal outputs after saving and reloading factors in a temporary folder. The checkpoint records a base hash and numeric feature schema, with tokenizer explicitly none-numeric-input. Temporary files are cleaned after verification. Preserve printed evidence if you need a run record.

Download this week’s Python lab ↓

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. A script always runs adapter arithmetic checks but executes optimizer training only with --train. It exits successfully without that flag. What ran, and what remains pending?
2. Which evidence directly proves the base stayed frozen?
3. Reloaded outputs match original adapted outputs. What is demonstrated?

Section 2.6 6 of 7

Guided comparison

Focus

Interpret actual adapter changes while keeping the miniature model’s limits explicit.

The real training path begins with an identity base. Its target doubles the first input coordinate and preserves the second. That desired update is rank one, making it a useful controlled case for B×A. One factor starts nonzero and the other at zero, so the initial additive update is zero while gradients can begin changing the zero factor.

After 160 steps, assertions require both factors to differ from their starting values and training loss to fall below one hundredth of its initial value. The base tensor must remain exactly equal. A fresh model then receives the saved factors and reproduces the adapted outputs. These are observations from real optimization when --train executes, not fixed printed scores.

The example is intentionally numeric: it does not tokenize language, contain attention layers, or prove a large pretrained model can be fine-tuned on this machine. Its completed competency is the low-rank training mechanism and checkpoint discipline. The weekly extension adds a second synthetic target transformation and compares rank one with rank two, retaining frozen-base and reserved-case checks. Explain when a target update cannot be represented at rank one rather than assuming more training steps always solve it.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Why initialize one factor nonzero and the other zero?
2. A target matrix update needs rank two but the adapter uses rank one. What can limit fit?
3. A numeric adapter run passes. Which claim remains unsupported?

Section 2.7 7 of 7

An adapter loaded against the wrong base

Focus

Reject an adapter whose base or input conventions differ from its recorded contract.

An adapter was trained against base matrix W1 and a feature order of temperature, pressure. A service loads it over W2 and feeds pressure, temperature. The factor shapes still match, so matrix multiplication succeeds. Nevertheless, both the reference weights and input semantics differ from training, making the result unreliable.

The loader checks the exact base hash and feature schema before copying factors. For a language model, the analogous record includes model revision, tokenizer revision, target modules, rank, scaling, and chat template. Shape compatibility is necessary but insufficient. A successful deserialization only proves bytes could be read.

If identity mismatches, reject loading and restore the compatible base-only release or the correct base-adapter pair. Do not silently retrain on production requests or pretend the mismatch is harmless because one sample looks plausible. After a compatible load, rerun a known numerical or language fixture and reserved task checks. This connects packaging to behavior: the adapter is part of a versioned system, not a universally portable patch whose meaning survives arbitrary bases and token conventions.

// Quick review

Check your understanding.

Choose an answer for immediate feedback. Retry freely; a correct answer for every question unlocks the next section.

1. Adapter shapes match but feature order is reversed. Is loading behaviorally compatible?
2. What should an exact base-hash mismatch trigger?
3. A .pt file deserializes successfully. What does that alone establish?

Your personal notes

Optional, ungraded, and saved only in this browser. Export a backup from the Academy homepage to keep them.

References and further reading
Ask your own AI assistant

Copy this prompt into an assistant you already use. Nothing is sent automatically, and your personal notes are not included.

Next lesson: Evaluating specialization and forgetting →