FT-00b: LoRA hyperparams from scratch — rank × alpha ablation

Lancer : Codespaces Colab

Navigation: Index | << Previous | Next >>

French version: FT-00b — LoRA hyperparams

Objective: measure firsthand how the (r, alpha) couple — rank of the decomposition and scaling — bounds the adaptation quality of a frozen network. No peft, no loralib — the same LoRALinear as FT-00a, trained over 6 values of r × 3 values of alpha/r = 18 configurations, on the same toy mini-task (inverted Fashion-MNIST, frozen 512→10 classifier).

Prerequisites: FT-00a — LoRALinear is built there in pure PyTorch.

Duration: ~15 min · Level: intermediate · Hardware: CPU is enough.

Position in the series: FT-00a demonstrated the mechanism; this notebook closes the tuning question — when too small a rank under-adapts, when too large an alpha destabilizes, and why the alpha/r scaling is what makes rank and magnitude decouplable.

On the menu: 1. reuse LoRALinear without redefining it · 2. assemble the mini-task (inverted Fashion-MNIST, frozen classifier) · 3. pre-train the model on the inverted domain · 4. run the 18-configuration ablation · 5. read the accuracy × budget × scaling table · 6. place the three baselines · 7. three guided examples, then three exercises.

Environment check

import copy, time, itertools
import numpy as np
import torch
import os
os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")  # determinisme cuBLAS (#16795)
# Determinisme (#16795) : la graine seule ne garantit PAS la reproductibilite
# (heuristiques cuDNN, kernels non deterministes). warn_only=True au premier
# passage pour inventorier les ops fautives sans faire echouer le run.
torch.use_deterministic_algorithms(True, warn_only=True)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets, transforms

SEED = 42
torch.manual_seed(SEED)
np.random.seed(SEED)

DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"PyTorch {torch.__version__} | device = {DEV} | numpy {np.__version__}")
PyTorch 2.11.0+cu128 | device = cuda | numpy 2.5.3

Reading the result: effective engine

The committed run executed on GPU (device = cuda, runtime in the cumul column of the section 4 table). The notebook remains runnable on CPU only (“Hardware: CPU is enough” at the top), at the cost of an ablation on the order of a few minutes; the measured runtime is recorded in the results table so the measurement stays dated (cf. PR #16080 body: “measured, not derived”).

The output line carries the exact environment fingerprint: “PyTorch 2.11.0+cu128 | device = cuda | numpy 2.5.3”. The initialization block also arms determinism (torch.use_deterministic_algorithms(True, warn_only=True)): comparing 18 configurations requires each run to start from the same state — the seed alone is not enough (cuDNN heuristics, non-deterministic kernels).

1. Reuse FT-00a’s LoRALinear, without redefining it

The mechanism is the same: B = 0 at step 0, W frozen, alpha / r scaling. We copy the same class as FT-00a (cell 6) under the name LoRALinear — same init, same forward, same merged_weight — so that no semantic divergence slips into the ablation.

class LoRALinear(nn.Module):
    """y = x @ W.T + (alpha / r) * (x @ A.T) @ B.T   -- W gele, seuls A et B vivent."""

    def __init__(self, base: nn.Linear, r: int, alpha: float):
        super().__init__()
        assert r > 0, "le rang doit etre strictement positif"
        self.base = base
        for p in self.base.parameters():
            p.requires_grad_(False)
        self.r, self.alpha = r, alpha
        self.scaling = alpha / r
        dev, dt = base.weight.device, base.weight.dtype
        self.A = nn.Parameter(
            torch.randn(r, base.in_features, device=dev, dtype=dt)
            * (1.0 / base.in_features ** 0.5)
        )
        self.B = nn.Parameter(
            torch.zeros(base.out_features, r, device=dev, dtype=dt)
        )

    def forward(self, x):
        return self.base(x) + self.scaling * ((x @ self.A.T) @ self.B.T)

    @torch.no_grad()
    def merged_weight(self):
        return self.base.weight + self.scaling * (self.B @ self.A)

    def n_trainable(self):
        return self.A.numel() + self.B.numel()

print("LoRALinear importee de FT-00a (cellule 6) -- aucune divergence de semantique.")
LoRALinear importee de FT-00a (cellule 6) -- aucune divergence de semantique.

Reading the result: fidelity to the mechanism

This cell copies FT-00a’s cell 6 class identically in semantics (init, forward, merged_weight), apart from a shortened docstring and the single addition of the n_trainable() accessor. Everything that follows builds on it as a component, not a re-implementation — that is what closes the question “is the ablation really comparing two settings, or two implementations?”

The output reduces to the line “LoRALinear importee de FT-00a (cellule 6) – aucune divergence de semantique.”: the class is in place, nothing is trained yet. It is the added n_trainable() accessor that will produce the params column of the section 5 table — each configuration’s budget is counted, not estimated.

2. Mini-task: inverted Fashion-MNIST, frozen 512→10 classifier

We reuse the same toy task as FT-00a (mini-task §3), with a subset to stay under 15 min CPU: 10,000 training images, 2,000 test. The toy model is a small CNN pre-trained on the inverted domain; we adapt only its Linear(512, 10) head via LoRA.

The CNN is frozen after pre-training: its 512 features serve as a fixed representation, and the adaptation task reduces to a 512 → 10 head — the configuration most favorable to LoRA (few parameters, a clean domain shift).

import os

DATA_DIR = os.path.join(os.path.expanduser("~"), ".cache", "ft00b")
tf = transforms.ToTensor()
train_set = datasets.FashionMNIST(DATA_DIR, train=True, download=True, transform=tf)
test_set = datasets.FashionMNIST(DATA_DIR, train=False, download=True, transform=tf)

def inverse(x):
    return 1.0 - x

# Sous-ensemble : 10k train / 2k test (deterministe, pour rester sous 15 min CPU)
rng = np.random.default_rng(SEED)
train_idx = rng.choice(len(train_set), size=10_000, replace=False)
test_idx = rng.choice(len(test_set), size=2_000, replace=False)
train_subset = torch.utils.data.Subset(train_set, train_idx.tolist())
test_subset = torch.utils.data.Subset(test_set, test_idx.tolist())
train_loader = torch.utils.data.DataLoader(train_subset, batch_size=256, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_subset, batch_size=512, shuffle=False)
print(f"Fashion-MNIST subset : {len(train_subset)} train / {len(test_subset)} test")
Fashion-MNIST subset : 10000 train / 2000 test

Reading the result: subset loaded

Four Fashion-MNIST archives are downloaded (26.4 MB, 29.5 kB, 4.42 MB, 5.15 kB), then the last line confirms the retained subset: “Fashion-MNIST subset : 10000 train / 2000 test”. It is this 10k/2k that holds the 18-configuration ablation within the budget announced at the top (~15 min on CPU) — subset size is the first lever on that budget.

class MiniCNN(nn.Module):
    """CNN jouet -- deux convolutions, sortie 512-dim avant la tete FC."""

    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
        self.pool = nn.MaxPool2d(2)
        self.fc = nn.Linear(32 * 7 * 7, 512)
        self.head = nn.Linear(512, 10)

    def features(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        return self.fc(x.flatten(1))

    def forward(self, x):
        return self.head(self.features(x))


def evaluate(model, loader, transform=None):
    model.eval()
    correct, total = 0, 0
    with torch.no_grad():
        for x, y in loader:
            x = x.to(DEV)
            if transform is not None:
                x = transform(x)
            p = model(x).argmax(1).cpu()
            correct += (p == y).sum().item()
            total += y.size(0)
    return correct / total

Subset and architecture

Architecture cousin to FT-00a’s: two convolutions (instead of three) then FC → 512 → separate head → 10 (FT-00a ended with a direct 576 → 10 head) — same family, not the same architecture. The trunk freezes the 512 features; only the head: Linear(512, 10) will be replaced by a LoRALinear in section 4: this separation is what makes the ablation targeted. We pre-train the model on the inverted domain, then evaluate its ability to generalize to the normal domain — it is on this domain shift that LoRA will adapt.

3. Pre-train the base model on the inverted domain

Identical to FT-00a §3: we train 2 epochs on (1 - x) so the model is competent on the photo negative, then mute on the target (the positive).

Two epochs of Adam (lr = 1e-3), FT-00a’s hyperparameters: same settings, same task, only the domain changes — the comparison with FT-00a remains valid.

base_model = MiniCNN().to(DEV)
opt = torch.optim.Adam(base_model.parameters(), lr=1e-3)

for epoch in range(2):
    base_model.train()
    for x, y in train_loader:
        x, y = x.to(DEV), y.to(DEV)
        opt.zero_grad()
        loss = F.cross_entropy(base_model(inverse(x)), y)
        loss.backward()
        opt.step()

acc_inv = evaluate(base_model, test_loader, transform=inverse)
acc_normal = evaluate(base_model, test_loader, transform=None)
print(f"Base, test inverse (son domaine)   : {acc_inv:.4f}")
print(f"Base, test normal (la cible LoRA)  : {acc_normal:.4f}")
Base, test inverse (son domaine)   : 0.8035
Base, test normal (la cible LoRA)  : 0.0360

Reading the result: the model is calibrated on the negative

As in FT-00a: acc_inv is high (the model masters its training domain) and acc_normal is low (below chance, which is 0.10). The committed output quantifies the gap: 0.8035 on the inverted test against 0.0360 on the normal test — competent on its domain, nearly mute on the target. It is precisely this gap that LoRA must close by adapting only the head: Linear(512, 10) head.

4. r × alpha ablation: 18 configurations

We adapt the head: Linear(512, 10) head via LoRA for 18 combinations:

  • r ∈ {1, 2, 4, 8, 16, 32} — 6 rank values
  • alpha/r ∈ {0.5, 1.0, 2.0} — 3 effective scaling values

The effective scaling alpha/r is what decouples magnitude from rank: with alpha/r = 1, doubling r does not change the amplitude of the learned signal. With alpha/r = 0.5, the signal is attenuated; with alpha/r = 2, it is amplified.

Each configuration starts from a fresh head, at fixed seed: the table rows are comparable at equal initialization, and the cumul column dates the cost of each run (the total is printed on the last line). 18 runs of 2 epochs on 10,000 images: that is the price of the measurement, contained in the budget announced at the top (~15 min on CPU) — “Total : 55.1s sur cuda” for the committed run.

RS = [1, 2, 4, 8, 16, 32]
SCALINGS = [0.5, 1.0, 2.0]   # = alpha / r
EPOCHS = 2
LR = 1e-3

results = []
t0 = time.time()

for r, scaling in itertools.product(RS, SCALINGS):
    alpha = scaling * r
    torch.manual_seed(SEED)
    np.random.seed(SEED)

    # Reset the head with a fresh LoRA wrapper -- copy of frozen base.
    m = copy.deepcopy(base_model)
    for p in m.parameters():
        p.requires_grad_(False)
    # Replace head with LoRA-wrapped fresh Linear
    head_base = nn.Linear(512, 10).to(DEV)
    nn.init.kaiming_uniform_(head_base.weight, a=5 ** 0.5)
    if head_base.bias is not None:
        nn.init.zeros_(head_base.bias)
    m.head = LoRALinear(head_base, r=r, alpha=alpha).to(DEV)

    opt = torch.optim.Adam(
        [p for p in m.head.parameters() if p.requires_grad], lr=LR
    )

    m.train()
    for epoch in range(EPOCHS):
        for x, y in train_loader:
            x, y = x.to(DEV), y.to(DEV)
            opt.zero_grad()
            loss = F.cross_entropy(m(x), y)
            loss.backward()
            opt.step()

    acc = evaluate(m, test_loader, transform=None)
    n_train = m.head.n_trainable()
    delta = time.time() - t0
    results.append((r, alpha, scaling, n_train, acc, delta))
    print(
        f"r={r:>2}  alpha={alpha:>5.1f}  alpha/r={scaling:>4.1f}  "
        f"params={n_train:>5}  acc={acc:.4f}  cumul={delta:>6.1f}s"
    )

print(f"\nTotal : {time.time() - t0:.1f}s sur {DEV}")
r= 1  alpha=  0.5  alpha/r= 0.5  params=  522  acc=0.1815  cumul=   3.1s
r= 1  alpha=  1.0  alpha/r= 1.0  params=  522  acc=0.1900  cumul=   6.3s
r= 1  alpha=  2.0  alpha/r= 2.0  params=  522  acc=0.1955  cumul=   9.3s
r= 2  alpha=  1.0  alpha/r= 0.5  params= 1044  acc=0.2080  cumul=  12.3s
r= 2  alpha=  2.0  alpha/r= 1.0  params= 1044  acc=0.2365  cumul=  16.5s
r= 2  alpha=  4.0  alpha/r= 2.0  params= 1044  acc=0.3325  cumul=  20.5s
r= 4  alpha=  2.0  alpha/r= 0.5  params= 2088  acc=0.2275  cumul=  23.0s
r= 4  alpha=  4.0  alpha/r= 1.0  params= 2088  acc=0.4145  cumul=  25.6s
r= 4  alpha=  8.0  alpha/r= 2.0  params= 2088  acc=0.4785  cumul=  28.8s
r= 8  alpha=  4.0  alpha/r= 0.5  params= 4176  acc=0.4680  cumul=  32.1s
r= 8  alpha=  8.0  alpha/r= 1.0  params= 4176  acc=0.5285  cumul=  34.9s
r= 8  alpha= 16.0  alpha/r= 2.0  params= 4176  acc=0.5805  cumul=  38.0s
r=16  alpha=  8.0  alpha/r= 0.5  params= 8352  acc=0.5250  cumul=  41.0s
r=16  alpha= 16.0  alpha/r= 1.0  params= 8352  acc=0.5880  cumul=  43.6s
r=16  alpha= 32.0  alpha/r= 2.0  params= 8352  acc=0.6210  cumul=  46.2s
r=32  alpha= 16.0  alpha/r= 0.5  params=16704  acc=0.5885  cumul=  49.2s
r=32  alpha= 32.0  alpha/r= 1.0  params=16704  acc=0.6265  cumul=  52.5s
r=32  alpha= 64.0  alpha/r= 2.0  params=16704  acc=0.6580  cumul=  55.1s

Total : 55.1s sur cuda

Reading the result: three measured regularities

Three regularities must emerge from the figures above (and the measurement confirms or nuances them):

  1. alpha/r = 1.0 is the sweet spot — it is the literature’s default choice (Hu et al. 2021 fix alpha = r for Transformers).
  2. r = 1 is too small on this task: a single degree of freedom is not enough to approach the benchmark (full head: 0.5270) or the best LoRA (0.6580 at r=32): r=1 caps at 0.1955.
  3. alpha/r = 2.0 can degrade: too much amplified signal early in training, divergence or oscillations.

What the committed table additionally shows: at fixed rank, scaling never degrades here — alpha/r = 2.0 dominates 1.0, which dominates 0.5 (at r=32: 0.5885 / 0.6265 / 0.6580). The literature’s “degradation” is not measured on this mini-task over 2 epochs; it will play out on long trajectories (guided example 3, section 7).

If one of them does not verify, that is a measured datum — not a notebook failure.

5. Summary table: accuracy × budget × scaling

Two views, read directly from the 18 measurements of section 4: accuracy by (r, alpha/r) and budget (trainable params) by r. The table carries no convergence curve — 2 epochs would not be readable anyway — that is the role of guided example 3 (trajectory over 6 epochs, section 7).

print("\n=== Exactitude par (r, alpha/r) ===")
header = "  r  | " + " | ".join(f"alpha/r={s:>4.1f}" for s in SCALINGS)
print(header)
print("-" * len(header))
for r in RS:
    row = [f"  {r:>2}  "]
    for scaling in SCALINGS:
        match = [v for v in results if v[0] == r and v[2] == scaling]
        if match:
            row.append(f"   {match[0][4]:.4f}    ")
        else:
            row.append("    --      ")
    print(" | ".join(row))

print("\n=== Budget par r (params entrainables sur la tete LoRA) ===")
for r in RS:
    n = [v[3] for v in results if v[0] == r][0]
    print(f"  r={r:>2}  ->  {n:>5} params  (full head = 5130)")

=== Exactitude par (r, alpha/r) ===
  r  | alpha/r= 0.5 | alpha/r= 1.0 | alpha/r= 2.0
-------------------------------------------------
   1   |    0.1815     |    0.1900     |    0.1955    
   2   |    0.2080     |    0.2365     |    0.3325    
   4   |    0.2275     |    0.4145     |    0.4785    
   8   |    0.4680     |    0.5285     |    0.5805    
  16   |    0.5250     |    0.5880     |    0.6210    
  32   |    0.5885     |    0.6265     |    0.6580    

=== Budget par r (params entrainables sur la tete LoRA) ===
  r= 1  ->    522 params  (full head = 5130)
  r= 2  ->   1044 params  (full head = 5130)
  r= 4  ->   2088 params  (full head = 5130)
  r= 8  ->   4176 params  (full head = 5130)
  r=16  ->   8352 params  (full head = 5130)
  r=32  ->  16704 params  (full head = 5130)

Reading the result: rank × magnitude trade-off

The budget doubles when r doubles (closed form r * (d + k) = r * 522 for 512 → 10): the budget column reads it directly, from 522 params at r=1 up to 16704 at r=32 — to be compared with the 5130 of the full head. Accuracy, on the other hand, saturates: at alpha/r = 1.0, it climbs from 0.1900 (r=1) to 0.6265 (r=32) — beyond a certain rank, adding degrees of freedom no longer helps on this mini-task. The alpha/r scaling is the second knob: it modulates the effective magnitude without changing the dimensionality of the problem.

6. Comparison against baselines

Three baselines to compare with the 18 configurations:

  • Frozen base on target: acc_normal of the base model (below chance)
  • Full fine-tuning of the head: Linear(512, 10) trained without constraint, same 2 epochs (gold standard, MED baseline)
  • LoRA r=4, alpha=4 (FT-00a): the reference configuration

The full run is the gold standard: same head, same 2 epochs, no rank constraint — it bounds what LoRA sacrifices by capping the rank. The frozen base, on the other hand, learns nothing: it is the floor below chance.

# Baseline : full fine-tuning de la tete (memes 2 epochs, sans LoRA)
torch.manual_seed(SEED)
np.random.seed(SEED)
full_model = copy.deepcopy(base_model)
for p in full_model.parameters():
    p.requires_grad_(False)
    # Except the head
for p in full_model.head.parameters():
    p.requires_grad_(True)
opt = torch.optim.Adam(full_model.head.parameters(), lr=LR)
for epoch in range(EPOCHS):
    full_model.train()
    for x, y in train_loader:
        x, y = x.to(DEV), y.to(DEV)
        opt.zero_grad()
        F.cross_entropy(full_model(x), y).backward()
        opt.step()
acc_full = evaluate(full_model, test_loader, transform=None)
print(f"Base gelee sur cible (sous le hasard) : {acc_normal:.4f}")
print(f"Full fine-tuning de la tete (etalon)  : {acc_full:.4f} (params = 5130)")

# LoRA r=4 alpha=4 (FT-00a config de reference)
match = [v for v in results if v[0] == 4 and v[2] == 1.0]
if match:
    r4_acc = match[0][4]
    print(f"LoRA r=4 alpha/r=1.0 (FT-00a config)  : {r4_acc:.4f} (params = {match[0][3]})")
Base gelee sur cible (sous le hasard) : 0.0360
Full fine-tuning de la tete (etalon)  : 0.5270 (params = 5130)
LoRA r=4 alpha/r=1.0 (FT-00a config)  : 0.4145 (params = 2088)

Reading the result: three landmarks

Three landmarks for reading the table:

  • Below chance gives the floor (the un-adapted model).
  • Full gives the reachable ceiling with the complete budget (5130 params, no rank constraint).
  • LoRA r=4 alpha/r=1.0 is FT-00a’s pedagogical configuration — how much do we sacrifice going from full to LoRA? The answer depends on the task, but it is measured in this notebook.

The output fixes the three quantified landmarks: 0.0360 (frozen base, below chance), 0.5270 (full, 5130 params) and 0.4145 (LoRA r=4, 2088 params) — the sacrifice accepted going from full to LoRA is measured here, not guessed.

7. Guided examples and exercises

Three guided examples, followed by three exercises of distinct scope. Each example demonstrates a technique; each exercise asks the student to measure a different quantity from the corresponding example. The example solutions are inside the examples (they execute and print their real outputs), not in a neighboring section.

Method: run cells 24-29 to read the guided examples (the outputs are real), then attempt exercises 30-35 (C.1-compliant stubs — pass / print(...) / result = None # TODO).

Each exercise reuses identically the code of the example before it — only the measured quantity changes: no new ingredient is required for any of the three.

Guided example 1: params/accuracy ratio for alpha/r = 1.0

For alpha/r = 1.0, compute the params / accuracy ratio for each r ∈ {1, 2, 4, 8, 16, 32} from the 18 measurements of section 4. Identify the r that minimizes this ratio — it is the marginal return of rank on this mini-task.

Why it matters: a rank r=1 can look efficient (few params) but under-adapts; a rank r=32 can look accurate but costly in inference memory. The params / accuracy ratio estimates the cost per accuracy point — that is what an engineer must look at to choose the rank to deploy.

Guided example 2: observing the alpha/r = 2.0 vs 1.0 degradation

Take back FT-00a’s invariant: ‖delta_W‖ = (alpha/r) * ‖B @ A‖. For r = 4, measure ‖B @ A‖ at the end of training for the two scalings alpha/r ∈ {1.0, 2.0}. Compare with ‖B @ A‖ * scaling (the effective magnitude of the delta).

Why it matters: the measurement isolates the cause of the degradation observed in section 4 — it is the amplification of the B@A signal that saturates, not the rank itself.

Guided example 3: epoch-by-epoch accuracy curve over 6 epochs

For r = 4 and alpha/r = 2.0, train for 6 epochs. At each epoch, measure test accuracy. Identify the amplification threshold — the epoch from which accuracy starts to oscillate or drop.

Why it matters: the cell demonstrates the trajectory of an over-amplifying configuration — useful to understand when early stopping would pay off on this same configuration.

Exercise 1: alpha/r = 0.5 — when rank is no longer enough

Redo the analysis of guided example 1 (params / accuracy ratio) for alpha/r = 0.5 over the 6 ranks. Compare with the alpha/r = 1.0 regime: does the params / accuracy ratio grow faster at low scaling? Identify the rank where the marginal return of rank starts to decline — that is the signal that the signal has become under-amplified.

Hint 1: take back the for r in RS loop of guided example 1, replacing v[2] == 1.0 with v[2] == 0.5.

Hint 2: to compare, compute the ratio params/acc(0.5) / params/acc(1.0) for each rank — a constant ratio would indicate that scaling is a mere multiplicative factor.

Exercise 2: ‖B@A‖ / r — the normalized invariant

Guided example 2 measures raw ‖B @ A‖. To compare across ranks without confusing dimension and magnitude, compute the normalized version ‖B @ A‖ / r for the three scalings alpha/r ∈ {0.5, 1.0, 2.0}, at r = 4. If LoRA is well calibrated, this ratio must decrease as scaling grows beyond 1 (the over-amplified signal saturates, so the effective magnitude caps).

Hint 1: take back the _train_and_measure function of guided example 2 (it already returns norm_dW).

Hint 2: the quantity to compare is norm_dW / scaling, not norm_dW / r — it is the effective magnitude that must cap, not the magnitude per degree of freedom.

Exercise 3: early stopping — the safe zone of r=8 / alpha/r = 1.0

Guided example 3 demonstrates the divergent trajectory of r=4 / alpha/r = 2.0 over 6 epochs. Redo the measurement on r = 8 / alpha/r = 1.0 (safe zone per sections 4-5) but over 3 epochs only — the natural horizon for early stopping. Compare the final accuracy with that of the same config measured by the section 4 ablation (r=8, scaling=1.0, 2 epochs): does the 3rd epoch bring a significant marginal gain?

Hint 1: take back the training loop of guided example 3, replacing r=4, alpha=8.0 with r=8, alpha=8.0 (alpha/r = 1.0) and range(1, 7) with range(1, 4).

Hint 2: the 2-epoch accuracy appears in results (filter v[0] == 8 and v[2] == 1.0). Compare it with the final accuracy of this exercise.

# Exemple guide 1 : ratio params / accuracy sur alpha/r = 1.0
# Grandeur mesuree : cout marginal par point d'exactitude.
print("=== ratio params / accuracy (alpha/r = 1.0) ===")
ratios = []
for r in RS:
    match = [v for v in results if v[0] == r and v[2] == 1.0]
    if match:
        n, acc = match[0][3], match[0][4]
        ratio = n / max(acc, 1e-6)
        ratios.append((r, n, acc, ratio))
        print(f"  r={r:>2}  params={n:>5}  acc={acc:.4f}  params/acc={ratio:>8.1f}")

best = min(ratios, key=lambda x: x[3]) if ratios else None
if best:
    print(f"\nJuste rang (min params/acc) : r={best[0]}, acc={best[2]:.4f}, ratio={best[3]:.1f}")
else:
    print("Aucune donnee pour ce scaling.")
=== ratio params / accuracy (alpha/r = 1.0) ===
  r= 1  params=  522  acc=0.1900  params/acc=  2747.4
  r= 2  params= 1044  acc=0.2365  params/acc=  4414.4
  r= 4  params= 2088  acc=0.4145  params/acc=  5037.4
  r= 8  params= 4176  acc=0.5285  params/acc=  7901.6
  r=16  params= 8352  acc=0.5880  params/acc= 14204.1
  r=32  params=16704  acc=0.6265  params/acc= 26662.4

Juste rang (min params/acc) : r=1, acc=0.1900, ratio=2747.4

Reading the result: marginal return degrades

The params/acc ratio grows with rank: from 2747.4 at r=1 (acc 0.1900) up to 26662.4 at r=32 (acc 0.6265), and the output identifies r=1 as “Juste rang (min params/acc)”. This minimum is misleading: it minimizes cost per accuracy point, not quality — the most frugal rank is also the least accurate (0.1900, against 0.6265 at r=32).

# Exemple guide 2 : ||B @ A|| a la fin de l'entrainement pour les deux scalings
# Grandeur mesuree : amplification du produit B @ A par le scaling.
def _train_and_measure(r, scaling, epochs=2):
    alpha = scaling * r
    torch.manual_seed(SEED)
    m = copy.deepcopy(base_model)
    for p in m.parameters():
        p.requires_grad_(False)
    head_base = nn.Linear(512, 10).to(DEV)
    nn.init.kaiming_uniform_(head_base.weight, a=5 ** 0.5)
    if head_base.bias is not None:
        nn.init.zeros_(head_base.bias)
    m.head = LoRALinear(head_base, r=r, alpha=alpha).to(DEV)
    opt = torch.optim.Adam(
        [p for p in m.head.parameters() if p.requires_grad], lr=LR
    )
    for _ in range(epochs):
        m.train()
        for x, y in train_loader:
            x, y = x.to(DEV), y.to(DEV)
            opt.zero_grad()
            F.cross_entropy(m(x), y).backward()
            opt.step()
    delta_W = m.head.scaling * (m.head.B @ m.head.A)
    return delta_W.norm().item(), m.head.A.norm().item(), m.head.B.norm().item()

for scaling in [1.0, 2.0]:
    norm_dW, norm_A, norm_B = _train_and_measure(r=4, scaling=scaling)
    print(
        f"alpha/r={scaling}  ||delta_W||={norm_dW:.4f}  ||A||={norm_A:.4f}  ||B||={norm_B:.4f}"
    )
alpha/r=1.0  ||delta_W||=1.1712  ||A||=3.9894  ||B||=0.4746
alpha/r=2.0  ||delta_W||=1.8837  ||A||=3.6879  ||B||=0.4275

Reading the result: amplification of the effective delta

At r=4, going from alpha/r = 1.0 to alpha/r = 2.0 takes the norm of the effective delta ‖delta_W‖ from 1.1712 to 1.8837: scaling amplifies the learned signal, without doubling it. The intermediate norms show it: ‖A‖ varies little (3.9894 → 3.6879) and ‖B‖ decreases (0.4746 → 0.4275) — the compensation comes from both factors, not just one.

# Exemple guide 3 : seuil d'amplification sur 6 epochs (r=4, alpha/r = 2.0)
# Grandeur mesuree : trajectoire d'accuracy epoch-par-epoch en regime suramplifie.
torch.manual_seed(SEED)
m = copy.deepcopy(base_model)
for p in m.parameters():
    p.requires_grad_(False)
head_base = nn.Linear(512, 10).to(DEV)
nn.init.kaiming_uniform_(head_base.weight, a=5 ** 0.5)
if head_base.bias is not None:
    nn.init.zeros_(head_base.bias)
m.head = LoRALinear(head_base, r=4, alpha=8.0).to(DEV)  # alpha/r = 2.0
opt = torch.optim.Adam(
    [p for p in m.head.parameters() if p.requires_grad], lr=LR
)
print("epoch | acc test")
print("------|----------")
for epoch in range(1, 7):
    m.train()
    for x, y in train_loader:
        x, y = x.to(DEV), y.to(DEV)
        opt.zero_grad()
        F.cross_entropy(m(x), y).backward()
        opt.step()
    acc = evaluate(m, test_loader, transform=None)
    print(f"  {epoch}  | {acc:.4f}")
epoch | acc test
------|----------
  1  | 0.2095
  2  | 0.4720
  3  | 0.5170
  4  | 0.5705
  5  | 0.5945
  6  | 0.5980

Reading the result: trajectory over 6 epochs

The committed trajectory climbs from 0.2095 (epoch 1) to 0.5980 (epoch 6) with no oscillation or drop: 0.4720, 0.5170, 0.5705, 0.5945, 0.5980 — the gains visibly flatten at the end. On this run, no “amplification threshold” appears: the measurement nuances the starting hypothesis rather than confirming it.

# Exercice 1 : ratio params / accuracy sur alpha/r = 0.5
#
# Indice 1 : 'results' est une liste de tuples (r, scaling, alpha, n_params, acc_test)
#             deja construite par les cellules precedentes (section 4).
# Indice 2 : pour comparer a alpha/r = 1.0, utiliser les donnees de l'exemple guide 1.
ratios_low = []
result = None  # TODO etudiant : construire ratios_low
print("=== ratio params / accuracy (alpha/r = 0.5) ===")
print("TODO : completer la construction de ratios_low")
print("TODO : comparer a alpha/r = 1.0 via le ratio ratios_low / ratios")
=== ratio params / accuracy (alpha/r = 0.5) ===
TODO : completer la construction de ratios_low
TODO : comparer a alpha/r = 1.0 via le ratio ratios_low / ratios
# Exercice 2 : ||B @ A|| normalise par r, sur les 3 scalings a r=4
#
# Indice 1 : reprendre _train_and_measure (defini a l'exemple guide 2) pour chaque scaling.
# Indice 2 : la grandeur pertinente est norm_dW / scaling -- c'est l'invariant de magnitude.
result = None  # TODO etudiant : pour scaling in [0.5, 1.0, 2.0], calculer norm_dW / scaling
print("=== ||B@A|| / scaling (r=4) ===")
print("TODO : completer la mesure de l'invariant normalise")
=== ||B@A|| / scaling (r=4) ===
TODO : completer la mesure de l'invariant normalise
# Exercice 3 : trajectoire 3 epochs en r=8 / alpha/r = 1.0 (zone sure)
#
# Indice 1 : reprendre la structure de l'exemple guide 3 en changeant r=4 -> r=8, alpha=8.0,
#             et range(1, 7) -> range(1, 4).
# Indice 2 : comparer l'accuracy finale a celle stockee dans 'results' pour r=8, scaling=1.0.
result = None  # TODO etudiant : entrainer 3 epochs, mesurer accuracy a chaque epoch, comparer a results
print("=== early-stopping r=8 / alpha/r = 1.0 (3 epochs) ===")
print("TODO : completer la trajectoire 3-epochs")
=== early-stopping r=8 / alpha/r = 1.0 (3 epochs) ===
TODO : completer la trajectoire 3-epochs

Summary

Three regularities measured on the same mini-task, six rank values, three scalings:

  • alpha/r = 1.0 is the reference choice: the effective magnitude of the signal is neutral, and rank alone commands dimensionality.
  • r = 1 is too small on inverted Fashion-MNIST: a single degree of freedom under-adapts. Beyond r = 4, gains saturate.
  • alpha/r = 2.0 can degrade: too much amplified signal, oscillations or divergence on large models.

The alpha / r decoupling is what makes the two knobs independently tunable: increasing r does not change the signal magnitude, and changing alpha without touching r does not change dimensionality. That is the ingredient that makes LoRA practical on 7B+ models — where rank stays small (r = 8 typical) but scaling becomes a fine-calibration hyperparameter.

Wiring: FT-00a (mechanism) → FT-00b (tuning) → FT-01 (LoRA with peft on GPT-2) → FT-02 (QLoRA 4-bit) → FT-06 (vision-language).

Next step: FT-00c pits this manual tuning against the state of the art on a real task.

Retour au sommet