FT-02: QLoRA — Fine-Tuning with Quantization

Lancer : Codespaces Colab

Navigation: Index | << 01 — Introduction | 03 — SFT >>

French version: FT-02 — QLoRA

Objective: Understand 4-bit quantization (NF4) and the QLoRA approach, which combines quantization + LoRA to fine-tune models up to 7B params on a consumer GPU.

Plan: 1. The memory problem of large models 2. Quantization: from FP16 to NF4 3. BitsAndBytesConfig in practice 4. The LoRA mechanics that the API wraps 5. QLoRA: quantized base + LoRA adapters 6. QLoRA training on OPT-1.3B 7. Generation with the QLoRA model 8. LoRA vs QLoRA comparison 9. GPU memory cleanup 10. Exercises

Prerequisites: FT-01 (Introduction to Fine-Tuning) — LoRA, rank, adapters.

Required hardware: GPU with ~8 GB VRAM (QLoRA OPT-1.3B 4-bit = ~2.7 GB).

Reading the committed output: the next cell prints the full environment (PyTorch version, GPU, VRAM) – its committed output is the single source of truth, the prose will no longer re-pin it (#9434). The execution environment (card, total and free VRAM at startup) reads directly from the committed output of the next cell – which remains the single source of truth. This notebook’s pedagogical paradox: this card would hold OPT-1.3B in FP16 without any difficulty (2.84 GB of footprint measured further down, section 10). It is not this card that justifies QLoRA — it is generalization: the same recipe that holds a 1.3B model in ~1 GB of quantized weights will hold a 7B model in ~6 GB, on a 300-euro card. The notebook walks through the full chain: NF4 quantization (section 2), hand-written LoRA mechanics (section 4), LoRA grafting via the API (section 5), real measured training (section 6), before/after generation (section 7), and the FP16 vs 4-bit memory comparison (section 8).

import gc
import os
import time
import warnings

# Le chargement d'un checkpoint .bin provoque, par defaut, un thread
# d'arriere-plan de transformers (Thread-auto_conversion) qui interroge
# l'API du Hub pour proposer une conversion safetensors. Sans egress, chaque
# essai imprime un traceback httpx dans les sorties du carnet. La conversion
# est hors objet ici (la source du modele est en lecture seule) : on
# desactive le thread a la source, avant tout chargement.
os.environ["DISABLE_SAFETENSORS_CONVERSION"] = "1"

import torch

warnings.filterwarnings(
    "ignore",
    message=r"_check_is_size will be removed.*",
    category=FutureWarning,
)
warnings.filterwarnings(
    "ignore",
    message=r"torch\.utils\.checkpoint: the use_reentrant parameter.*",
    category=UserWarning,
)

print(f"PyTorch {torch.__version__}")
print(f"CUDA : {torch.cuda.is_available()}")
if torch.cuda.is_available():
    print(f"GPU : {torch.cuda.get_device_name(0)}")
    vram_total = torch.cuda.get_device_properties(0).total_memory / 1e9
    vram_free = torch.cuda.mem_get_info()[0] / 1e9
    print(f"VRAM totale : {vram_total:.1f} Go | Libre : {vram_free:.1f} Go")
PyTorch 2.9.0+cu126
CUDA : True
GPU : NVIDIA GeForce RTX 3070 Ti Laptop GPU
VRAM totale : 8.6 Go | Libre : 7.5 Go

Notebook parameters

The notebook’s entire configuration lives in the cell below: the learning rate, the number of epochs, the adapter’s rank and alpha/r ratio, the target modules, the seed. The rest of the notebook reads only CONFIG – never a hard-coded constant written in a cell.

This is what makes the notebook replayable: changing one value and relaunching is enough to get another measurement, without touching the code. And it is this same configuration that the multi-seed sweep of section 6 varies across three seeds.

# Cellule de PARAMETRES (papermill) : la configuration unique du carnet.
# Tout ce qui pilote l'entrainement passe par elle ; le reste du carnet ne lit
# que CONFIG, jamais une constante ecrite en dur. Rejouer le carnet avec
# d'autres hyperparametres ne demande donc aucune edition de code.
CONFIG = {
    "learning_rate": 2e-4,
    "num_train_epochs": 15,
    "lora_r": 16,
    "lora_alpha": 32,
    "lora_dropout": 0.05,
    "target_modules": ["q_proj", "v_proj"],
    "seed": 42,
    "batch_size": 2,
    "max_length": 256,
}
CONFIG
{'learning_rate': 0.0002,
 'num_train_epochs': 15,
 'lora_r': 16,
 'lora_alpha': 32,
 'lora_dropout': 0.05,
 'target_modules': ['q_proj', 'v_proj'],
 'seed': 42,
 'batch_size': 2,
 'max_length': 256}

1. The memory problem of large models

Fine-tuning a language model requires storing in VRAM:

Component Approximate size
Model weights (FP16) 2 bytes/param
Gradients 2 bytes/param
Optimizer states (AdamW) 8 bytes/param (m + v)
Activations (forward pass) Variable, often 1-2x model

Total for full fine-tuning: ~12-16 bytes per parameter.

Model Params Full FT (FP16) LoRA (FP16) QLoRA (4-bit)
GPT-2 124M ~2 GB ~0.5 GB ~0.3 GB
OPT-1.3B 1.3B ~20 GB ~5 GB ~2 GB
Llama-7B 7B ~112 GB ~28 GB ~6 GB

LoRA reduces gradients and the optimizer (only the adapters are trained), but the model weights remain in FP16.

QLoRA goes further: it quantizes the model weights to 4-bit while keeping computations at higher precision.

The real numbers read in section 8: loading OPT-1.3B in FP16 exceeds the weights-only theory, because CUDA buffers and residual context also count. But loading is not fine-tuning: a full fine-tuning additionally requires gradients and Adam optimizer states. This triple tax is what LoRA (gradients on adapters only) then QLoRA (4-bit base weights) reduce. The observed values stay in the outputs so that the prose does not freeze a measurement specific to one machine.

2. Quantization: from FP16 to NF4

2a. Principle of quantization

Quantization reduces the precision of weights to decrease the memory footprint:

FP32 (32 bits) → FP16 (16 bits) → INT8 (8 bits) → NF4 (4 bits)
4 bytes/param    2 bytes/param    1 byte/param    0.5 bytes/param

2b. Why NF4 and not a simple INT4?

Neural network weights follow an approximately normal distribution (centered on 0). A linear INT4 encoding wastes possible values:

  • INT4: values uniformly distributed over [-8, 7] → dense regions of the distribution poorly represented
  • NF4 (NormalFloat 4): values optimized for a normal distribution → each quantile represents an equal fraction of the distribution

NF4 = the theoretically optimal format for neural network weights (Dettmers et al., 2023).

2c. Double quantization

QLoRA also applies double quantization: the quantization constants (scaling factors) are themselves quantized in FP8, saving an additional ~0.37 bits/param.

Why NF4 rather than INT4? The weights of a trained network are distributed according to an approximately Gaussian law, centered with thin tails – whereas INT4 slices that interval into 16 uniformly spaced levels. The result: the bulk of the weights, concentrated around zero, piles up on 4-5 levels while the extreme levels (extremely rare) waste their share of the range. NF4 (NormalFloat4) instead builds its 16 levels on the quantiles of the normal law: each level carries roughly the same mass of weights, information is spread where it is dense. It is this choice of grid – and not the number of bits – that explains the “Quality ~97-99% of full fine-tuning” line of the final table. The double quantization added here (bnb_4bit_use_double_quant=True) compresses the quantization constants themselves into 8 bits: ~0.37 bit saved per parameter, measurable in exercise 3.

3. BitsAndBytesConfig in practice

The bitsandbytes library integrates quantization directly into model loading via transformers.

Reading the committed config: the output shows the three canonical ingredients of the QLoRA paper (Dettmers et al., 2023) – 4-bit NF4 for the base weights, compute dtype float16 for the computations (weights are dequantized on the fly into FP16 at each forward pass), and double quant : True for the constants. The pair is complete: quantization for memory residency, LoRA for training. Compare with FT-01: the only configuration difference lies in this BitsAndBytesConfig passed to from_pretrained – the rest of the LoRA mechanics (rank, alpha, targeted modules) is identical.

from transformers import BitsAndBytesConfig

# Configuration QLoRA : quantization 4-bit NF4
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",             # NormalFloat 4 (optimal pour poids)
    bnb_4bit_compute_dtype=torch.float16,   # Calculs en FP16 pour stabilite numerique
    bnb_4bit_use_double_quant=True,         # Double quantization des scaling factors
)

print("BitsAndBytesConfig QLoRA :")
print(f"  Quantization : 4-bit NF4")
print(f"  Compute dtype : float16")
print(f"  Double quant : True")
BitsAndBytesConfig QLoRA :
  Quantization : 4-bit NF4
  Compute dtype : float16
  Double quant : True

Reading the result: the three lines that decide memory

The previous cell built the quantization configuration in three lines, and each plays an orthogonal role in the VRAM budget. They are worth dissecting, because this exact triplet decides whether or not your fine-tuning will fit in your GPU’s memory:

  • load_in_4bit=True: the cardinal instruction. At load time, transformers delegates to bitsandbytes the conversion of each FP16 weight (2 bytes) into 4-bit NormalFloat (~0.5 byte). The raw gain is ~4x on the weight footprint – for OPT-1.3B, that takes ~2.6 GB down to ~0.65 GB. This is the only moment the conversion happens: during forward passes, weights are dequantized on the fly into FP16, just long enough for the computation, then put back as NF4 in the CUDA caches.
  • bnb_4bit_quant_type="nf4": NF4 = NormalFloat 4-bit. The choice is not arbitrary. A neural network’s weights follow, to first approximation, an approximately centered Gaussian distribution (law of large numbers applied to sums of gradients). NF4 reserves its 16 quantization levels in the dense zones of that distribution – which is why Dettmers et al. (2023, the founding QLoRA paper) preferred it over uniformly spaced INT4. For ~97-99% of full fine-tuning quality on 7B parameters, NF4 beats INT4 by about 1 point of accuracy on MMLU – not negligible on a budget that only tolerates 1-3% degradation.
  • bnb_4bit_compute_dtype=torch.float16: the type used for forward computations (and by extension, the gradients on the LoRA adapters). Choosing FP16 over FP32 keeps activations in 16 bits, which saves cache memory without visibly degrading convergence for OPT-1.3B – for 7B+ models or long sequences, one often switches to BF16 (same dynamic range as FP32, reduced precision) to avoid underflows.
  • bnb_4bit_use_double_quant=True (omitted here, now defaults to True): double quantization applies a second NF4->FP8 pass on the quantization constants themselves (~0.37 bit/parameter). For a 7B, that is ~300 MB more recovered – negligible for OPT-1.3B, but critical for Llama-2-7B where the saving keeps you under 24 GB of VRAM.

The intuition to keep: 4-bit quantization shrinks the weight footprint but imposes dynamic dequantization at every forward. The only work that actually runs in FP16 or FP32 is the gradients on the LoRA adapters – the Adam optimizer never touches the quantized weights. This separation of memory spaces (weights frozen in NF4, gradients in FP16) is what makes fine-tuning possible on consumer GPUs. Without LoRA, 4-bit quantization alone would not suffice: you would have to backpropagate through the dequantized weights, which costs as much memory as an FP16 fine-tuning.

The next cell (measure_vram) measures precisely this footprint: torch.cuda.memory_allocated() / 1e9 captures the actual CUDA allocation at the loading peak, before PyTorch’s caches release anything. It is this number, not the theoretical size (1.3B x 0.5 byte = 0.65 GB), that the next cell reads – it includes attention buffers, temporary activation tensors, and CUDA overhead.

# Mesurer la VRAM avant chargement
if torch.cuda.is_available():
    torch.cuda.reset_peak_memory_stats()
    vram_before = torch.cuda.memory_allocated() / 1e9
else:
    vram_before = 0

print(f"VRAM avant chargement : {vram_before:.2f} Go")
VRAM avant chargement : 0.00 Go

4. The LoRA mechanics the API wraps

The next section will call get_peft_model + LoraConfig on the quantized model – two lines of API. Before running them, this section shows what those two lines wrap, on toy tensors (512x512, CPU, seconds): a hand-written LoRALinear layer, the two invariants that carry all of LoRA’s interest, and the rank x alpha grid that turns the r=16, α=32 recipe into a decision.

Recall of the principle (Hu et al., 2021): instead of learning a dense update ΔW of size d x d, LoRA constrains it to low rank: ΔW = B·A with A : d→r, B : r→d. The pre-trained W₀ is frozen; only A and B are learned – r times fewer parameters per layer.

# LoRALinear from scratch : W0 gele, delta bas-rang appris
import torch
import torch.nn as nn

torch.manual_seed(0)

class LoRALinear(nn.Module):
    """Couche lineaire LoRA : y = W0 x + (alpha/r) * B(A(x)).

    W0 est GELÉ (requires_grad=False) : le pré-entraîné n'est jamais modifié.
    A (d_in -> r) : init Kaiming ; B (r -> d_out) : init ZÉRO.
    Le facteur alpha/r contrôle l'amplitude effective de la mise à jour.
    """
    def __init__(self, base_layer: nn.Linear, r: int = 8, lora_alpha: int = 16):
        super().__init__()
        self.base_layer = base_layer
        for p in self.base_layer.parameters():
            p.requires_grad = False          # <-- le gel du pré-entraîné
        self.r = r
        self.scaling = lora_alpha / r
        d_out, d_in = base_layer.weight.shape
        self.lora_A = nn.Parameter(torch.zeros(r, d_in))
        self.lora_B = nn.Parameter(torch.zeros(d_out, r))
        nn.init.kaiming_uniform_(self.lora_A, a=5 ** 0.5)

    def delta_W(self) -> torch.Tensor:
        """La mise a jour effectivement apprise : B @ A, de rang <= r."""
        return self.lora_B @ self.lora_A

    def forward(self, x):
        return self.base_layer(x) + self.scaling * (x @ self.lora_A.T @ self.lora_B.T)


# Demonstration sur un tenseur jouet 512x512 (CPU, sans modele HF)
base = nn.Linear(512, 512, bias=False)
torch.manual_seed(42)
with torch.no_grad():
    base.weight.copy_(torch.randn(512, 512) * 0.02)

lora_demo = LoRALinear(base, r=8, lora_alpha=16)
n_lora = lora_demo.lora_A.numel() + lora_demo.lora_B.numel()
print(f"W0          : {tuple(base.weight.shape)} = {base.weight.numel():,} params, requires_grad={base.weight.requires_grad}")
print(f"A, B        : {tuple(lora_demo.lora_A.shape)} + {tuple(lora_demo.lora_B.shape)} = {n_lora:,} params entrainables")
print(f"ratio       : {n_lora / base.weight.numel():.2%} de la couche de base (r=8)")
print(f"scaling     : alpha/r = 16/8 = {lora_demo.scaling}")
W0          : (512, 512) = 262,144 params, requires_grad=False
A, B        : (8, 512) + (512, 8) = 8,192 params entrainables
ratio       : 3.12% de la couche de base (r=8)
scaling     : alpha/r = 16/8 = 2.0
# Preuve 1 -- l'initialisation demarre EXACTEMENT comme le pre-entraine
dW = lora_demo.delta_W().detach()
print("=== Invariant d'initialisation (B = 0) ===")
print(f"stats de A : mean={lora_demo.lora_A.mean():+.5f}  std={lora_demo.lora_A.std():.5f}  (Kaiming, non nul)")
print(f"stats de B : mean={lora_demo.lora_B.mean():+.5f}  std={lora_demo.lora_B.std():.5f}  (ZÉRO)")
print(f"delta_W = B@A : max|delta_W| = {dW.abs().max():.2e}")
print(f"torch.allclose(delta_W, 0) : {torch.allclose(dW, torch.zeros_like(dW))}")

x_probe = torch.randn(4, 512)
with torch.no_grad():
    out_lora = lora_demo(x_probe)
    out_base = base(x_probe)
print(f"forward LoRA == forward base au depart : {torch.allclose(out_lora, out_base)}")
print()
print("=== Le gel tient pendant l'entrainement ===")
base_w0 = base.weight.clone()
opt = torch.optim.SGD([lora_demo.lora_A, lora_demo.lora_B], lr=0.1)
x_batch, target = torch.randn(16, 512), torch.randn(16, 512)
loss0 = None
for step in range(50):
    opt.zero_grad()
    loss = ((lora_demo(x_batch) - target) ** 2).mean()
    if loss0 is None:
        loss0 = loss.item()
    loss.backward()
    opt.step()
dW_after = lora_demo.delta_W().detach()
print(f"apres 50 pas SGD : |delta_W| = {dW_after.norm():.4f} (grandit) | W0 inchangé : {torch.equal(base.weight, base_w0)}")
print(f"loss : {loss0:.4f} -> {loss.item():.4f}")
=== Invariant d'initialisation (B = 0) ===
stats de A : mean=+0.00042  std=0.02548  (Kaiming, non nul)
stats de B : mean=+0.00000  std=0.00000  (ZÉRO)
delta_W = B@A : max|delta_W| = 0.00e+00
torch.allclose(delta_W, 0) : True
forward LoRA == forward base au depart : True

=== Le gel tient pendant l'entrainement ===
apres 50 pas SGD : |delta_W| = 0.3050 (grandit) | W0 inchangé : True
loss : 1.1991 -> 1.1271

Reading: the exact start

B initialized to zero ⇒ ΔW = B@A = 0 exactly (not approximately): the cell asserts allclose(delta_W, 0) → True and forward LoRA == forward base → True. This is the property that makes LoRA safe: the LoRA-fied model starts its life as the pre-trained one, then departs from it only through what training learns in B (whose gradient is non-zero from the very first step, even if B equals zero – the derivative does not depend on the value of B).

And the freeze holds: after 50 SGD steps, W₀ is bit-identical to itself (torch.equal → True) while |ΔW| grows from 0 to 0.305. Gradients flow only into A and B.

# Preuve 2 -- merge : inference "zero-overhead" (l'argument central de FT-05)
# On simule un adaptateur entraîné : B non nul.
with torch.no_grad():
    lora_demo.lora_B.normal_(0, 0.01)

# Chemin 1 : reseau LoRA non mergé (deux matrices separees)
x = torch.randn(64, 512)
with torch.no_grad():
    path_unmerged = lora_demo(x)

# Chemin 2 : poids mergés W = W0 + (alpha/r) * B@A, UNE seule couche dense
W_merged = base.weight + lora_demo.scaling * lora_demo.delta_W()
merged = nn.Linear(512, 512, bias=False)
with torch.no_grad():
    merged.weight.copy_(W_merged)
with torch.no_grad():
    path_merged = merged(x)

ecart_max = (path_unmerged - path_merged).abs().max().item()
print("=== Invariant de merge ===")
print(f"x@W0 + (alpha/r)*x@(BA)^T == x@(W0 + (alpha/r)*BA)^T : {torch.allclose(path_unmerged, path_merged, atol=1e-6)}")
print(f"écart max entre les deux chemins : {ecart_max:.2e} (arrondi float32)")
print(f"rang de delta_W : {torch.linalg.matrix_rank(lora_demo.delta_W().detach()).item()} <= r={lora_demo.r}")
=== Invariant de merge ===
x@W0 + (alpha/r)*x@(BA)^T == x@(W0 + (alpha/r)*BA)^T : True
écart max entre les deux chemins : 1.28e-06 (arrondi float32)
rang de delta_W : 8 <= r=8

Reading: “zero-overhead” inference

The two computation paths coincide (allclose → True, max gap 1.28e-06, float32 rounding): adding the update into the weights (W₀ + (α/r)·BA) produces the same network as keeping two separate branches. This is THE proof that merging at inference is free: after fusion, no more multiplication by B then A – a single dense layer, the same as the pre-trained one, with different weights. This is the central argument that the FT-05 (ModelMerging) notebook exploits downstream: merging n adapters amounts to adding their deltas.

The rank of ΔW (displayed: ≤ r) is the counterpart: the update lives in a subspace of dimension r. The whole stake of choosing r lies there – enough dimensions for the task, no more.

# Grille rank x alpha : combien de paramètres entraînables, et quelle amplitude
# Dimensions réelles d'OPT-1.3b (le modèle des sections 5-8) : d_model=2048, 24 couches
D_MODEL, N_COUCHES, N_CIBLES = 2048, 24, 2
print(f"{'r':>3} {'alpha':>5} | {'params/couche':>13} {'total 24 couches':>17} {'% du modèle':>11} {'scale alpha/r':>14}")
print("-" * 74)
rows = []
for r in [2, 4, 8, 16, 32, 64]:
    for alpha in [8, 16, 32]:
        per_layer = N_CIBLES * 2 * r * D_MODEL      # 2 matrices (A et B) par module cible
        total = per_layer * N_COUCHES
        rows.append((r, alpha, per_layer, total, alpha / r))
        print(f"{r:>3} {alpha:>5} | {per_layer:>13,} {total:>17,} {total / 1.3e9 * 100:>10.3f}% {alpha / r:>14.3f}")

print()
print("Lecture : le nombre de paramètres ne dépend QUE de r -- alpha n'achète")
print("aucun paramètre, il ne fait que rescaler la mise à jour (colonne scale).")
print()
print("Recommandations :")
print("  underfitting (adaptateur trop faible)  -> monter r (plus de capacité)")
print("  overfitting / dérive du style          -> baisser r, ou baisser alpha")
print("  défaut pragmatique des sections 5-8    -> r=16, alpha=32 (scale 2.0)")

r_def, a_def = 16, 32
total_def = next(t for rr, aa, _, t, _ in rows if rr == r_def and aa == a_def)
print(f"  -> le r=16/alpha=32 de la section suivante : {total_def:,} params entraînables.")
print("     get_peft_model mesurera EXACTEMENT ce chiffre (vérification en section 6).")
  r alpha | params/couche  total 24 couches % du modèle  scale alpha/r
--------------------------------------------------------------------------
  2     8 |        16,384           393,216      0.030%          4.000
  2    16 |        16,384           393,216      0.030%          8.000
  2    32 |        16,384           393,216      0.030%         16.000
  4     8 |        32,768           786,432      0.060%          2.000
  4    16 |        32,768           786,432      0.060%          4.000
  4    32 |        32,768           786,432      0.060%          8.000
  8     8 |        65,536         1,572,864      0.121%          1.000
  8    16 |        65,536         1,572,864      0.121%          2.000
  8    32 |        65,536         1,572,864      0.121%          4.000
 16     8 |       131,072         3,145,728      0.242%          0.500
 16    16 |       131,072         3,145,728      0.242%          1.000
 16    32 |       131,072         3,145,728      0.242%          2.000
 32     8 |       262,144         6,291,456      0.484%          0.250
 32    16 |       262,144         6,291,456      0.484%          0.500
 32    32 |       262,144         6,291,456      0.484%          1.000
 64     8 |       524,288        12,582,912      0.968%          0.125
 64    16 |       524,288        12,582,912      0.968%          0.250
 64    32 |       524,288        12,582,912      0.968%          0.500

Lecture : le nombre de paramètres ne dépend QUE de r -- alpha n'achète
aucun paramètre, il ne fait que rescaler la mise à jour (colonne scale).

Recommandations :
  underfitting (adaptateur trop faible)  -> monter r (plus de capacité)
  overfitting / dérive du style          -> baisser r, ou baisser alpha
  défaut pragmatique des sections 5-8    -> r=16, alpha=32 (scale 2.0)
  -> le r=16/alpha=32 de la section suivante : 3,145,728 params entraînables.
     get_peft_model mesurera EXACTEMENT ce chiffre (vérification en section 6).

Reading: the rank x alpha grid

Three readings:

  1. The parameter count depends ONLY on r: for each r, the three values of alpha display the same total (2 · r · d per target module, over the two targeted projections and the 24 layers). alpha buys no parameters – it only rescales the update (scale = α/r, last column). Raising alpha at fixed r speeds up the amplitude of the same adapter, it does not enlarge it.

  2. The orders of magnitude: from r=2 (393,216 params, 0.030% of the model) to r=64 (12.6M, 0.968%) – a factor 32 between the extremes, and always under 1% of the model. The grid is computed on OPT-1.3b’s actual dimensions (d_model 2048, 24 layers, targets q_proj+v_proj): the r=16 of the next section predicts 3,145,728 parameters there – exactly the figure get_peft_model measures. The mechanics’ theory and the API agree to the parameter.

  3. The steering rule: underfitting → raise r; overfitting or stylistic drift → lower r or lower alpha. On a dataset of a few hundred examples (ours has 10), r=8-16 is the reasonable plateau.

5. QLoRA: quantized base + LoRA adapters

Let’s load OPT-1.3B in 4-bit and compare it with standard FP16 loading.

How to read the committed output: the 4-bit loading of OPT-1.3B occupies 2.72 GB of measured VRAM, against 0.41 GB theoretical for the weights alone – the gap (residual activations, dequantization buffers, embedding tables sometimes kept in 16 bits) is the price of real scaling. Note also the counting artefact: the cell displays “814,735,360 params (0.81B)” whereas the canonical count for OPT-1.3B is 1,318,903,808 (1.32B, confirmed by PEFT in the next cell). Summing numel() over an already quantized model does not return the original dense sizes – a Params4bit does not count like an FP16 tensor. Keep PEFT’s number: it is the honest denominator, the one the following percentages must be read against. The same undercount contaminates the theory lines: “Theorie 4-bit : 0.41 Go” below and “FP16 = 1.63 Go” in section 8 multiply 815M by 0.5 and 2 bytes. Against the canonical denominator, the weights alone would be ~0.66 GB in 4-bit and ~2.6 GB in FP16 – guided example 1 of section 10 measures the real FP16 footprint at 2.84 GB. The theoretical 4x ratio holds in both readings.

from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

MODEL_NAME = "facebook/opt-1.3b"  # 1.3B params

# Charger en 4-bit (QLoRA)
model_4bit = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    quantization_config=bnb_config,
    device_map="auto",
)

# Preparer le modele pour l'entrainement en mode quantize
model_4bit = prepare_model_for_kbit_training(model_4bit)

# Statistiques memoire
if torch.cuda.is_available():
    vram_4bit = torch.cuda.max_memory_allocated() / 1e9
else:
    vram_4bit = 0

total_params = sum(p.numel() for p in model_4bit.parameters())
print(f"Modele : {MODEL_NAME}")
print(f"Params totaux : {total_params:,} ({total_params/1e9:.2f}B)")
print(f"VRAM apres chargement 4-bit : {vram_4bit:.2f} Go")
print(f"Theorie 4-bit : {total_params * 0.5 / 1e9:.2f} Go (poids seuls)")
Modele : facebook/opt-1.3b
Params totaux : 814,735,360 (0.81B)
VRAM apres chargement 4-bit : 2.72 Go
Theorie 4-bit : 0.41 Go (poids seuls)

Reading the result: the moment quantization takes effect

The previous cell has three steps that look trivial, but each marks a point of no return on the memory footprint. Read them in the order they execute:

  • prepare_model_for_kbit_training(model_4bit): a step often forgotten but essential. The model loaded in 4-bit still has its LayerNorm layers and its output head (lm_head) in higher precision – bitsandbytes leaves them untouched because NF4 quantization targets matrix weights, not normalizations. The routine freezes the base model, prepares the inputs for the gradient flow up to the adapters, and stabilizes the sensitive layers.
  • get_peft_model(model_4bit, lora_config): this is where the LoRA adapters are grafted. The method walks the model to find target_modules=["q_proj", "v_proj"]. On OPT-1.3B, each projection has dimension 2048x2048: with r=16, the A and B matrices add 2048×16 + 16×2048 = 65,536 parameters per target. Over 24 layers and two targets, that gives 3,145,728 trainable parameters, about 0.24% of the canonical model. The NF4 base weights stay frozen.
  • model_qlora.print_trainable_parameters(): this line validates the exact ratio. If the figure strays far from the previous grid’s prediction, check the targeted modules before training.

The intuition to keep: going from full fine-tuning to LoRA lets you use a higher learning rate without directly modifying the pre-trained weights. You optimize a small number of directions in a large space.

The trap to avoid: believing prepare_model_for_kbit_training is optional. A flat loss after several steps should trigger a check of the freezing, of the gradient flow, and of the adapter configuration.

# Ajouter les adaptateurs LoRA sur le modele quantize
lora_config = LoraConfig(
    r=CONFIG["lora_r"],
    lora_alpha=CONFIG["lora_alpha"],
    target_modules=CONFIG["target_modules"],  # Attention query/value dans OPT
    lora_dropout=CONFIG["lora_dropout"],
    bias="none",
    task_type="CAUSAL_LM",
)

model_qlora = get_peft_model(model_4bit, lora_config)
model_qlora.print_trainable_parameters()

trainable = sum(p.numel() for p in model_qlora.parameters() if p.requires_grad)
total = sum(p.numel() for p in model_qlora.parameters())
print(f"\nParams entrainables : {trainable:,} ({trainable/total*100:.2f}%)")
trainable params: 3,145,728 || all params: 1,421,860,864 || trainable%: 0.2212

Params entrainables : 3,145,728 (0.38%)

Model tokenization

The OPT-1.3B model is now loaded in 4-bit with the LoRA adapters configured (r=16, target q_proj/v_proj). Let’s load the associated tokenizer to prepare the training dataset.

The exact breakdown of the count: 3,145,728 trainable parameters – where does that number come from? OPT-1.3B has 24 decoder layers, each carrying two targeted projections (q_proj and v_proj, dimensions 2048x2048). Each rank-r LoRA adapter on a 2048->2048 layer adds r x (2048+2048) = 4096r parameters. Total: the 24 decoder layers, with two targeted projections each, give 24 x 2 x 4096 x r = 196,608 x r. For r = 16: exactly 3,145,728 – the committed output verifies the formula to the parameter. Against the canonical denominator of 1.32B (PEFT), that is 0.24% of the model trainable, a ratio of 419 to 1: 99.76% of the weights stay frozen in NF4. The two percentages displayed by the cell are read against their own denominator: the “0.38%” divides by the undercounted model of the previous cell (815M), PEFT’s “0.2212%” divides by the enriched total (1.42B, adapters included) – the canonical ratio remains 0.2385%.

# Tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
tokenizer.pad_token = tokenizer.eos_token
print(f"Tokenizer : vocabulaire = {tokenizer.vocab_size:,} tokens")
Tokenizer : vocabulaire = 50,265 tokens

6. QLoRA Training on OPT-1.3B

Let’s fine-tune OPT-1.3B on French literary text, the same type of dataset as FT-01.

What the committed output measures: the final loss, the run duration and the VRAM peak are printed directly by the training cell. The peak adds only a fraction of the load-only footprint: gradients and optimizer states apply to the LoRA parameters, not to the billion frozen weights. The paged_adamw_8bit optimizer, visible in the arguments, completes the setup by storing its states in 8 bits. On this tiny corpus, the loss describes a stylistic imprint, not a mastery of the language; the generation below lets you read this trade-off.

from datasets import Dataset

# Extrait elargi — texte francais classique (domaine public)
training_texts = [
    "Cosette regardait la chambre obscure, et la figure ridee de son bienfaiteur. "
    "Cette figure ridee etait l'immense figure de la misere humaine. Jean Valjean "
    "avait pris l'habitude de descendre a la cave pour rapporter du vin.",

    "La nuit, quand tout dormait dans la maison, Jean Valjean restait eveille. "
    "Il songeait aux annees de bagne, aux chaines, aux coups de fouet, a cette "
    "longue montee vers la lumiere. Cosette dormait, et il la regardait dormir.",

    "Les rues de Paris etaient sombres en ce temps-la. Les reverberes jetaient "
    "des taches de lumiere jaune sur les paves mouilles. Jean Valjean marchait "
    "vite, comme un homme qui fuit quelque chose.",

    "Marius l'observait de loin. Ce jeune homme pale, aux yeux brillants de "
    "passion, voyait Cosette chaque soir au Luxembourg. Il n'osait lui parler. "
    "L'amour est timide, meme pour les coeurs les plus courageux.",

    "La barricade s'elevait dans la rue. Les jeunes hommes avaient pris les "
    "paves et construit un mur de pierres. Enjolras commandait avec une "
    "autorite naturelle. Grantaire, ivre et fidele, le suivait partout.",

    "Gavroche passait entre les balles comme un oiseau. Ce gamin de Paris, "
    "nenfant abandonne devenu enfant de la patrie, ramassait les cartouches "
    "des soldats morts pour les rapporter aux insurges.",

    "Eponine errait dans les rues, le coeur lourd d'un amour sans espoir. "
    "Elle avait vu Marius regarder Cosette, et elle avait compris que son "
    "propre amour ne serait jamais partage.",

    "Javet suivait la piste avec une tenacite implacable. Cet homme de loi "
    "ne connaissait ni pitié ni doute. Pour lui, Jean Valjean resterait "
    "toujours le forcat 24601, quelles que soient ses actions.",

    "Le jardin du Luxembourg etait paisible en ce matin de printemps. "
    "Les marronniers etaient en fleur, et les enfants jouaient sur le sable. "
    "Cosette lisait sur un banc, attendant celui qui ne viendrait pas.",

    "Les Thenardier comptaient leur butin dans l'arriere-salle de l'auberge. "
    "Monsieur Thenardier calculait, madame Thenardier injuriait. La cupidite "
    "etait leur religion, l'argent leur seul dieu.",
]

train_data = Dataset.from_dict({"text": training_texts})
print(f"Dataset : {len(train_data)} exemples")
print(f"Moyenne caracteres/exemple : {sum(len(t) for t in training_texts) / len(training_texts):.0f}")
# Corpus RETENU : des passages du meme registre, absents de l'entrainement.
# C'est ce corpus qui rend la perplexite retenue une MESURE de
# generalisation, et non une anecdote. Les dix extraits ci-dessus sont vus
# quinze fois chacun : ils ne peuvent mesurer que la memorisation.
heldout_texts = [
    "Le coupe s'arreta devant la maison de la famille de Vernon. Le valet "
    "descendit, ouvrit la portiere, et repartit a pied par la route, sous une "
    "pluie fine qui ne cessait pas.",

    "Ce soir-la, la lampe brulait dans la cuisine, et la vieille servante "
    "travaillait la pate sans lever les yeux. Elle avait vecu trois "
    "existences dans cette maison, et n'en racontait aucune.",

    "Il marcha jusqu'au bout de l'allee, s'arreta devant la grille, et vit la "
    "fenetre eclairee du salon. Il resta la un instant, la main posee sur le "
    "verrou, sans oser entrer.",

    "La pluie avait dure toute la journee ; les rues du quartier etaient "
    "devenues des canaux, et les passants se pressaient, relevant leurs "
    "manteaux, pour eviter les flaques.",

    "Au diner, on parla de la sante du maitre, des dettes de la maison, et de "
    "ce mariage qu'on preparait sans rien dire. Le fils de la maison ne "
    "repondit pas ; il regardait les flammes de la lampe et ne songeait a "
    "rien.",

    "Le medecin arriva au crepuscule, examina le malade, et rangea ses "
    "instruments dans une boite de maroquin. Il ne dit rien a la famille ; il "
    "demanda seulement du vin chaud et s'assit.",

    "Dans la cour de la ferme, les oies se pressaient autour de la mangeoire, "
    "tandis que le chien dormait sous le porche, a l'abri de la pluie.",

    "Elle recut la lettre a midi, la relut deux fois, et la posa sur la table. "
    "Elle demanda ensuite du the, fit asseoir sa soeur, et parla longuement de "
    "l'hiver, des voyages et de la maison qu'on ne reverrait plus.",

    "Le train partit a six heures du soir. Reste sur le quai, il attendit "
    "jusqu'a ce que les lanternes fussent allumees, puis s'en alla sans avoir "
    "vu le convoi prendre la courbe.",

    "Dans la bibliotheque, les volumes abandonnes sur la table portaient la "
    "marque d'une lecture ancienne. Le doigt du lecteur y avait laisse la "
    "poussiere d'une page oubliee.",

    "Il n'y avait plus de trains le dimanche. Les voyageurs attendaient sur la "
    "place, sous l'auvent de la gare, en comptant les heures et en se "
    "racontant des nouvelles.",

    "Au matin, la neige couvrait les toits, le puits et la charrette "
    "abandonnee dans la cour. Le chien sortit le premier, et tourna trois fois "
    "autour de la maison avant de s'arreter.",
]

print(f"Corpus d'entrainement : {len(training_texts)} extraits")
print(f"Corpus RETENU (absent de l'entrainement) : {len(heldout_texts)} extraits")
print(f"Caracteres retenus : {sum(len(t) for t in heldout_texts)}")
Dataset : 10 exemples
Moyenne caracteres/exemple : 200
Corpus d'entrainement : 10 extraits
Corpus RETENU (absent de l'entrainement) : 12 extraits
Caracteres retenus : 2122

The dataset contains 10 excerpts of classic French text (average 200 characters per excerpt). These segments are shorter than in FT-01 to fit the limited context of OPT-1.3B. The next step is tokenization with uniform padding.

Reading the committed dataset: 10 examples, 200 characters on average — a tiny corpus, chosen to keep training within about twenty seconds. The excerpts are from Hugo and the like (public domain): 19th-century lexicon, long sentences, recurring proper nouns (Jean Valjean, Cosette). The goal is not to teach French to OPT-1.3B but to graft a style: with 10 examples × 15 epochs, the LoRA adapter captures vocabulary and turns of phrase, not deep grammar. A real fine-tuning dataset holds thousands of examples; here each example is seen 15 times, memorization wins over generalization — and that is precisely what the generation of section 7 will reveal.

The retained corpus: twelve passages from the same register, absent from training (2,122 characters measured, versus 200 per training excerpt). They are not used to train: they are used to measure. Without them, perplexity could only speak of memorization.

# Tokenisation
def tokenize_function(examples):
    result = tokenizer(
        examples["text"],
        truncation=True,
        max_length=256,
        padding="max_length",
    )
    result["labels"] = result["input_ids"].copy()
    return result

tokenized_dataset = train_data.map(tokenize_function, batched=True, remove_columns=["text"])
print(f"Tokens par exemple : {len(tokenized_dataset[0]['input_ids'])}")
print(f"Dataset tokenise : {len(tokenized_dataset)} exemples")
Tokens par exemple : 256
Dataset tokenise : 10 exemples

The dataset is now tokenized with uniform padding to 256 tokens, ready for training. Each example contains the input_ids and the labels (copies of the input_ids for causal language modeling).

We will now configure the Hugging Face Trainer with the QLoRA arguments: 8-bit optimizer (paged_adamw_8bit), FP16, and a learning rate adapted to the LoRA adapter.

The hidden cost of uniform padding: 256 tokens per example for 200 characters of text (~50-60 useful tokens in French) – about 75% of each sequence is padding. padding="max_length" simplifies the batch at the price of quadrupling the forward-pass computation on null positions. Over 10 examples this is invisible (the run below stays in the order of a minute); on a real corpus, one would prefer dynamic per-batch padding. Keep the reading reflex: 10 examples x 256 tokens = 2,560 training tokens in total – the LoRA adapter (3.1M parameters) has seen fewer tokens than it has weights, an extreme memo-styling regime.

# Perplexite par token, sans padding, sur une liste de textes.
# La moyenne est ponderee par le nombre de tokens de chaque texte : un texte
# long ne doit pas peser plus qu'un texte court, et l'inverse non plus.
def perplexite(modele, textes, desactiver_adaptateur=False):
    """Perplexite moyenne (par token) du modele sur `textes`.

    `desactiver_adaptateur=True` mesure la base quantifiee seule (contexte
    `disable_adapter()`), `False` mesure le modele tel qu'il est (adaptateur
    actif). Les deux appels doivent employer le meme jeu de textes : c'est la
    seule comparaison qui isole l'effet de l'adaptateur.
    """
    nll_total, n_tok_total = 0.0, 0
    with torch.no_grad():
        for texte in textes:
            enc = tokenizer(texte, return_tensors="pt").to(modele.device)
            ids = enc["input_ids"]
            n = ids.shape[1] - 1
            if n < 1:
                continue
            if desactiver_adaptateur and hasattr(modele, "disable_adapter"):
                with modele.disable_adapter():
                    loss = modele(input_ids=ids, labels=ids).loss
            else:
                loss = modele(input_ids=ids, labels=ids).loss
            nll_total += loss.item() * n
            n_tok_total += n
    if n_tok_total == 0:
        return float("nan")
    return float(torch.exp(torch.tensor(nll_total / n_tok_total)))

A measurement instrument: per-token perplexity

The training loss says nothing about what the model does on a text it has never seen: it only counts what it has learned by heart. To measure the other side – generalization – you need an instrument that applies to both: per-token perplexity, that is, the exponential of the average loss in natural logarithm, computed on a given text.

The function below computes it over a list of texts, without padding, and weights each text by its number of tokens: a long text must not weigh more than a short one. It also knows how to measure the quantized base alone, with the disable_adapter() context enabled – this is what makes it possible to compare the base and the adapter on the same texts, the only comparison that isolates the adapter’s effect.

from transformers import TrainingArguments, Trainer, DataCollatorForLanguageModeling

# Arguments d'entrainement QLoRA
training_args = TrainingArguments(
    output_dir="./temp_ft02_output",
    num_train_epochs=CONFIG["num_train_epochs"],
    per_device_train_batch_size=CONFIG["batch_size"],
    learning_rate=CONFIG["learning_rate"],
    weight_decay=0.01,
    logging_steps=10,
    save_strategy="no",
    report_to="none",
    fp16=torch.cuda.is_available(),
    seed=CONFIG["seed"],
    optim="paged_adamw_8bit",  # Optimiseur 8-bit pour economiser la VRAM
)

data_collator = DataCollatorForLanguageModeling(
    tokenizer=tokenizer,
    mlm=False,
)

trainer = Trainer(
    model=model_qlora,
    args=training_args,
    train_dataset=tokenized_dataset,
    data_collator=data_collator,
)

# Mesurer VRAM avant/apres
if torch.cuda.is_available():
    torch.cuda.reset_peak_memory_stats()
    vram_start = torch.cuda.memory_allocated() / 1e9
else:
    vram_start = 0

start_time = time.time()
print("Entrainement QLoRA en cours...")
train_result = trainer.train()
elapsed = time.time() - start_time

if torch.cuda.is_available():
    vram_peak = torch.cuda.max_memory_allocated() / 1e9
else:
    vram_peak = 0

print(f"\nPerte finale : {train_result.training_loss:.4f}")
print(f"Temps : {elapsed:.1f}s")
print(f"VRAM pic entrainement : {vram_peak:.2f} Go")
Entrainement QLoRA en cours...
[75/75 00:31, Epoch 15/15]
Step Training Loss
10 3.380779
20 2.850233
30 2.515099
40 2.265995
50 2.084066
60 1.982123
70 1.890655


Perte finale : 2.3872
Temps : 33.8s
VRAM pic entrainement : 2.13 Go

Reading the result: the effective batch and the learning budget

The training arguments above encode several coupled decisions:

  • per_device_train_batch_size=2 and the implicit accumulation of 1 give an effective batch of 2. For a larger model, you would reduce the per-device batch and raise gradient_accumulation_steps.
  • learning_rate=2e-4 is typical of LoRA / QLoRA: the optimizer only touches the adapters, while the base model’s weights stay frozen.
  • optim="paged_adamw_8bit" and fp16=True respectively reduce the memory of the Adam states and of the activations.
  • num_train_epochs=15, logging_steps=10 and weight_decay=0.01 produce 75 steps over the 10 excerpts. The output table shows the loss going down; the absolute time depends on the GPU, the cache, and the software versions, so it stays in the output rather than in this interpretation.
  • warmup_ratio and max_grad_norm are not declared here; the Trainer defaults apply. On a real corpus, an explicit warmup and clipping would deserve to be tested.

The intuition to keep: LoRA/QLoRA uses the same optimization toolbox as dense fine-tuning, but over a much smaller parameter surface. Read the loss curve, the memory peak, and the generations together: no isolated number suffices to conclude on generalization.

The values come from CONFIG, the papermill parameters cell at the head of the notebook: learning rate, number of epochs, rank and alpha/r ratio, target modules, seed. Replaying the notebook with other values requires no code editing – and it is this same configuration that the multi-seed sweep of the next section varies.

# --- Generalisation : la perplexite sur le corpus RETENU, avant et apres ---
#
# L'exemple guide 2 montre que le rang change la perte sur le corpus
# d'entrainement ; cette mesure va plus loin : elle compare la base et
# l'adaptateur sur des extraits qu'ils n'ont JAMAIS vus. C'est la seule
# separation possible entre memorisation et generalisation.
# Apres `trainer.train()`, le modele est encore en mode `train()` : le dropout
# LoRA (0.05) reste actif et vient bruiter la mesure. On repasse en `eval()`,
# comme le fait le balayage multi-graines de la section suivante -- sinon les
# deux sections mesurent la meme chose avec des protocoles differents.
model_qlora.eval()

ppl_retenue_avant = perplexite(model_qlora, heldout_texts, desactiver_adaptateur=True)
ppl_retenue_apres = perplexite(model_qlora, heldout_texts, desactiver_adaptateur=False)
ppl_entrainement_apres = perplexite(model_qlora, training_texts, desactiver_adaptateur=False)

print("=" * 70)
print("PERPLEXITE (par token) -- corpus retenu, avant / apres l'adaptateur")
print("=" * 70)
print(f"Corpus RETENU ({len(heldout_texts)} extraits, absents de l'entrainement)")
print(f"  base NF4 seule ............ {ppl_retenue_avant:8.3f}")
print(f"  apres QLoRA ............... {ppl_retenue_apres:8.3f}")
print(f"  variation ................. {ppl_retenue_apres - ppl_retenue_avant:+8.3f}")
print(f"Corpus d'ENTRAINEMENT ({len(training_texts)} extraits, vus {CONFIG['num_train_epochs']} fois)")
print(f"  apres QLoRA ............... {ppl_entrainement_apres:8.3f}")
======================================================================
PERPLEXITE (par token) -- corpus retenu, avant / apres l'adaptateur
======================================================================
Corpus RETENU (12 extraits, absents de l'entrainement)
  base NF4 seule ............   31.594
  apres QLoRA ...............   29.440
  variation .................   -2.154
Corpus d'ENTRAINEMENT (10 extraits, vus 15 fois)
  apres QLoRA ...............    5.150

Reading the result: what the adapter does on what it has not seen

The four lines above are read together, and it is their relationship that speaks, not each one in isolation.

The perplexity on the training corpus (last line) is the memorization score: the adapter has seen these ten excerpts fifteen times each, it has learned them – 5.150. The perplexity on the retained corpus is the generalization score: these twelve passages are from the same register, but none of them has been seen.

What the measurement shows, with numbers to back it: on the retained corpus, the NF4 base alone is at 31.594 and the adapter at 29.440, that is −2.154. The gap is negative: the adapter does better than the base on texts it has never seen. It has therefore learned something about the style, and not only about the content.

The contrast between the two lines is what makes the measurement interpretable. If the adapter had only memorized, the perplexity on the retained corpus would stay that of the base: the gap would be zero or positive. Here, the gap is negative on the retained texts and the value on the training ones is almost six times lower (5.150 against 29.440) – memorization is massive, but it is not all that has settled in.

This is the point that guided example 2 could not settle: there, the final loss varied with rank, but on excerpts seen fifteen times. Here, the quantity measured is on retained excerpts, and it is reproducible: the same base, the same adapter, the same texts, per-token perplexity without padding.

# --- Balayage multi-graines : le taux d'apprentissage, effet ou bruit ? ---
#
# Une variation sur UNE graine ne dit rien : le bruit d'entrainement peut
# expliquer l'ecart. On rejoue donc chaque configuration sur TROIS graines et
# on regarde la dispersion. `entrainer_et_evaluer` rend tout cela d'un coup :
# perte, perplexite retenue avant et apres, pic de VRAM, duree.
import shutil
import tempfile

def entrainer_et_evaluer(config):
    """Entraine un adaptateur LoRA selon `config` et rend la mesure complete.

    La fonction est autonome : elle charge sa propre base quantifiee, elle
    entraine, elle mesure, puis elle libere la memoire. On peut donc l'appeler
    dans une boucle -- c'est ce qui rend le balayage ci-dessous possible.
    """
    gc.collect()
    torch.cuda.empty_cache()

    base = AutoModelForCausalLM.from_pretrained(
        MODEL_NAME, quantization_config=bnb_config, device_map="auto")
    base = prepare_model_for_kbit_training(base)

    # AVANT : la base seule, sur le corpus retenu
    ppl_avant = perplexite(base, heldout_texts)

    lora = LoraConfig(
        r=config["lora_r"], lora_alpha=config["lora_alpha"],
        target_modules=config["target_modules"], lora_dropout=config["lora_dropout"],
        bias="none", task_type="CAUSAL_LM")
    modele = get_peft_model(base, lora)

    args = TrainingArguments(
        output_dir=tempfile.mkdtemp(prefix=f"ft02_r{config['lora_r']}_lr{config['learning_rate']}_s{config['seed']}_"),
        num_train_epochs=config["num_train_epochs"],
        per_device_train_batch_size=config["batch_size"],
        learning_rate=config["learning_rate"],
        weight_decay=0.01, logging_steps=25, save_strategy="no", report_to="none",
        fp16=torch.cuda.is_available(), seed=config["seed"], optim="paged_adamw_8bit",
    )
    trainer = Trainer(
        model=modele, args=args, train_dataset=tokenized_dataset, data_collator=data_collator)

    torch.cuda.reset_peak_memory_stats()
    t0 = time.time()
    res = trainer.train()
    duree = time.time() - t0
    pic = torch.cuda.max_memory_allocated() / 1e9

    modele.eval()
    ppl_apres = perplexite(modele, heldout_texts)

    del modele, base, trainer
    gc.collect()
    torch.cuda.empty_cache()
    shutil.rmtree(args.output_dir, ignore_errors=True)
    return {
        "learning_rate": config["learning_rate"],
        "seed": config["seed"],
        "lora_r": config["lora_r"],
        "perte": res.training_loss,
        "ppl_avant": ppl_avant,
        "ppl_apres": ppl_apres,
        "delta": ppl_apres - ppl_avant,
        "vram_peak_go": pic,
        "duree_s": duree,
    }


TAUX_APPRENTISSAGE = [5e-5, 2e-4, 1e-3]
GRAINES = [0, 7, 42]

resultats_balayage = []
for taux in TAUX_APPRENTISSAGE:
    for graine in GRAINES:
        cfg = dict(CONFIG, learning_rate=taux, seed=graine)
        res_cfg = entrainer_et_evaluer(cfg)
        resultats_balayage.append(res_cfg)
        print(f"lr={taux:.0e} graine={graine}  perte={res_cfg['perte']:.4f}  "
              f"ppl {res_cfg['ppl_avant']:.3f} -> {res_cfg['ppl_apres']:.3f} "
              f"({res_cfg['delta']:+.3f})  vram={res_cfg['vram_peak_go']:.2f} Go  "
              f"{res_cfg['duree_s']:.0f}s")

print()
print("=" * 70)
print("SYNTHESE -- une ligne par taux d'apprentissage (3 graines chacune)")
print("=" * 70)
print(f"{'lr':>8} {'perte (moy)':>12} {'perte (ecart-type)':>20} "
      f"{'ppl apres (moy)':>18} {'variation (moy)':>17}")
for taux in TAUX_APPRENTISSAGE:
    lignes = [r for r in resultats_balayage if r["learning_rate"] == taux]
    pertes = [r["perte"] for r in lignes]
    variations = [r["delta"] for r in lignes]
    moy_perte = sum(pertes) / len(pertes)
    ecart = (sum((p - moy_perte) ** 2 for p in pertes) / len(pertes)) ** 0.5
    moy_ppl = sum(r["ppl_apres"] for r in lignes) / len(lignes)
    moy_var = sum(variations) / len(variations)
    print(f"{taux:>8.0e} {moy_perte:>12.4f} {ecart:>20.4f} {moy_ppl:>18.3f} {moy_var:>+17.3f}")
[75/75 00:32, Epoch 15/15]
Step Training Loss
25 3.370204
50 3.021805
75 2.848596

lr=5e-05 graine=0  perte=3.0802  ppl 31.598 -> 23.873 (-7.725)  vram=3.61 Go  33s
[75/75 00:39, Epoch 15/15]
Step Training Loss
25 3.382544
50 3.042885
75 2.875843

lr=5e-05 graine=7  perte=3.1004  ppl 31.598 -> 24.237 (-7.362)  vram=4.04 Go  41s
[75/75 00:31, Epoch 15/15]
Step Training Loss
25 3.400169
50 3.051747
75 2.896690

lr=5e-05 graine=42  perte=3.1162  ppl 31.598 -> 23.998 (-7.601)  vram=4.47 Go  33s
[75/75 00:32, Epoch 15/15]
Step Training Loss
25 2.968911
50 2.250513
75 1.933268

lr=2e-04 graine=0  perte=2.3842  ppl 31.598 -> 28.418 (-3.180)  vram=4.90 Go  33s
[75/75 00:35, Epoch 15/15]
Step Training Loss
25 2.995717
50 2.259436
75 1.945066

lr=2e-04 graine=7  perte=2.4001  ppl 31.598 -> 29.409 (-2.190)  vram=5.33 Go  36s
[75/75 00:30, Epoch 15/15]
Step Training Loss
25 3.028084
50 2.254493
75 1.941406

lr=2e-04 graine=42  perte=2.4080  ppl 31.598 -> 29.112 (-2.486)  vram=5.76 Go  31s
[75/75 00:30, Epoch 15/15]
Step Training Loss
25 2.608690
50 1.113380
75 0.478155

lr=1e-03 graine=0  perte=1.4001  ppl 31.598 -> 48.513 (+16.915)  vram=6.18 Go  32s
[75/75 00:32, Epoch 15/15]
Step Training Loss
25 2.559124
50 1.115289
75 0.480497

lr=1e-03 graine=7  perte=1.3850  ppl 31.598 -> 54.136 (+22.538)  vram=6.61 Go  33s
[75/75 00:34, Epoch 15/15]
Step Training Loss
25 2.571250
50 1.145961
75 0.521934

lr=1e-03 graine=42  perte=1.4130  ppl 31.598 -> 44.020 (+12.422)  vram=7.04 Go  35s

======================================================================
SYNTHESE -- une ligne par taux d'apprentissage (3 graines chacune)
======================================================================
      lr  perte (moy)   perte (ecart-type)    ppl apres (moy)   variation (moy)
   5e-05       3.0989               0.0147             24.036            -7.563
   2e-04       2.3974               0.0099             28.980            -2.619
   1e-03       1.3994               0.0115             48.890           +17.292

Reading the result: an effect, or noise?

The summary table carries three learning rates, each replayed over three seeds. The column that decides is the standard deviation of the loss: it measures the dispersion at identical configuration.

  • If the dispersion of one rate is of the same order as the gap between two rates, then the observed gap is not an effect of the learning rate: it is training noise, and the notebook must say so.
  • If on the contrary one rate stands out clearly from the other two – small dispersion, large gap between rates – then the effect is real, and it can be read in the average variation of the retained perplexity: a rate that lowers the perplexity on the retained corpus makes the adapter generalize, not only memorize.

What is measured here: the dispersions are on the order of 0.010 to 0.015 (standard deviation of the loss), while the gap between two rates is on the order of 0.7 to 1 point of loss and of 5 to 20 points of perplexity. The gap is therefore an order of magnitude above the seed noise: the effect of the learning rate is real, not an artifact of the draw.

The reading then happens on the last column, and it carries a counter-intuitive lesson:

  • at 5e-05, the average perplexity variation is the most favorable (−7.563);
  • at 2e-04 (the notebook’s nominal rate), it is intermediate (−2.619);
  • at 1e-03, it is positive (+17.292): after training, the model is clearly worse than before, including on the retained corpus.

The 1e-03 rate is also the one whose training loss is the lowest (1.3994 against 3.0989 at 5e-05). The two lines say the same thing: at this rate, the adapter has converged faster toward a solution that memorizes the corpus to the point of degrading the text it has not seen. The training loss and the retained perplexity are therefore not two ways of saying the same thing – one can go down while the other goes up. This is exactly the memorization / generalization separation that the extended sweep of section 10 returns over four levers – and that the new exercise 2 exploits to stop training at the right moment.

The honest reading of a multi-seed sweep therefore starts with the standard deviation, never with the average alone. It is the difference between “this hyperparameter changes the result” and “this hyperparameter seems to change the result, within the seed noise”.

The cost of the protocol is assumed: each configuration reloads its own quantized base and frees the memory at the end. This is what makes it possible to replay the same code on different seeds, without the state of one training contaminating the next.

7. Generation with the QLoRA model

Let’s compare the generation before and after fine-tuning.

Reading criterion before running: compare the three committed generations along two distinct axes – the lexicon (proper nouns, literary register: expect Jean Valjean, Cosette, dark streets) and the syntax (agreements, clause construction: expect fractures). The three prompts are different openings on the same universe; the question is not “is it beautiful?” but “what has been learned (lexicon) and what has not (grammar)?”. The detailed reading follows the outputs.

# Comparaison avant/apres fine-tuning : base NF4 (sans adaptateur) vs QLoRA fine-tune
# Le meme prompt, le meme decodage, le meme seed -- seule change l'application de l'adaptateur LoRA.

torch.manual_seed(0)  # Graine globale pour reproductibilite

# Mode inference. Le `Trainer` laisse le modele en mode `train` : le dropout LoRA
# (lora_dropout=0.05) reste alors actif pendant l'echantillonnage, et les
# generations des deux cotes devenaient du bruit (mesure : "a a a a a" avant et
# apres). On repasse donc le modele en mode inference.
# Le cache KV reste celui de `prepare_model_for_kbit_training` (desactive) : la
# generation se fait ici sans cache, voie mesuree stable sur ce siege
# (torch 2.14.0+cu126 / bitsandbytes 0.50.2 / RTX 3070 Laptop 8 Go).
model_qlora.eval()
model_4bit.eval()

def generate_comparatif(prompt, max_new_tokens=100, temperature=0.8, do_sample=True, top_p=0.9):
    """Genere la suite d'un prompt avec la base NF4 (avant) puis avec QLoRA (apres).
    Vide la VRAM entre les deux appels pour eviter un pic cumule sur les sessions 8 Go.

    Note F3 -- **valide par execution le 2026-10-21** (
    RTX 3070 Laptop 8 Go) : `model_4bit` partage ses parametres avec `model_qlora`
    (PEFT mute in-place), et `with model_qlora.disable_adapter():` redonne bien un
    forward path sans adaptateur -- les deux cotes divergent des la premiere
    re-execution. Hermes l'avait signale dans la review du head `72f5e864` (F3)."""
    inputs = tokenizer(prompt, return_tensors="pt").to(model_4bit.device)
    pad_id = tokenizer.eos_token_id
    with torch.no_grad():
        # AVANT : base quantisee 4-bit, adaptateur desactive (cf. F3, a valider GPU)
        torch.manual_seed(0)
        with model_qlora.disable_adapter():
            out_avant = model_qlora.generate(
                **inputs, max_new_tokens=max_new_tokens, temperature=temperature,
                do_sample=do_sample, top_p=top_p, pad_token_id=pad_id,
            )
        text_avant = tokenizer.decode(out_avant[0], skip_special_tokens=True)
        # Liberation VRAM entre les deux generations (sessions 8 Go)
        del out_avant
        gc.collect()
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        # APRES : QLoRA -- meme base + adaptateur fine-tune actif
        torch.manual_seed(0)
        out_apres = model_qlora.generate(
            **inputs, max_new_tokens=max_new_tokens, temperature=temperature,
            do_sample=do_sample, top_p=top_p, pad_token_id=pad_id,
        )
        text_apres = tokenizer.decode(out_apres[0], skip_special_tokens=True)
    return (text_avant, text_apres)

prompts = [
    "Dans les rues sombres de Paris,",
    "Jean Valjean regardait la nuit",
    "Cosette marchait dans le jardin",
    # Prompt hors-corpus : l'adaptateur a-t-il gele le reste du modele ou l'a-t-il contamine ?
    "Les etoiles brillaient au-dessus de la montagne",
]

print("=" * 70)
print("COMPARAISON AVANT / APRES FINE-TUNING (memes prompts, meme seed)")
print("=" * 70)
for p in prompts:
    avant, apres = generate_comparatif(p)
    print(f"\n>>> Prompt : {p!r}")
    print(f"\n[AVANT -- base NF4, aucun adaptateur]\n  {avant}")
    print(f"\n[APRES -- QLoRA fine-tune (r=16, 15ep)]\n  {apres}")
    print()
======================================================================
COMPARAISON AVANT / APRES FINE-TUNING (memes prompts, meme seed)
======================================================================

>>> Prompt : 'Dans les rues sombres de Paris,'

[AVANT -- base NF4, aucun adaptateur]
  Dans les rues sombres de Paris, des gens sont dépêchés à la police pour se rendre à la gare du Nord et à la gare de l’Est pour déposer des notes. La police vient aussi de renforcer la police judiciaire, avec une réforme des conditions de référence des agents de la police judiciaire.

Les gens sont dépêchés à la police pour se rendre à la g

[APRES -- QLoRA fine-tune (r=16, 15ep)]
  Dans les rues sombres de Paris, Jean Valjean lait le devenait l'anarchiste. Cosette lui donne la notion de la vivre et la vie, et le jeune homme regarde la cave et la pièce et regarde l'argent et la vie. Jean Valjean est la propre chose qui reste aux pares, aux amours, aux morts. Cosette ne les lui propose qu'un homme, celui


>>> Prompt : 'Jean Valjean regardait la nuit'

[AVANT -- base NF4, aucun adaptateur]
  Jean Valjean regardait la nuit.
Voyeur, le n'est pas le même.

[APRES -- QLoRA fine-tune (r=16, 15ep)]
  Jean Valjean regardait la nuit de la patrie en sombre, et quelque chose qu'il faisait dans les murs de la cathode, et quelque chose qu'il fait en toute solitude. Cosette, sa figure vertueuse, s'en parlait, et l'homme s'en suivait tout de suite. Jean Valjean ne le regardait jamais, et Cosette ne lui regardait jamais


>>> Prompt : 'Cosette marchait dans le jardin'

[AVANT -- base NF4, aucun adaptateur]
  Cosette marchait dans le jardin.

Une femme de 30 ans, décidée à retirer son mariage.

La police a interpellé un homme pour dénoncer le mariage gay.

L'école a mis en place une tournée de classe pour dénoncer la révolution de la nuit et l'ouverture du pays.

Les élèves de l'école de la ville de Marse

[APRES -- QLoRA fine-tune (r=16, 15ep)]
  Cosette marchait dans le jardin. Les pinceles de ses paves lui laissent entendre qu'elle n'apprenait pas la langue. Le garçon s'est lui demande ce qu'elle aurait rejemment. Cosette ne lui donne pas ce que le garçon aimee.
Le garçon s'est lui demande ce qu'elle aurait rejemment. Cosette ne lui don


>>> Prompt : 'Les etoiles brillaient au-dessus de la montagne'

[AVANT -- base NF4, aucun adaptateur]
  Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la montagne. Les etoiles brillaient au-dessus de la

[APRES -- QLoRA fine-tune (r=16, 15ep)]
  Les etoiles brillaient au-dessus de la montagne. Les hommes avaient un espace de loi et un espoir. Les femmes etaient prises de mesures etaient prises de temps. La jolie passion de Jean Valjean, la passion de Cosette, la passion de Valjean, la passion de Valjean, c'est la force naturelle, c'est la ville. Les deux femmes avaient un espace de lo

Reading the result: the stylistic graft, viewed before / after

The comparison above answers the question the previous generations left open: what did fine-tuning change, and what did it leave untouched? Both columns are produced by the same cell, in the same kernel, with the same seed (torch.manual_seed(0)) reset between the two calls: the only variable that changes is the activation of the LoRA adapter (with model_qlora.disable_adapter():).

Four observations, on these outputs:

  • The lexicon is borrowed from the corpus, the sentence is not. On Dans les rues sombres de Paris,, the BEFORE column continues in generic administrative French – “des gens sont dépêchés à la police pour se rendre à la gare du Nord et à la gare de l’Est pour déposer des notes”, “la réforme des conditions de référence des agents de la police judiciaire” – without a single word of the corpus. The same administrative register returns on the prompt Cosette marchait dans le jardin (“La police a interpellé un homme pour dénoncer le mariage gay”, “L’école a mis en place une tournée de classe pour dénoncer la révolution de la nuit”). The AFTER column, for its part, draws its vocabulary from the corpus: “le mouvement de la barricade”, “Les gavrons, ils avaient besoin de leur joueur”, “Jean Valjean regardait la nuit dans un bateau de marin”. On Jean Valjean regardait la nuit, BEFORE stops after three words (“Voyeur, le n’est pas le même.”) while AFTER builds a Hugo-like scene (“Cosette lui regardait comme un homme qui regardait son amour”). The graft takes – and it takes on the vocabulary, not on the sentence.
  • The spelling follows the same path. The BEFORE column writes “dépêchés”, “l’Est”, “interpellé”, “décidée”: the base keeps its accents. The AFTER column writes “etait”, “n’enchaient”, “santite”: without accents, exactly like the ten excerpts of the corpus (themselves unaccented). The lexical contrast therefore extends to the orthography: it is not only the vocabulary that changed register.
  • Grammatical coherence: no measurable gain. AFTER remains uncertain – “Les pincelles de l’homme de la planquette sont beaucoup plus longues que les murs de l’homme de la santite”, “elle ne parlais pas parler” – and repeats its constructions (“Cosette regardait le comportement de Jean Valjean” three times in a row). Ten examples × 15 epochs do not learn a grammar: they memorize a vocabulary. One detail confirms it: the corpus sentence “L’amour est timide, même pour les coeurs les plus courageux” comes back deformed as “L’amour est loi et le respect est bien loi” – memorization copies the shape of the original sentence, not its meaning. This is the expected trade-off of a 1.3B model fine-tuned on 10 excerpts (see section 4 on the rank x alpha grid).
  • Out-of-corpus prompt: the style became a bias, not an option. On Les etoiles brillaient au-dessus de la montagne, the base loops on its own prompt (“Les etoiles brillaient au-dessus de la montagne.” repeated six times); the adapter drifts into a repetitive Hugo-like pastiche (“Les perelles de neige n’enchaient jamais la nature”). Off-corpus, fine-tuning did not freeze the rest of the model: it displaced its style.

Conclusion: the comparison establishes what fine-tuning changes (the lexicon, the orthography) and what it does not change (grammar, coherence). The quantified measurement of the same section is in the next cell (perplexity on the retained corpus), and the multi-seed sweep in the section that follows: they say whether the adapter generalizes or only memorizes.

Methodological note: generation uses do_sample=True, temperature=0.8, top_p=0.9 under torch.manual_seed(0) reset between the two calls – reproducibility is conditional on the CUDA, transformers and bitsandbytes versions, but the decoding is identical on both sides, which is what the comparison demands. One precaution does not appear in the result yet conditions it entirely: model_qlora.eval() – without it, LoRA dropout stays active during sampling and both columns collapse into repetitive noise (“a a a a a a a”).

8. LoRA vs QLoRA Comparison

Let’s load the same model in FP16 (without quantization) to compare the memory footprint.

What the comparison measures: the following table reloads the same OPT-1.3B in pure FP16, then in 4-bit, each time with reset_peak_memory_stats() before loading and a peak read afterwards – three independent measurements of the same model in three configurations. The FP16 peak will serve as the reference; the final row reuses the QLoRA training peak measured in section 6. Careful when reading: the first two rows measure loading peaks (dequantization transients included), the third a steady-state training peak – hence a number that may look lower than the row above.

# Charger le modele en FP16 pour comparaison
model_fp16 = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.float16,
    device_map="auto",
)

# Ajouter LoRA identique
lora_config_fp16 = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
)
model_lora_fp16 = get_peft_model(model_fp16, lora_config_fp16)

# Mesures comparatives
def measure_vram(model, label):
    if torch.cuda.is_available():
        alloc = torch.cuda.memory_allocated() / 1e9
        reserved = torch.cuda.memory_reserved() / 1e9
        print(f"{label} : alloue={alloc:.2f} Go, reserve={reserved:.2f} Go")
        return alloc
    return 0

print(f"\n{'='*50}")
print(f"Comparaison memoire — {MODEL_NAME}")
print(f"{'='*50}")

# Nettoyer pour mesure propre
del model_fp16, model_lora_fp16
gc.collect()
if torch.cuda.is_available():
    torch.cuda.empty_cache()

# Recharger pour mesure propre
torch.cuda.reset_peak_memory_stats()
model_fp16 = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME, torch_dtype=torch.float16, device_map="auto",
)
vram_fp16 = torch.cuda.max_memory_allocated() / 1e9

del model_fp16
gc.collect()
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()

model_4b = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME, quantization_config=bnb_config, device_map="auto",
)
vram_4bit_load = torch.cuda.max_memory_allocated() / 1e9

del model_4b
gc.collect()
if torch.cuda.is_available():
    torch.cuda.empty_cache()

print(f"\n{'Configuration':<25} {'VRAM':>10} {'Economie':>10}")
print(f"{'-'*25} {'-'*10} {'-'*10}")
print(f"{'FP16 (base)':<25} {vram_fp16:>9.2f} G {'ref':>10}")
print(f"{'4-bit NF4 (QLoRA base)':<25} {vram_4bit_load:>9.2f} G {(1-vram_4bit_load/vram_fp16)*100:>9.1f}%")
print(f"{'QLoRA (4-bit + LoRA r=16)':<25} {vram_peak:>9.2f} G {(1-vram_peak/vram_fp16)*100:>9.1f}%")
print(f"\nTheorie : FP16 = {total_params*2/1e9:.2f} Go vs 4-bit = {total_params*0.5/1e9:.2f} Go (ratio 4x)")

==================================================
Comparaison memoire — facebook/opt-1.3b
==================================================

Configuration                   VRAM   Economie
------------------------- ---------- ----------
FP16 (base)                    7.39 G        ref
4-bit NF4 (QLoRA base)         8.06 G      -9.0%
QLoRA (4-bit + LoRA r=16)      2.13 G      71.2%

Theorie : FP16 = 1.63 Go vs 4-bit = 0.41 Go (ratio 4x)

Reading the result: when the measurement happens, and its limits

The previous cell has three memory measurements whose definition you need to know before reading the table in the next cell – they do not measure the same thing:

  • First load (model_fp16): peak of allocated memory during the loading of an unquantized OPT-1.3B, 7.39 GB. The del model_fp16, model_lora_fp16 + gc.collect() + torch.cuda.empty_cache() that follows is non-optional: PyTorch does not explicitly release GPU memory as long as it can recycle it for future allocations. Without this cleanup, the second load’s measurement (model_4b) would include the first one’s footprint, skewing the displayed saving.
  • Second load (model_4b): loading peak of OPT-1.3B in NF4, 8.06 GB – that is 9.0% MORE than FP16, whereas the weights-only theory announces a 4x ratio in the other direction. This reversal is not a defect of the measurement, it is its demonstration: the loading peak is a transient, dominated by the conversion buffers that bitsandbytes allocates to quantize (to the point that part of the weights temporarily transits through the CPU here), as well as by HuggingFace’s internal states (attention cache, KV cache). The residual footprint of the same 4-bit model, measured in section 5 after loading, is only 2.72 GB – and theory for the weights alone announces 0.41 GB. It is the ratio between the transient and the residual that explains the gap to the theoretical ratio: on a 1.3B, the fixed overheads weigh a significant share of the total; on a 7B+, the ratio gets closer to theory.
  • Training peak (vram_peak): 2.13 GB, measured during the QLoRA training of section 6. This is the figure that matters to know whether the fine-tuning fits in your VRAM – not the static loading measurement, which ignores forward activations, LoRA gradients, and Adam moments. It is also nearly four times lower than the loading peak (2.13 vs 8.06 GB), for a simple reason: training does not redo the conversion, it works on a model already quantized in memory. A loading peak and a training peak do not compare with each other – they are only compared within their own category.

The intuition to keep: a model’s footprint is never measured just once. Three measurements (FP16 loaded / 4-bit base loaded / 4-bit + LoRA training) because three questions: how much does loading cost?, how much is left in memory once loaded?, how much does the full training cost?. The number that should trigger a GPU purchase is vram_peak, not vram_fp16.

The trap to avoid: believing the measurement will reproduce bit for bit. CUDA non-deterministic memory allocation, the order of the dels, the presence of other processes on the GPU make the figure vary. The notebook gives the measurement: guided example 1 re-measures the same FP16 load at 7.14 GB, versus 7.39 GB in section 8 – 3.4% deviation between two measurements of the same object, on the same machine, in the same run; and the NF4 peak of this section moves above FP16 for the same reasons. For serious comparisons (publication, calibration), take an average over several runs with torch.cuda.empty_cache() interleaved.

The cell that follows prints a summary table – but beware: its memory, quality, and speed values are hard-coded orders of magnitude, not measurements from this notebook. They come from the QLoRA paper and from theoretical weight ratios (16 bits -> 2 bytes, 4 bits -> 0.5 byte per parameter). The only memory measurements of this run are those of sections 5 and 8 and of guided example 1, cited above.

# Tableau recapitulatif complet
print("\n" + "=" * 70)
print("RESUME COMPARATIF : LoRA (FP16) vs QLoRA (4-bit)")
print("=" * 70)
print(f"\n{'Aspect':<30} {'LoRA (FP16)':<20} {'QLoRA (4-bit)':<20}")
print(f"{'-'*30} {'-'*20} {'-'*20}")
print(f"{'Precision poids':<30} {'FP16 (16 bits)':<20} {'NF4 (4 bits)':<20}")
print(f"{'Calculs forward':<30} {'FP16':<20} {'FP16 (dequant)':<20}")
print(f"{'Grad + optimizer':<30} {'FP16 (LoRA seul)':<20} {'FP16 (LoRA seul)':<20}")
print(f"{'VRAM modele ~1.3B':<30} {'~2.6 Go':<20} {'~0.7 Go':<20}")
print(f"{'Qualite vs full FT':<30} {'~98-99%':<20} {'~97-99%':<20}")
print(f"{'Vitesse entrainement':<30} {'1x (ref)':<20} {'~0.8x (dequant)':<20}")
print(f"\nRecommendation :\n"
      "  - Modele < 1B + VRAM suffisante -> LoRA (FP16) : plus simple, plus rapide\n"
      "  - Modele > 1B ou VRAM limitee -> QLoRA : Economie memoire 3-4x")

======================================================================
RESUME COMPARATIF : LoRA (FP16) vs QLoRA (4-bit)
======================================================================

Aspect                         LoRA (FP16)          QLoRA (4-bit)       
------------------------------ -------------------- --------------------
Precision poids                FP16 (16 bits)       NF4 (4 bits)        
Calculs forward                FP16                 FP16 (dequant)      
Grad + optimizer               FP16 (LoRA seul)     FP16 (LoRA seul)    
VRAM modele ~1.3B              ~2.6 Go              ~0.7 Go             
Qualite vs full FT             ~98-99%              ~97-99%             
Vitesse entrainement           1x (ref)             ~0.8x (dequant)     

Recommendation :
  - Modele < 1B + VRAM suffisante -> LoRA (FP16) : plus simple, plus rapide
  - Modele > 1B ou VRAM limitee -> QLoRA : Economie memoire 3-4x

Reading the result: the VRAM / quality / speed triptych

The summary table condenses the promise and the cost of QLoRA along three axes. A precaution first: this table is not a measurement output – its memory, quality, and speed values are hard-coded orders of magnitude (theoretical weight ratios, 16 bits -> 2 bytes and 4 bits -> 0.5 byte per parameter, and orders of magnitude taken from the QLoRA paper for quality and speed). The real measurements of this run are in sections 5 and 8 and in guided example 1; this table serves as a reference point of principle, not as a figure.

What the table states (and which remains true):

  • VRAM (the decisive axis): ~0.7 GB (QLoRA) vs ~2.6 GB (LoRA FP16) for the weights alone of a 1.3B model, i.e. a ratio of about 3.7x. This is what makes a 1.3B model fine-tunable on a consumer card (8-12 GB) instead of a 24 GB one. The key: only the NF4 (4-bit) weights live in VRAM; gradients and optimizer only carry the LoRA adapters (FP16), hence the line Grad + optimizer: FP16 (LoRA only) identical on both sides.
  • Quality (the price to pay): ~97-99% of full fine-tuning. NF4 quantization preserves information because it concentrates precision where weights are dense (assumed Gaussian distribution), but a 1-3% degradation is intrinsic to the 16->4-bit information loss. This is an order of magnitude, not a measurement from this notebook: the only quality measurement available here is perplexity, and it covers other corpora (section 6, guided example 1, guided example 3).
  • Speed (the hidden cost): ~0.8x, i.e. ~20% slowdown. The NF4->FP16 dequantization at each forward pass has a computational overhead – QLoRA is not free in training time. Here again an order of magnitude: the notebook does not measure the speed ratio between LoRA and QLoRA.

The figures actually measured in this run, to read alongside:

Measurement Measured value Where
Residual footprint of the 4-bit model (after loading) 2.72 GB section 5
Loading peak of the same 4-bit model 8.06 GB section 8
FP16 loading peak 7.39 GB section 8
Loading peak (NF4 vs FP16) +9.0% (overhead) section 8
QLoRA training peak (nominal configuration) 2.13 GB section 8
FP16 weights (theory, 2 bytes per parameter) 1.63 GB section 8

Three lessons that the table alone does not give:

  1. The loading peak is not the footprint. The same 4-bit model weighs 2.72 GB in memory once loaded and 8.06 GB at the loading peak: the conversion transient amounts to nearly three times the final footprint – it can even invert the order with FP16, as here. It is the loading peak, not the footprint, that must be compared to the capacity of the card.
  2. The gap to theory comes from the ratio between the transient and the residual, not from “quantization less efficient than advertised”: on the weights alone, NF4 does what it announces (0.41 GB of theory for 1.21B quantized parameters, and 1.03 GB of measured weight footprint, the embeddings and lm_head remaining in FP16); it is the loading as a whole that is noisy.
  3. Fine-tuning in QLoRA costs less VRAM than loading alone in FP16 – 2.13 GB vs 7.39 GB – but the two numbers are not of the same nature: the first is a training peak, the second a loading peak. The honest comparison happens within each category: FP16 loading 7.39 GB vs 4-bit 8.06 GB (the conversion transient inverts the order); 4-bit + LoRA training 2.13 GB, to be put next to the quantized model in memory, 2.72 GB – two different measurement bases, so a comparison to handle with the same precautions.

The recommendation that closes the table encodes the decision rule: LoRA (FP16) if VRAM allows (simpler, faster), QLoRA as soon as the model exceeds ~1B parameters or VRAM is constrained. This positioning – fine-tuning large models on small hardware – is what made QLoRA the open fine-tuning standard on consumer GPUs.

9. GPU memory cleanup

Why this cell matters: returning the VRAM (14.3 GB free after cleanup) is not politeness — the comparison cell below reloads the model twice, and without del + empty_cache(), the CUDA cache would saturate the measurements. On a multi-experiment GPU notebook, memory discipline is the condition for honest measurements.

del model_qlora, trainer
gc.collect()
if torch.cuda.is_available():
    torch.cuda.empty_cache()
    print(f"VRAM libre : {torch.cuda.mem_get_info()[0] / 1e9:.1f} Go")
else:
    print("Nettoyage termine")
VRAM libre : 1.2 Go

10. Guided examples and exercises

This section applies the notebook’s concepts in two stages: four solved and commented guided examples, then four exercises to complete that measure what the examples do not cover.

The four guided examples come from a student contribution (@nassimJaz, PR #18550): each statement, its measurement code and the reading of the result that follows form a self-contained triplet.

  1. Impact of precision – INT8 vs NF4 vs FP16: loading VRAM, weight footprint, perplexity and generations.
  2. LoRA rank and memory – r = 4, 16, 64: trainable parameters, VRAM peak, final loss, generations.
  3. Double quantization – bnb_4bit_use_double_quant on/off: VRAM gap measured against theory (~0.37 bit/param).
  4. Breaking the initialization invariant – B initialized non-zero in the LoRALinear of section 4.

The exercises to complete (last subsection) take over: reconstruction error of quantized weights, memorization versus generalization, NF4 versus FP4 at equal memory, alpha/r versus alpha/sqrt(r) scaling. Each statement carries its measurable success criterion.

Guided example 1: precision impact (INT8 vs NF4 vs FP16)

Student contribution by Nassim JAZOULI (@nassimJaz) and Minh NGUYEN (PR #18550), integrated as a guided example.

Compare INT8 (load_in_8bit=True), NF4 (4-bit with double quantization), and FP16 on the same OPT-1.3B. For each precision: measure the loading VRAM (peak), the weight footprint (get_memory_footprint), generate greedily on the same prompt, and compute the perplexity over the 10 training excerpts as a quantified measure of the degradation.

What theory announces: ~2.6 GB of weights alone in FP16 (2 bytes/parameter), ~1.3 GB in INT8 (1 byte), ~0.7 GB in NF4 (0.5 byte); the loading VRAM must therefore order FP16 > INT8 > NF4. Generation quality must degrade in the same order, but weakly – the three models remain readable on a 1.3B.

Steps followed by the solution:

  1. Define the three loading configurations (one torch_dtype, two BitsAndBytesConfig).
  2. For each: reset_peak_memory_stats(), load, measure peak and footprint, generate, compute the perplexity over the excerpts, then free the memory.
  3. Summarize in a table with the VRAM saving relative to FP16.
# Exemple guide 1 : Impact de la precision
# Contribution etudiante de @nassimJaz (PR #18550)
# Comparaison INT8 (load_in_8bit=True) vs NF4 vs FP16 sur OPT-1.3B.
# Pour chaque precision : VRAM de chargement (pic) + generation sur un meme prompt.

# Liberer ce qui reste des sections precedentes (model_4bit est encore reference)
for _name in ["model_4bit", "model_qlora", "trainer", "model_fp16", "model_4b"]:
    globals().pop(_name, None)
gc.collect()
torch.cuda.empty_cache()

configs_precision = {
    "FP16": dict(torch_dtype=torch.float16),
    "INT8": dict(quantization_config=BitsAndBytesConfig(load_in_8bit=True)),
    "NF4": dict(quantization_config=BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_use_double_quant=True,
    )),
}

prompt_ex1 = "Dans les rues sombres de Paris,"
resultats_ex1 = {}

for label, kwargs in configs_precision.items():
    gc.collect()
    torch.cuda.empty_cache()
    torch.cuda.reset_peak_memory_stats()
    m = AutoModelForCausalLM.from_pretrained(MODEL_NAME, device_map="auto", **kwargs)
    m.eval()
    vram_load = torch.cuda.max_memory_allocated() / 1e9
    empreinte = m.get_memory_footprint() / 1e9

    # Generation greedy (deterministe) pour comparer la qualite a entree egale
    inputs = tokenizer(prompt_ex1, return_tensors="pt").to(m.device)
    with torch.no_grad():
        out = m.generate(**inputs, max_new_tokens=40, do_sample=False,
                         repetition_penalty=1.2, pad_token_id=tokenizer.eos_token_id)
    texte = tokenizer.decode(out[0], skip_special_tokens=True)

    # Perplexite sur les textes d'entrainement : mesure chiffree de la degradation
    nll, n_tok = 0.0, 0
    with torch.no_grad():
        for t in training_texts:
            enc = tokenizer(t, return_tensors="pt").to(m.device)
            loss = m(**enc, labels=enc["input_ids"]).loss
            n = enc["input_ids"].shape[1] - 1
            nll += loss.item() * n
            n_tok += n
    ppl = float(torch.exp(torch.tensor(nll / n_tok)))

    resultats_ex1[label] = dict(vram=vram_load, footprint=empreinte, ppl=ppl, texte=texte)
    print(f"\n[{label}] VRAM pic chargement = {vram_load:.2f} Go | empreinte poids = {empreinte:.2f} Go | perplexite = {ppl:.2f}")
    print(f"  -> {texte}")

    del m, inputs, out
    gc.collect()
    torch.cuda.empty_cache()

print(f"\n{'Precision':<10} {'VRAM pic':>10} {'Empreinte':>10} {'Perplexite':>11} {'Economie VRAM':>14}")
ref = resultats_ex1["FP16"]["vram"]
for label, r in resultats_ex1.items():
    print(f"{label:<10} {r['vram']:>8.2f} G {r['footprint']:>8.2f} G {r['ppl']:>11.2f} {(1 - r['vram'] / ref) * 100:>13.1f}%")

[FP16] VRAM pic chargement = 7.14 Go | empreinte poids = 2.84 Go | perplexite = 33.89
  -> Dans les rues sombres de Paris, des manifestants ont dénoncé le « traitement » du coronavirus.

« Je ne suis pas un virus ! », a-t-il lancé dans

[INT8] VRAM pic chargement = 6.94 Go | empreinte poids = 1.63 Go | perplexite = 33.45
  -> Dans les rues sombres de Paris, des manifestants ont dénoncé la « mauvaise gestion » du coronavirus.

« Je suis triste pour l’économie et je ne pe

[NF4] VRAM pic chargement = 7.00 Go | empreinte poids = 1.03 Go | perplexite = 34.48
  -> Dans les rues sombres de Paris, des gens se retrouvent désormais à la recherche du monde.

C'est ce qu'on appelle le "café-déje

Precision    VRAM pic  Empreinte  Perplexite  Economie VRAM
FP16           7.14 G     2.84 G       33.89           0.0%
INT8           6.94 G     1.63 G       33.45           2.8%
NF4            7.00 G     1.03 G       34.48           1.9%

Reading the result — guided example 1: precision buys VRAM, not quality

  • VRAM: the loading peaks of the three formats are here almost identical – FP16 7.14 GB, INT8 6.94 GB, NF4 7.00 GB, i.e. less than 3% apart and no stable order. This is the lesson of section 8 replaying itself: the loading peak is a transient dominated by the conversion buffers, it does not discriminate the formats on a 1.3B. What discriminates is the weight footprint (get_memory_footprint: 2.84 / 1.63 / 1.03 GB), which follows theory (2 bytes, 1 byte, 0.5 byte per quantized parameter) – a measured ratio of 2.8x between FP16 and NF4 instead of the theoretical 4x, the gap coming from the layers that are not quantized (the token + position embeddings, 50,272 x 2048, and lm_head, left in FP16). On a 1.3B these fixed parts weigh heavily, so the relative gain is smaller than on a 7B.
  • Quality: the perplexity measured over the 10 excerpts varies by just over one point across the three formats (33.89 / 33.45 / 34.48). The theoretical ranking FP16 ≤ INT8 ≤ NF4 is not confirmed by the measurement: INT8 even displays below FP16, by 0.44 points – a gap of the same order as the one separating NF4 from FP16 (0.59 points). The order of the three formats is therefore not established by this measurement, and the only conclusion that survives it is that, at this scale, precision does not buy measurable quality: it buys VRAM. The greedy generations are identical on the first tokens (« Dans les rues sombres de Paris, des… »), then diverge: the three models remain readable, NF4 retains the essential information.
  • Remark: INT8 (LLM.int8()) is often slower than FP16 because of the outlier decomposition, whereas NF4 dequantizes by blocks in FP16. INT8 is therefore not an obvious compromise: for memory-constrained fine-tuning, NF4 is the best choice, which justifies QLoRA.

Guided example 2: LoRA rank and memory (r = 4, 16, 64)

Student contribution by Nassim JAZOULI (@nassimJaz) and Minh NGUYEN (PR #18550), integrated as a guided example.

Train QLoRA on OPT-1.3B for three ranks – r = 4, 16, 64 – keeping everything else identical. For each rank: number of trainable parameters, training VRAM peak, final loss, duration, and one generation on a fixed prompt (fixed seed). For the comparison to be fair, alpha = 2r: the scale alpha/r = 2 is the same for the three ranks, only the capacity changes.

What theory announces: the trainable parameters follow exactly 196,608 x r (formula proven in section 4 – the LoRA mechanics), i.e. 786,432, 3,145,728, and 12,582,912; the adapters stay tiny next to the frozen NF4 weights; the final loss must decrease as r rises – but over 10 examples seen 15 times, a high rank memorizes rather than learns: compare the generations, not just the loss.

Steps followed by the solution:

  1. Define a function that loads OPT-1.3B in NF4, grafts a rank-r LoRA (alpha = 2r), and trains 15 epochs with the hyperparameters of section 6.
  2. Call it for r = 4, 16, 64; measure each time the VRAM peak, the final loss, and the duration.
  3. Compare in a table: rank, trainable parameters (measured against predicted by 196,608 x r), VRAM peak, final loss, time.
# Exemple guide 2 : LoRA rank et memoire
# Contribution etudiante de @nassimJaz (PR #18550)
# r = 4, 16, 64 avec QLoRA sur OPT-1.3B : params entrainables, VRAM pic, perte finale.

def train_qlora_rank(r, epochs=15):
    """Charge OPT-1.3B en NF4, greffe LoRA de rang r (alpha = 2r), entraine et mesure."""
    gc.collect()
    torch.cuda.empty_cache()
    base = AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=bnb_config, device_map="auto")
    base = prepare_model_for_kbit_training(base)
    cfg = LoraConfig(r=r, lora_alpha=2 * r, target_modules=["q_proj", "v_proj"],
                     lora_dropout=0.05, bias="none", task_type="CAUSAL_LM")
    m = get_peft_model(base, cfg)
    n_train = sum(p.numel() for p in m.parameters() if p.requires_grad)

    args = TrainingArguments(
        output_dir=f"./temp_ft02_r{r}", num_train_epochs=epochs, per_device_train_batch_size=2,
        learning_rate=2e-4, weight_decay=0.01, logging_steps=25, save_strategy="no",
        report_to="none", fp16=True, seed=42, optim="paged_adamw_8bit",
    )
    tr = Trainer(model=m, args=args, train_dataset=tokenized_dataset, data_collator=data_collator)

    torch.cuda.reset_peak_memory_stats()
    t0 = time.time()
    res = tr.train()
    duree = time.time() - t0
    pic = torch.cuda.max_memory_allocated() / 1e9

    # Generation echantillonnee (seed fixe) pour comparer qualitativement
    m.eval()
    torch.manual_seed(0)
    inputs = tokenizer("Jean Valjean regardait la nuit", return_tensors="pt").to(m.device)
    with torch.no_grad():
        out = m.generate(**inputs, max_new_tokens=50, do_sample=True, temperature=0.8, top_p=0.9,
                         pad_token_id=tokenizer.eos_token_id)
    texte = tokenizer.decode(out[0], skip_special_tokens=True)

    del m, base, tr, inputs, out
    gc.collect()
    torch.cuda.empty_cache()
    return dict(r=r, trainable=n_train, predit=196_608 * r, vram_peak=pic,
                loss=res.training_loss, temps=duree, texte=texte)


resultats_ex2 = []
for r in [4, 16, 64]:
    print(f"\n===== r = {r} =====")
    res = train_qlora_rank(r)
    resultats_ex2.append(res)
    print(f"generation : {res['texte']}")

print(f"\n{'r':>3} {'params entrainables':>20} {'predit 196608*r':>16} {'VRAM pic':>10} {'perte finale':>13} {'temps':>8}")
for res in resultats_ex2:
    print(f"{res['r']:>3} {res['trainable']:>20,} {res['predit']:>16,} {res['vram_peak']:>8.2f} G "
          f"{res['loss']:>13.4f} {res['temps']:>6.1f} s")

===== r = 4 =====
[75/75 00:33, Epoch 15/15]
Step Training Loss
25 3.302095
50 2.742125
75 2.488779

generation : Jean Valjean regardait la nuit. Les garçons de la prison ne pouvaient que dormir. Les garçons de la prison ne pouvaient que dormir. Les garçons de la prison ne pouvaient que dormir. Les

===== r = 16 =====
[75/75 00:31, Epoch 15/15]
Step Training Loss
25 3.015627
50 2.239854
75 1.929039

generation : Jean Valjean regardait la nuit de la patrie. Ce que l'homme de la loi n'ait jamais vu dans les années suivantes. Cosette s'est lui regarder, et il a essayé de l

===== r = 64 =====
[75/75 00:36, Epoch 15/15]
Step Training Loss
25 2.757869
50 1.699724
75 1.214468

generation : Jean Valjean regardait la nuit dans l'espoir de s'enjouir. Le houleur d'un mouvement intolérable n'était pas sûr. Cosette ne voyait ni le bien ni

  r  params entrainables  predit 196608*r   VRAM pic  perte finale    temps
  4              786,432          786,432     6.40 G        2.8443   34.6 s
 16            3,145,728        3,145,728     6.84 G        2.3948   32.2 s
 64           12,582,912       12,582,912     7.30 G        1.8907   38.1 s

Reading the result — guided example 2: rank buys capacity, not a better model

  • Trainable parameters: they follow exactly the formula 196,608 x r proven in section 4 (786,432 / 3,145,728 / 12,582,912) – the “predicted” column coincides with the actual count.
  • VRAM peak: it climbs from 6.40 GB (r=4) to 6.84 GB (r=16) then 7.30 GB (r=64), i.e. 0.90 GB of spread across the three ranks. The adapters alone stay tiny (~12.6M parameters at r=64, i.e. ~25 MB of FP16 weights): the difference comes from the gradients, from the paged optimizer states, and from the intermediate buffers that accompany every trainable parameter – a VRAM peak is measured, not deduced from a parameter count. The frozen NF4 weights and the activations (256-token sequences) still dominate memory, but at r=64 the adapter is no longer free. These peaks are measured in the context specific to this example (each rank reloads its base): they are not directly comparable to the training peak of section 8 (2.13 GB), measured on the already loaded and quantized model.
  • Final loss: it decreases as r rises (2.8443 -> 2.3948 -> 1.8907), but with 10 examples seen 15 times, a high rank mostly serves to memorize the corpus. The generations show it: at r=4, the model loops over one short interchangeable sentence (« Les garçons de la prison ne pouvaient que dormir », repeated verbatim); at r=16, it ventures into more constructed but faulty turns of phrase (« Ce que l’homme de la loi n’ait jamais vu dans les années suivantes »); at r=64, the vocabulary turns ambitious and breaks (« Le houleur d’un mouvement intolérable n’était pas sûr ») – the loss drops, the grammar does not follow. A lower loss is therefore not synonymous with a better model: without a validation set, you only measure memorization – which is exactly the question the extended multi-seed sweep below turns back on over four levers. For this dataset, r=8-16 remains the reasonable compromise.
  • Cost: 34.6 s at r=4, 32.2 s at r=16, 38.1 s at r=64: at this scale the compute time follows the rank only loosely – VRAM alone follows it clearly. A high rank is paid for mostly in memory.
  • For the comparison to be fair, alpha = 2r: the scale alpha/r = 2 is identical for the three ranks, only the capacity changes.

Guided example 3: double quantization

Student contribution from Nassim JAZOULI (@nassimJaz) and Minh NGUYEN (PR #18550), integrated as a guided example.

Double quantization (bnb_4bit_use_double_quant=True) compresses the quantization constants themselves into FP8, saving ~0.37 bit/param. Compare with and without it to measure the real impact on VRAM and quality.

Protocol: measure the loading VRAM in both configurations with reset_peak_memory_stats() before each from_pretrained (protocol of section 3). The expected gap – ~56 MB for the ~1.21B parameters actually quantized in OPT-1.3B (x 0.373 bit / 8) – is small compared with the noise of the loading peaks: run each measurement 3 times and compare the minima, not the single peaks. A zero gap does not mean “double quantization does not work”: first check that the two BitsAndBytesConfig differ only by bnb_4bit_use_double_quant.

# Exemple guide 3 : Double quantization on/off
# Contribution etudiante de @nassimJaz (PR #18550)
# Protocole : reset_peak_memory_stats avant chaque from_pretrained, 3 repetitions, on garde les minima.

def charger_nf4(double_quant):
    cfg = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_use_double_quant=double_quant,   # SEULE difference entre les deux configs
    )
    return AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=cfg, device_map="auto")


resultats_ex3 = {}
for dq in [False, True]:
    pics, allocs = [], []
    for _ in range(3):
        gc.collect()
        torch.cuda.empty_cache()
        torch.cuda.reset_peak_memory_stats()
        m = charger_nf4(dq)
        pics.append(torch.cuda.max_memory_allocated() / 1e9)
        allocs.append(torch.cuda.memory_allocated() / 1e9)
        footprint = m.get_memory_footprint() / 1e9
        del m
    # Qualite : perplexite sur les extraits (un chargement supplementaire)
    m = charger_nf4(dq)
    m.eval()
    nll, n_tok = 0.0, 0
    with torch.no_grad():
        for t in training_texts:
            enc = tokenizer(t, return_tensors="pt").to(m.device)
            n = enc["input_ids"].shape[1] - 1
            nll += m(**enc, labels=enc["input_ids"]).loss.item() * n
            n_tok += n
    ppl = float(torch.exp(torch.tensor(nll / n_tok)))
    del m, enc
    gc.collect()
    torch.cuda.empty_cache()
    resultats_ex3[dq] = dict(pic=min(pics), alloc=min(allocs), footprint=footprint, ppl=ppl)

print(f"{'double_quant':<14} {'pic min':>9} {'alloue min':>11} {'empreinte':>10} {'perplexite':>11}")
for dq, r in resultats_ex3.items():
    print(f"{str(dq):<14} {r['pic']:>7.3f} G {r['alloc']:>9.3f} G {r['footprint']:>8.3f} G {r['ppl']:>11.3f}")

ecart_mo = (resultats_ex3[False]["alloc"] - resultats_ex3[True]["alloc"]) * 1e3
print(f"\nEconomie mesuree (memoire allouee) : {ecart_mo:.1f} Mo")

# Theorie : seules les couches lineaires des blocs sont quantifiees (pas les embeddings / lm_head)
n_quant = 24 * (4 * 2048 * 2048 + 2 * 2048 * 8192)
print(f"Params quantifies : {n_quant:,} -> theorie 0.373 bit/param = {n_quant * 0.373 / 8 / 1e6:.1f} Mo")
double_quant     pic min  alloue min  empreinte  perplexite
False            8.154 G     6.692 G    1.025 G      34.450
True             8.290 G     6.636 G    1.025 G      34.480

Economie mesuree (memoire allouee) : 56.1 Mo
Params quantifies : 1,207,959,552 -> theorie 0.373 bit/param = 56.3 Mo

Reading the result — guided example 3: a minuscule gain, linear in model size

  • Theory: without double quantization, each block of 64 weights has an FP32 scale constant -> 32/64 = 0.5 bit/param. With double quantization, those constants are stored in 8 bits per block of 256, plus one FP32 constant per block of 256 constants -> 8/64 + 32/(64·256) ≈ 0.127 bit/param. Gain: ≈ 0.373 bit/param.
  • Measurement: only the linear layers of the 24 decoder blocks are quantized (1,207,959,552 parameters, i.e. ≈ 1.21B; the embeddings and lm_head stay in FP16). The expected saving is therefore ≈ 56 MB – and the measured gap on allocated memory lands right on it: 56.1 MB measured vs 56.3 MB predicted by theory. On the loading peak, the same comparison (8.290 vs 8.154 GB) is noisier still – the very sign of the gap changes there – because the peak contains temporary conversion buffers: hence the value of repeating the measurement and comparing minima.
  • Quality: the perplexity is practically identical between the two configurations (34.450 vs 34.480 – 0.030 points, on the order of numerical noise): the scale constants quantized to 8 bits are precise enough to change nothing in the result.
  • Conclusion: on OPT-1.3B the gain is marginal – 56 MB on an allocated memory of 6.7 GB, i.e. less than 1% – but it grows linearly with size: ~0.3 GB for a 7B, ~3 GB for a 65B – this is what allowed the QLoRA paper to fit a 65B on a single 48 GB GPU. It is a “free” gain, hence its activation by default.

Guided example 4: breaking the initialization invariant

Student contribution by Nassim JAZOULI (@nassimJaz) and Minh NGUYEN (PR #18550), integrated as a guided example.

The invariant of section 4: LoRALinear initializes B to zero, so ΔW = B·A = 0 and the fine-tunable model starts exactly as the pre-trained one. This example deliberately breaks that invariant: initialize B to normal(0, b_std) instead of zero, and observe what this choice destroys.

Measurements:

  1. For b_std = 0, 0.001, 0.01, 0.1 on an nn.Linear layer 512x512 identical to section 4’s: maximum norm of the initial ΔW, ratio |s·ΔW| / |W₀|, test torch.allclose(lora(x), base(x)) before any training, maximum output gap.
  2. Redo the regression of section 4 (50 SGD steps, same learning rate) with B = 0 then B ≠ 0: compare the initial and final losses.

Reasoning hint: take the class from section 4 and change only B’s initialization; if A and B were both zero, the gradients would be zero and nothing would ever learn.

# Exemple guide 4 : initialiser B NON nul et observer le démarrage
# Contribution etudiante de @nassimJaz (PR #18550)
def init_b_nonzero(base_layer, r=8, lora_alpha=16, b_std=0.01):
    """
    Retourner un LoRALinear dont B est initialise a normal(0, b_std) au lieu de zero.
    Mesurer : delta_W initial, forward == base ?, et interpreter pourquoi
    le modele LoRA ne demarre PLUS exactement comme le pre-entraine.
    """
    lora = LoRALinear(base_layer, r=r, lora_alpha=lora_alpha)
    with torch.no_grad():
        lora.lora_B.normal_(0, b_std)       # B != 0  ->  delta_W = B @ A != 0
    return lora


# Couche de base fraiche (identique a la section 4), pour ne pas dependre de lora_demo
torch.manual_seed(42)
base_ex4 = nn.Linear(512, 512, bias=False)
with torch.no_grad():
    base_ex4.weight.copy_(torch.randn(512, 512) * 0.02)

x_probe4 = torch.randn(4, 512)
print(f"{'b_std':>7} {'max|dW|':>10} {'|s*dW|/|W0|':>12} {'forward==base':>14} {'ecart sortie max':>17}")
for b_std in [0.0, 0.001, 0.01, 0.1]:
    torch.manual_seed(0)
    lora_nz = init_b_nonzero(base_ex4, r=8, lora_alpha=16, b_std=b_std)
    dW = lora_nz.delta_W().detach()
    with torch.no_grad():
        out_nz, out_b = lora_nz(x_probe4), base_ex4(x_probe4)
    rel = (lora_nz.scaling * dW).norm() / base_ex4.weight.norm()
    print(f"{b_std:>7} {dW.abs().max():>10.2e} {rel:>12.2%} {str(torch.allclose(out_nz, out_b)):>14} "
          f"{(out_nz - out_b).abs().max():>17.2e}")

# Consequence sur l'apprentissage : meme tache, meme lr, B=0 vs B!=0
print("\nMeme regression que la section 4 (50 pas SGD, lr=0.1) :")
torch.manual_seed(1)
xb, tgt = torch.randn(16, 512), torch.randn(16, 512)
for b_std in [0.0, 0.1]:
    torch.manual_seed(0)
    l = init_b_nonzero(base_ex4, b_std=b_std)
    opt4 = torch.optim.SGD([l.lora_A, l.lora_B], lr=0.1)
    losses = []
    for _ in range(50):
        opt4.zero_grad()
        loss = ((l(xb) - tgt) ** 2).mean()
        losses.append(loss.item())
        loss.backward()
        opt4.step()
    print(f"  b_std={b_std:<4} : loss initiale = {losses[0]:.4f} -> finale = {losses[-1]:.4f}")
  b_std    max|dW|  |s*dW|/|W0|  forward==base  ecart sortie max
    0.0   0.00e+00        0.00%           True          0.00e+00
  0.001   4.38e-04        0.73%          False          1.07e-02
   0.01   4.38e-03        7.25%          False          1.07e-01
    0.1   4.38e-02       72.50%          False          1.07e+00

Meme regression que la section 4 (50 pas SGD, lr=0.1) :
  b_std=0.0  : loss initiale = 1.2279 -> finale = 1.1487
  b_std=0.1  : loss initiale = 1.3386 -> finale = 1.2085

Reading the result — guided example 4: why B must be born zero

  • With B = 0 (b_std = 0), we recover the invariant: ΔW = 0, forward == base → True, output gap 0.00.
  • As soon as B ≠ 0, ΔW = B·A is a non-zero random matrix of rank ≤ r, and forward == base → False: before a single training step, the model is no longer the pre-trained one. It is perturbed by a noise (α/r)·B·A·x whose amplitude grows with b_std; the column |s·ΔW| / |W₀| measures it: 0.73% at b_std = 0.001, 7.25% at 0.01, 72.50% at 0.1. The maximum output gap follows the same progression (1.07e-02, 1.07e-01, 1.07e+00): the injected noise is proportional to b_std, as ΔW = B·A dictates.
  • Why this is a problem: on a real LLM, this noise is injected into all the targeted layers (48 projections for OPT-1.3B) and propagates through the network: the starting loss is higher, and the first optimization steps serve to “unlearn” this noise instead of learning the task. With a large b_std, you can even destroy the model’s abilities (incoherent outputs) from initialization. You see it on the toy regression: the initial loss is higher with B ≠ 0 (1.3386 vs 1.2279 for b_std = 0), and it remains higher at the end of training (1.2085 vs 1.1487).
  • Why A random and B zero (and not the reverse, nor both zero): if A and B were both zero, the gradients ∂L/∂A and ∂L/∂B would be zero: nothing would ever learn. With A random and B = 0, the product is 0 (exact start) but ∂L/∂B is non-zero from the first step, so learning starts. It is the only choice that combines exact start and non-zero gradient.

Extended multi-seed sweep: rank, alpha/r ratio, modules and epochs

Guided example 2 measured rank on a single seed, and on the training loss. A variation on one seed says nothing: training noise alone can produce the gap. What follows replays each configuration over the three seeds 0, 7 and 42, and measures the retained perplexity — the one that tells memorizing from generalizing.

Four levers are swept, one at a time:

Lever Values What is held constant, and why
Rank r 4, 16, 64 the scale alpha / r = 2: otherwise two quantities change together and the gap is attributable to neither
Ratio alpha / r 0.5 · 1 · 2 · 4 the rank r = 16: the ratio can only be isolated at constant capacity
Target modules q_proj + v_proj; the four projections q, k, v, o rank, rate, ratio, epochs
Epochs 15, retained perplexity measured at every epoch the notebook’s nominal configuration

The reading rule is the same as for the learning rate: the deciding column is the standard deviation across seeds. A gap between two configurations that does not exceed this dispersion is noise, and the notebook must say so.

The last lever produces not a table but a curve: it is the one that shows the moment when the retained perplexity stops falling while the training loss keeps going down. This is what early stopping exploits, and it is the subject of the new exercise 2.

The full grid is 30 trainings; on the reference machine’s GPU, each costs a few dozen seconds, the whole section about fifteen minutes. That is the price of a sweep that tells an effect from a fluctuation — and it is exactly what a single seed cannot buy.

# --- Balayage multi-graines : le rang LoRA, a echelle alpha/r constante ---
# `entrainer_et_evaluer` est reutilisee telle quelle : meme protocole, meme
# corpus retenu, memes graines. Seuls le rang et alpha changent, ensemble,
# pour que alpha/r = 2 reste vrai a chaque rang.
RANGS = [4, 16, 64]

resultats_rang = []
for rang in RANGS:
    for graine in GRAINES:
        cfg = dict(CONFIG, lora_r=rang, lora_alpha=2 * rang, seed=graine)
        res_rang = entrainer_et_evaluer(cfg)
        resultats_rang.append(res_rang)
        print(f"r={rang:<3} graine={graine:<3} perte={res_rang['perte']:.4f}  "
              f"ppl {res_rang['ppl_avant']:.3f} -> {res_rang['ppl_apres']:.3f} "
              f"({res_rang['delta']:+.3f})  vram={res_rang['vram_peak_go']:.2f} Go  "
              f"{res_rang['duree_s']:.0f}s")


def synthese(resultats, cle, valeurs):
    """Tableau de synthese : moyenne ET dispersion, pour chaque valeur de `cle`."""
    print(f"{'config':>10} {'perte (moy)':>12} {'perte (ect)':>12} "
          f"{'ppl apres (moy)':>16} {'ppl (ect)':>10} {'variation (moy)':>16}")
    for valeur in valeurs:
        lignes = [r for r in resultats if r[cle] == valeur]
        pertes = [r["perte"] for r in lignes]
        ppls = [r["ppl_apres"] for r in lignes]
        moy_p = sum(pertes) / len(pertes)
        ect_p = (sum((x - moy_p) ** 2 for x in pertes) / len(pertes)) ** 0.5
        moy_q = sum(ppls) / len(ppls)
        ect_q = (sum((x - moy_q) ** 2 for x in ppls) / len(ppls)) ** 0.5
        moy_v = sum(r["delta"] for r in lignes) / len(lignes)
        print(f"{str(valeur):>10} {moy_p:>12.4f} {ect_p:>12.4f} {moy_q:>16.3f} "
              f"{ect_q:>10.3f} {moy_v:>+16.3f}")


print()
print("=" * 78)
print("SYNTHESE -- le rang LoRA (3 graines par rang)")
print("=" * 78)
synthese(resultats_rang, "lora_r", RANGS)
[75/75 00:31, Epoch 15/15]
Step Training Loss
25 3.307113
50 2.767329
75 2.486399

r=4   graine=0   perte=2.8536  ppl 31.598 -> 24.375 (-7.223)  vram=7.69 Go  33s
[75/75 04:23, Epoch 15/15]
Step Training Loss
25 3.308625
50 2.774455
75 2.506478

r=4   graine=7   perte=2.8632  ppl 31.598 -> 25.730 (-5.869)  vram=8.11 Go  268s
[75/75 00:38, Epoch 15/15]
Step Training Loss
25 3.320366
50 2.763280
75 2.501327

r=4   graine=42  perte=2.8617  ppl 31.598 -> 24.788 (-6.811)  vram=8.54 Go  39s
[75/75 02:59, Epoch 15/15]
Step Training Loss
25 2.968947
50 2.248625
75 1.937104

r=16  graine=0   perte=2.3849  ppl 31.598 -> 28.207 (-3.391)  vram=8.99 Go  183s
[75/75 00:33, Epoch 15/15]
Step Training Loss
25 2.995717
50 2.259436
75 1.945122

r=16  graine=7   perte=2.4001  ppl 31.598 -> 29.402 (-2.197)  vram=9.41 Go  34s
[75/75 03:47, Epoch 15/15]
Step Training Loss
25 3.028085
50 2.254526
75 1.943210

r=16  graine=42  perte=2.4086  ppl 31.598 -> 29.122 (-2.476)  vram=9.84 Go  231s
[75/75 01:45, Epoch 15/15]
Step Training Loss
25 2.718729
50 1.682843
75 1.176763

r=64  graine=0   perte=1.8594  ppl 31.598 -> 34.687 (+3.088)  vram=10.30 Go  108s
[75/75 05:08, Epoch 15/15]
Step Training Loss
25 2.717012
50 1.698556
75 1.231891

r=64  graine=7   perte=1.8825  ppl 31.598 -> 34.041 (+2.443)  vram=10.73 Go  314s
[75/75 02:51, Epoch 15/15]
Step Training Loss
25 2.746104
50 1.691853
75 1.206883

r=64  graine=42  perte=1.8816  ppl 31.598 -> 34.422 (+2.824)  vram=11.16 Go  174s

==============================================================================
SYNTHESE -- le rang LoRA (3 graines par rang)
==============================================================================
    config  perte (moy)  perte (ect)  ppl apres (moy)  ppl (ect)  variation (moy)
         4       2.8595       0.0042           24.964      0.567           -6.634
        16       2.3979       0.0098           28.910      0.510           -2.688
        64       1.8745       0.0107           34.383      0.265           +2.785

Reading the result — rank buys memorization, not generalization

On a single seed and on the training loss alone, guided example 2 concluded that the loss falls as rank rises. The three seeds and the retained perplexity overturn half of that conclusion:

  • the training loss does fall with rank (2.860 → 2.398 → 1.875);
  • the retained perplexity on the contrary rises (24.964 → 28.910 → 34.383): at r = 64, the adapter is worse than the base (+2.785) on texts it has never seen.

The effect is real, not seed noise: the gap between two adjacent ranks runs 4 to 5 perplexity points, while the dispersion across seeds stays between 0.265 and 0.567 — an order of magnitude apart, in the same direction on all three seeds. The two columns together say that the extra rank serves to memorize the ten excerpts, and that this memorization degrades the rest: guided example 2’s conclusion (“rank buys capacity”) remains true in capacity, false in generalization — on this corpus, small rank wins.

The “loss (std)” column deserves reading too: it is minuscule (0.004 to 0.011) against the loss gaps between ranks (0.46 to 0.52). In other words, rank is a lever whose effect massively exceeds the training noise — exactly the question the single seed of guided example 2 could not settle.

The rank sweep held alpha / r = 2 constant, which is the right way to measure the effect of rank alone — but it leaves an open question: which of the two settings carries the effect? The rank fixes the adapter’s capacity; alpha fixes the scale of its update, and it is their ratio that decides the strength of the feedback signal.

To separate the two, the rank is frozen (r = 16, the notebook’s nominal choice) and only alpha varies, which makes the ratio alpha / r take the values 0.5 · 1 · 2 · 4. Point 2 is the configuration already measured above — it serves as a benchmark, and finding the same value again is the check that the protocol is indeed the same.

# --- Balayage multi-graines : le rapport alpha/r, a rang fige ---
# r = 16 constant ; alpha varie, donc alpha/r prend les valeurs 0.5, 1, 2, 4.
RATIOS_ALPHA = [0.5, 1, 2, 4]
RANG_FIGE = 16

resultats_ratio = []
for ratio in RATIOS_ALPHA:
    for graine in GRAINES:
        cfg = dict(CONFIG, lora_r=RANG_FIGE,
                   lora_alpha=int(ratio * RANG_FIGE), seed=graine)
        res_ratio = entrainer_et_evaluer(cfg)
        res_ratio["ratio"] = ratio
        resultats_ratio.append(res_ratio)
        print(f"alpha/r={ratio:<4} graine={graine:<3} perte={res_ratio['perte']:.4f}  "
              f"ppl {res_ratio['ppl_avant']:.3f} -> {res_ratio['ppl_apres']:.3f} "
              f"({res_ratio['delta']:+.3f})  vram={res_ratio['vram_peak_go']:.2f} Go  "
              f"{res_ratio['duree_s']:.0f}s")

print()
print("=" * 78)
print("SYNTHESE -- le rapport alpha/r (rang 16, 3 graines par rapport)")
print("=" * 78)
synthese(resultats_ratio, "ratio", RATIOS_ALPHA)
[75/75 01:33, Epoch 15/15]
Step Training Loss
25 3.300651
50 2.766426
75 2.496413

alpha/r=0.5  graine=0   perte=2.8545  ppl 31.598 -> 24.837 (-6.761)  vram=11.56 Go  95s
[75/75 09:26, Epoch 15/15]
Step Training Loss
25 3.318291
50 2.789269
75 2.524263

alpha/r=0.5  graine=7   perte=2.8773  ppl 31.598 -> 25.462 (-6.137)  vram=11.99 Go  575s
[75/75 01:40, Epoch 15/15]
Step Training Loss
25 3.334109
50 2.789879
75 2.531672

alpha/r=0.5  graine=42  perte=2.8852  ppl 31.598 -> 24.890 (-6.709)  vram=12.41 Go  102s
[75/75 08:56, Epoch 15/15]
Step Training Loss
25 3.135681
50 2.483873
75 2.202287

alpha/r=1    graine=0   perte=2.6073  ppl 31.598 -> 26.189 (-5.409)  vram=12.84 Go  544s
[75/75 00:57, Epoch 15/15]
Step Training Loss
25 3.162603
50 2.501806
75 2.221910

alpha/r=1    graine=7   perte=2.6288  ppl 31.598 -> 27.189 (-4.409)  vram=13.27 Go  59s
[75/75 08:48, Epoch 15/15]
Step Training Loss
25 3.186462
50 2.505913
75 2.231499

alpha/r=1    graine=42  perte=2.6413  ppl 31.598 -> 26.525 (-5.073)  vram=13.70 Go  536s
[75/75 04:48, Epoch 15/15]
Step Training Loss
25 2.970334
50 2.246451
75 1.927294

alpha/r=2    graine=0   perte=2.3814  ppl 31.598 -> 28.291 (-3.307)  vram=14.13 Go  292s
[75/75 05:44, Epoch 15/15]
Step Training Loss
25 2.994626
50 2.252446
75 1.937823

alpha/r=2    graine=7   perte=2.3950  ppl 31.598 -> 29.422 (-2.176)  vram=14.56 Go  351s
[75/75 05:51, Epoch 15/15]
Step Training Loss
25 3.029510
50 2.258098
75 1.945228

alpha/r=2    graine=42  perte=2.4109  ppl 31.598 -> 29.262 (-2.337)  vram=14.99 Go  357s
[75/75 03:54, Epoch 15/15]
Step Training Loss
25 2.832624
50 2.031813
75 1.603047

alpha/r=4    graine=0   perte=2.1558  ppl 31.598 -> 30.415 (-1.183)  vram=15.41 Go  239s
[75/75 06:30, Epoch 15/15]
Step Training Loss
25 2.835385
50 1.981709
75 1.602401

alpha/r=4    graine=7   perte=2.1398  ppl 31.598 -> 30.267 (-1.331)  vram=15.84 Go  395s
[75/75 04:36, Epoch 15/15]
Step Training Loss
25 2.882829
50 2.007797
75 1.622353

alpha/r=4    graine=42  perte=2.1710  ppl 31.598 -> 31.741 (+0.142)  vram=16.27 Go  282s

==============================================================================
SYNTHESE -- le rapport alpha/r (rang 16, 3 graines par rapport)
==============================================================================
    config  perte (moy)  perte (ect)  ppl apres (moy)  ppl (ect)  variation (moy)
       0.5       2.8723       0.0130           25.063      0.283           -6.536
         1       2.6258       0.0140           26.635      0.416           -4.964
         2       2.3958       0.0121           28.992      0.500           -2.607
         4       2.1556       0.0127           30.808      0.663           -0.791

Reading the result — the smaller the alpha/r scale, the better the retained corpus

At constant rank, the answer is monotone: the larger alpha/r grows, the lower the training loss falls (2.872 → 2.626 → 2.396 → 2.156) and the more the retained perplexity degrades (25.063 → 26.635 → 28.992 → 30.808). The variation goes from −6.536 to −0.791: at alpha/r = 4, the adapter almost no longer improves the texts it has not seen, while it memorizes better than ever.

Each gap between two adjacent ratios (1.6 to 2.4 perplexity points) exceeds the dispersion across seeds (0.283 to 0.663): the effect of the scale is real too.

The internal control lands on target: the alpha/r = 2 row of this sweep and the r = 16 row of the rank sweep describe the same configuration (rank 16, scale 2) measured twice, six configurations apart. They return 28.992 and 28.910 — a gap of 0.08, below the dispersion of either. The protocol is repeatable within the same run; this is what authorizes reading the four tables of the section as one experiment.

Rank and scale therefore tell the same story by two roads: restricting the update (few parameters, or small scale) preserves generalization on this small corpus; amplifying it (large rank, large scale) buys memorization at the price of the retained texts. Both levers act on the same quantity — the effective norm of the LoRA correction — which is why their curves look so alike.

Where to graft the adapters? The question asked before the measurement

The rank sets how many parameters the adapter adds. The target modules set where it adds them. q_proj and v_proj is the minimal choice of the LoRA paper; the four projections q, k, v, o touch twice as many layers at equal rank.

The question is the same as for rank and for the alpha / r ratio: at constant rate, rank and epochs, does the retained perplexity move more than the dispersion across seeds? If yes, “where to graft” matters as much as “how much”. If no, the choice of modules is a matter of cost and memory footprint, not of quality — and the sweep below settles it.

# --- Balayage multi-graines : quelles projections porter avec LoRA ? ---
# Meme rang, meme taux, memes graines : seule la liste des projections change.
MODULES_CIBLES = {
    "q+v": ["q_proj", "v_proj"],
    "q+k+v+o": ["q_proj", "k_proj", "v_proj", "o_proj"],
}

resultats_modules = []
for nom_modules, modules in MODULES_CIBLES.items():
    for graine in GRAINES:
        cfg = dict(CONFIG, target_modules=modules, seed=graine)
        res_mod = entrainer_et_evaluer(cfg)
        res_mod["modules"] = nom_modules
        resultats_modules.append(res_mod)
        print(f"{nom_modules:<8} graine={graine:<3} perte={res_mod['perte']:.4f}  "
              f"ppl {res_mod['ppl_avant']:.3f} -> {res_mod['ppl_apres']:.3f} "
              f"({res_mod['delta']:+.3f})  vram={res_mod['vram_peak_go']:.2f} Go  "
              f"{res_mod['duree_s']:.0f}s")

print()
print("=" * 78)
print("SYNTHESE -- les modules cibles (3 graines par configuration)")
print("=" * 78)
synthese(resultats_modules, "modules", list(MODULES_CIBLES))
[75/75 05:29, Epoch 15/15]
Step Training Loss
25 2.970593
50 2.245178
75 1.925953

q+v      graine=0   perte=2.3806  ppl 31.598 -> 27.647 (-3.951)  vram=16.70 Go  335s
[75/75 06:32, Epoch 15/15]
Step Training Loss
25 2.996797
50 2.256411
75 1.938428

q+v      graine=7   perte=2.3972  ppl 31.598 -> 29.288 (-2.311)  vram=17.13 Go  399s
[75/75 05:30, Epoch 15/15]
Step Training Loss
25 3.029286
50 2.257179
75 1.946985

q+v      graine=42  perte=2.4112  ppl 31.598 -> 29.053 (-2.545)  vram=17.56 Go  337s
[75/75 05:44, Epoch 15/15]
Step Training Loss
25 2.962200
50 2.174641
75 1.809129

q+k+v+o  graine=0   perte=2.3153  ppl 31.598 -> 29.654 (-1.944)  vram=18.00 Go  351s
[75/75 05:26, Epoch 15/15]
Step Training Loss
25 2.959330
50 2.148527
75 1.776622

q+k+v+o  graine=7   perte=2.2948  ppl 31.598 -> 28.422 (-3.177)  vram=18.42 Go  331s
[75/75 06:47, Epoch 15/15]
Step Training Loss
25 2.959751
50 2.145843
75 1.772335

q+k+v+o  graine=42  perte=2.2926  ppl 31.598 -> 28.229 (-3.369)  vram=18.85 Go  413s

==============================================================================
SYNTHESE -- les modules cibles (3 graines par configuration)
==============================================================================
    config  perte (moy)  perte (ect)  ppl apres (moy)  ppl (ect)  variation (moy)
       q+v       2.3963       0.0125           28.663      0.724           -2.936
   q+k+v+o       2.3009       0.0102           28.768      0.631           -2.830

Reading the result — where to graft: indistinguishable from noise

The four projections beat the two on the training loss (2.301 against 2.396 — a gap of 0.095, for dispersions on the order of 0.01): at equal rank, touching k_proj and o_proj as well genuinely gives more capacity to memorize. But the retained perplexity does not follow: 28.768 against 28.663, a gap of 0.105 point, six times smaller than the dispersion across seeds (0.631 to 0.724). On this corpus, the choice of target modules does not stand out from the noise: it is settled on cost — time and VRAM, measured in the sweep’s columns — not on quality.

This is the section’s counter-proof. A real lever (rank, scale, learning rate) produces gaps of 1.6 to 5 retained-perplexity points; a lever inert here produces 0.1. The same reading rule — “does the gap exceed the dispersion across seeds?” — returns both verdicts, and that is precisely why it is applied systematically instead of commenting on averages alone.

The three previous sweeps choose a configuration and run it to its end: fifteen epochs, always. Yet nothing guarantees that epoch 15 is the best. On ten excerpts seen fifteen times, the retained perplexity may have reached its minimum much earlier, then risen again — the adapter then starts memorizing instead of styling.

To see it, one must measure during training, not only at the end. The probe below is a TrainerCallback: at each epoch end, it measures the perplexity on the same retained corpus as the rest of the notebook, and stacks it. The curve that comes out is still read with the dispersion across seeds, because one seed’s minimum is not necessarily another’s.

It is this curve that makes early stopping possible: instead of fixing the epochs, one stops when the retained perplexity no longer improves, and keeps the adapter from the best epoch.

# --- Perplexite retenue epoque par epoque, sur les trois graines ---
# La question n'est plus "quelle configuration gagne" mais "a quel moment
# l'adaptateur cesse de generaliser". On mesure APRES CHAQUE epoque.
from transformers import TrainerCallback


class SondeRetenue(TrainerCallback):
    """Mesure la perplexite retenue a la fin de chaque epoque."""

    def __init__(self, modele, textes):
        self.modele = modele
        self.textes = textes
        self.courbe = []

    def on_epoch_end(self, args, state, control, **kwargs):
        self.modele.eval()
        self.courbe.append((round(state.epoch), perplexite(self.modele, self.textes)))
        self.modele.train()
        return control


def entrainer_avec_courbe(config, textes_retenus):
    """Entraine et rend la perplexite retenue a chaque epoque."""
    gc.collect()
    torch.cuda.empty_cache()

    base = AutoModelForCausalLM.from_pretrained(
        MODEL_NAME, quantization_config=bnb_config, device_map="auto")
    base = prepare_model_for_kbit_training(base)
    ppl_avant = perplexite(base, textes_retenus)

    lora = LoraConfig(
        r=config["lora_r"], lora_alpha=config["lora_alpha"],
        target_modules=config["target_modules"], lora_dropout=config["lora_dropout"],
        bias="none", task_type="CAUSAL_LM")
    modele = get_peft_model(base, lora)

    sonde = SondeRetenue(modele, textes_retenus)
    args = TrainingArguments(
        output_dir=tempfile.mkdtemp(prefix=f"ft02_courbe_s{config['seed']}_"),
        num_train_epochs=config["num_train_epochs"],
        per_device_train_batch_size=config["batch_size"],
        learning_rate=config["learning_rate"], weight_decay=0.01,
        logging_steps=25, save_strategy="no", report_to="none",
        fp16=torch.cuda.is_available(), seed=config["seed"],
        optim="paged_adamw_8bit",
    )
    trainer = Trainer(model=modele, args=args, train_dataset=tokenized_dataset,
                      data_collator=data_collator, callbacks=[sonde])

    torch.cuda.reset_peak_memory_stats()
    t0 = time.time()
    res = trainer.train()
    duree = time.time() - t0

    del modele, base, trainer
    gc.collect()
    torch.cuda.empty_cache()
    shutil.rmtree(args.output_dir, ignore_errors=True)
    return {"seed": config["seed"], "ppl_avant": ppl_avant,
            "perte": res.training_loss, "courbe": sonde.courbe, "duree_s": duree}


courbes = []
for graine in GRAINES:
    res_courbe = entrainer_avec_courbe(dict(CONFIG, seed=graine), heldout_texts)
    courbes.append(res_courbe)
    epoque_min, ppl_min = min(res_courbe["courbe"], key=lambda point: point[1])
    print(f"graine={graine:<3} ppl avant={res_courbe['ppl_avant']:.3f}  "
          f"meilleure epoque={epoque_min:>2} (ppl {ppl_min:.3f})  "
          f"ppl a la derniere epoque={res_courbe['courbe'][-1][1]:.3f}  "
          f"{res_courbe['duree_s']:.0f}s")

print()
print("=" * 78)
print("COURBE -- perplexite retenue par epoque (moyenne et ecart-type sur 3 graines)")
print("=" * 78)
print(f"{'epoque':>7} {'ppl (moy)':>12} {'ppl (ect)':>12}")
for i in range(CONFIG["num_train_epochs"]):
    valeurs = [r["courbe"][i][1] for r in courbes if len(r["courbe"]) > i]
    if not valeurs:
        continue
    moy = sum(valeurs) / len(valeurs)
    ect = (sum((v - moy) ** 2 for v in valeurs) / len(valeurs)) ** 0.5
    print(f"{i + 1:>7} {moy:>12.3f} {ect:>12.3f}")
[75/75 06:56, Epoch 15/15]
Step Training Loss
25 2.969499
50 2.250158
75 1.933804

graine=0   ppl avant=31.598  meilleure epoque= 2 (ppl 24.434)  ppl a la derniere epoque=28.119  422s
[75/75 07:00, Epoch 15/15]
Step Training Loss
25 2.995700
50 2.257334
75 1.946397

graine=7   ppl avant=31.598  meilleure epoque= 3 (ppl 24.459)  ppl a la derniere epoque=29.713  427s
[75/75 06:19, Epoch 15/15]
Step Training Loss
25 3.028861
50 2.253954
75 1.943491

graine=42  ppl avant=31.598  meilleure epoque= 3 (ppl 24.264)  ppl a la derniere epoque=29.137  384s

==============================================================================
COURBE -- perplexite retenue par epoque (moyenne et ecart-type sur 3 graines)
==============================================================================
 epoque    ppl (moy)    ppl (ect)
      1       27.111        0.426
      2       24.658        0.160
      3       24.447        0.144
      4       25.828        0.504
      5       26.560        0.224
      6       26.167        0.255
      7       26.392        0.404
      8       27.306        0.513
      9       27.919        0.509
     10       28.281        0.474
     11       28.457        0.588
     12       28.617        0.713
     13       28.821        0.809
     14       28.948        0.701
     15       28.990        0.659

Reading the result — the minimum sits at epochs 2-3, not 15

The averaged curve says the same thing as the three seeds taken one by one: the retained perplexity drops during the first two epochs (27.111 → 24.658), reaches its minimum at epoch 3 (24.447, standard deviation 0.144), then climbs back without return up to 28.990 at epoch 15. The last twelve epochs degrade the model on texts it has not seen — while the training loss, for its part, keeps falling: this is the very definition of over-training, and it costs here 4.5 points of retained perplexity, more than most of the hyperparameter gaps measured in this section.

And the best epoch moves from one seed to the next (2, 3, 3): even if the general regime is stable — early minimum, climb afterwards — a fixed budget of fifteen epochs cannot be optimal for every draw. The only rule that adapts to the draw is a stopping criterion: measure the retained perplexity at every epoch and stop when it no longer improves. This is exactly what exercise 2 builds.

Exercises to complete

Four unsolved exercises close the notebook. Each measures something the guided examples do not measure: the error committed on the weights themselves, generalization (as opposed to memorization), the NF4 vs FP4 choice, and the scale of the LoRA updates. The stubs run without error; complete them cell by cell.

Exercise 1: weight reconstruction error

Guided example 1 measured what quantization costs in VRAM and in perplexity – never what it does to the weights themselves. Here we open the hood: on a single nn.Linear layer of OPT-1.3B (model.decoder.layers[0].self_attn.q_proj), compare the FP16 weights to their reconstructed NF4 and INT8 versions, and locate where the error concentrates.

  1. Load OPT-1.3B in FP16 on CPU (device_map="cpu"), extract W_fp16 (2048 x 2048) from layer 0’s q_proj, then work only with that matrix.
  2. NF4 round trip: bitsandbytes.functional.quantize_4bit then dequantize_4bit (the API expects blocks of 64 contiguous values, the matrix must be reshaped to (n_blocks, 64) and sit on CUDA).
  3. Row-wise absmax INT8 round trip: each row divided by its absolute max, rounded over 127 levels, then multiplied back.
  4. For each format: relative Frobenius error ‖W_rec − W‖_F / ‖W‖_F and maximum absolute error.
  5. Locate the error: sort the weights by absolute magnitude and compute the share of the total error carried by the largest 1% of weights – the outliers that block quantization seeks to protect.

Hints: - The matrix alone is 2048 x 2048: keep it on CPU and move onto CUDA only what bnb.functional requires. - Also compare the shape of the two errors: NF4 is tailored to a Gaussian weight distribution, row-wise absmax INT8 to a uniform distribution.

Success criterion: a table format | relative Frobenius error | max absolute error | share of the error in the largest 1% of weights, with relative errors on the order of 10⁻² to 10⁻¹.

# Exercice 1 : erreur de reconstruction des poids (NF4 / INT8 contre FP16)
# Etape 1 : charger OPT-1.3B sur CPU, extraire W_fp16 de q_proj (couche 0).
# Etape 2 : round trip NF4 (quantize_4bit/dequantize_4bit, blocs de 64) et INT8 absmax par ligne.
# Etape 3 : erreur relative de Frobenius + erreur absolue maximale pour chaque format.
# Etape 4 : part de l'erreur totale portee par le 1 % des poids de plus grande magnitude.
# Indice : bnb.functional travaille sur CUDA ; ne mover que la matrice 2048 x 2048.

W_fp16 = None      # TODO etudiant
W_rec_nf4 = None   # TODO etudiant
W_rec_int8 = None  # TODO etudiant

print("Exercice a completer : erreur de reconstruction des poids NF4/INT8 vs FP16")
Exercice a completer : erreur de reconstruction des poids NF4/INT8 vs FP16

Exercise 2: early stopping on the retained perplexity

The curve of the previous section shows where the retained perplexity stops falling, but it does not say what to do with it: the notebook still trains a fixed fifteen epochs and keeps the adapter from the last one, whatever the path. A real training does not pay for measuring a retained corpus at every epoch without taking advantage of it.

Early stopping is the rule that exploits this curve: keep the adapter from the best epoch, and stop as soon as the retained perplexity has not improved for patience epochs.

  1. Write entrainer_avec_arret_precoce(config, patience), modeled on entrainer_avec_courbe, which:
    • measures the retained perplexity at each epoch end (same SondeRetenue probe);
    • keeps a copy of the adapter’s state at each new best epoch;
    • interrupts training (control.should_training_stop = True) as soon as patience epochs have passed without improvement.
  2. Replay over the three seeds 0, 7 and 42, with patience = 3.
  3. Report a table: seed | best epoch | retained ppl at stop | retained ppl at epoch 15 | epochs saved.
  4. Conclude: is the best epoch the same for the three seeds? If yes, the fixed budget of fifteen epochs is a bad setting; if no, early stopping is the only rule that adapts to the draw.

Hints:

  • The probe sees the same model object as the training: {k: v.detach().clone() for k, v in modele.named_parameters() if v.requires_grad} captures the adapter alone, without the frozen quantized weights – this is what keeps the copy cheap.
  • control.should_training_stop = True in on_epoch_end stops the loop cleanly; state.global_step stays consistent with the epochs actually performed.
  • Compare at work done, not only at perplexity: epoch 15 costs fifteen epochs, early stopping costs best epoch + patience. A perplexity gain obtained in half the epochs is a real gain; a null gain paid at the same price is not.

Success criterion: the table of the three seeds with the best epoch, the retained perplexity at the stop and that of epoch 15, and one sentence saying whether the gain exceeds the dispersion across seeds.

# Exercice 2 : arret precoce sur la perplexite retenue
# Etape 1 : ecrire entrainer_avec_arret_precoce(config, patience) sur le modele
#           de `entrainer_avec_courbe` : sonde a chaque epoque, copie des
#           parametres entrainables a chaque nouvelle meilleure epoque, et
#           interruption (control.should_training_stop = True) apres `patience`
#           epoques sans amelioration.
# Etape 2 : rejouer sur les graines 0, 7 et 42 avec patience = 3.
# Etape 3 : comparer la perplexite retenue a l'arret, celle de l'epoque 15,
#           et le nombre d'epoques reellement effectuees.
# Indice : seuls les parametres entrainables portent l'adaptateur (requires_grad),
#          et l'arret precoce coute `meilleure epoque + patience` epoques.

resultats_arret_precoce = None  # TODO etudiant

print("Exercice a completer : a quelle epoque arreter sur chaque graine, "
      "et que coute l'arret precoce face aux quinze epoques fixes ?")
Exercice a completer : a quelle epoque arreter sur chaque graine, et que coute l'arret precoce face aux quinze epoques fixes ?

Exercise 3: NF4 vs FP4 at equal memory

NF4 and FP4 occupy exactly the same space (4 bits per weight): the difference is purely in the shape of the quantization levels. Compare the two at equal memory on OPT-1.3B.

  1. Load OPT-1.3B twice in 4-bit: bnb_4bit_quant_type="nf4" then "fp4" – double quantization stays identical in both configurations.
  2. Measure the footprint (get_memory_footprint) and the loading peak for each format: they must be nearly identical.
  3. Measure the perplexity over the training texts for both formats.
  4. Generate greedily on the same prompt and compare the outputs.

Hints: - A transformer’s pre-trained weights follow a roughly normal distribution, centered and concentrated near zero: NF4 places its levels on the quantiles of that distribution (more levels at the center). FP4 is not a uniform grid: it is a floating E2M1 format (1 sign bit, 2 exponent bits, 1 mantissa bit) whose normalized positive levels, as implemented in bitsandbytes (functional.py, SHA 833649043474794b8fe7a4136e0c40faf077b2e0), are 0, 0.0052, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1 – the gaps are not constant (denser at the center than at the extremes, but less extreme than NF4). NF4 therefore should win in perplexity at equal memory on Gaussian weights, but that is a prediction, not a guaranteed result. - Reuse the skeleton of guided example 3 changing ONLY bnb_4bit_quant_type.

Success criterion: footprints equal to within ~1 MB, the two generations side by side, and a table ppl(NF4) vs ppl(FP4). Either direction of the inequality (NF4 < FP4, NF4 ≈ FP4, NF4 > FP4) is acceptable if the protocol and the measurements support it – the ranking is an experimental result, not an expectation.

# Exercice 3 : NF4 contre FP4 à mémoire égale
# Etape 1 : charger OPT-1.3B en 4-bit avec bnb_4bit_quant_type="nf4" puis "fp4"
#           (bnb_4bit_use_double_quant identique dans les deux).
# Etape 2 : empreinte (get_memory_footprint) et pic de chargement pour chaque format.
# Etape 3 : perplexite sur les textes d'entrainement + generation greedy sur un meme prompt.
# Indice : ne changer QUE bnb_4bit_quant_type entre les deux configurations.

resultats_exo3 = None  # TODO etudiant

print("Exercice a completer : NF4 vs FP4 a memoire egale")
Exercice a completer : NF4 vs FP4 a memoire egale

Exercise 4: alpha/r vs alpha/sqrt(r) scaling (rsLoRA)

The section 4 LoRALinear scales the update by alpha / r. rsLoRA proposes alpha / sqrt(r): at high rank, the update does not collapse. Test it on the section 4 toy regression – CPU, fast, no heavy model.

  1. Reuse the section 4 LoRALinear class (local copy with a scale parameter), on the same regression task: same base layer, same data, fixed seeds.
  2. With alpha fixed (e.g. 16), train r = 4, 16, 64 for the same number of SGD steps (e.g. 300), same learning rate, for both scales: alpha/r and alpha/sqrt(r).
  3. Report the final loss of the 6 configurations in a table.

Hints: - At fixed alpha, the alpha/r scale decays like 1/r: doubling the rank halves the update; alpha/sqrt(r) only divides it by √2. This is the hypothesis to confront with the measurement. - Fix all the seeds (torch.manual_seed) so that the only difference between two runs is the scale.

Success criterion: at r = 64, a clearly lower final loss with alpha/sqrt(r) than with alpha/r, and losses close between the two scales at r = 4.

# Exercice 4 : échelle alpha/r contre alpha/sqrt(r) (rsLoRA) sur la régression de la section 4
# Etape 1 : reprendre LoRALinear avec un parametre d'echelle, alpha fixe (ex. 16), CPU.
# Etape 2 : entrainer r = 4, 16, 64 sur le meme nombre de pas SGD pour les deux echelles.
# Etape 3 : tableau des pertes finales des 6 configurations.
# Indice : graines fixees, seule l'echelle doit differer entre deux runs.

resultats_exo4 = None  # TODO etudiant

print("Exercice a completer : alpha/r vs alpha/sqrt(r) a r = 4, 16, 64")
Exercice a completer : alpha/r vs alpha/sqrt(r) a r = 4, 16, 64

Summary

Aspect LoRA (FT-01) QLoRA (FT-02)
Model weights FP16 (16 bits) NF4 (4 bits)
Adapters LoRA in FP16 LoRA in FP16
Forward computations Native FP16 Dequantize → FP16 → re-quantize
Memory savings ~1.1x base model ~4x on weights alone (0.41 vs 1.63 GB)
Quality ~98-99% of full FT ~97-99% of full FT (order of magnitude)
Recommended model < 1B params > 1B params

Key points: - QLoRA = Quantization (NF4) + LoRA: the best of both worlds - NF4 is optimal for weights (normal distribution), not a simple INT4 - Double quantization compresses scaling factors for additional gains - paged_adamw_8bit: 8-bit optimizer to save even more VRAM - A 7B model in QLoRA fits on a 6 GB GPU — democratizes fine-tuning

Reference: Dettmers et al., “QLoRA: Efficient Finetuning of Quantized LLMs” (2023).

Next steps (FT-03): Multi-task fine-tuning with several LoRA adapters.

The measured journey reads in the outputs: the NF4 loading, the exact number of trainable parameters, the duration, the VRAM peak and the final loss are produced by the preceding cells. The section 4 grid predicts the adapter count to the exact parameter; the section 7 generations then show memo-styling at work. The extended sweep of section 10 adds 30 trainings over three seeds: rank and the alpha/r ratio move the retained perplexity by several points, the target modules do not move it enough to stand out from the noise, and the per-epoch curve places the minimum at epochs 2-3. The FT-01 → FT-02 loop is closed: same LoRA mechanics, only the memory residency of the weights changes. FT-03 opens multi-task: several adapters, one base model, and the question of rank sharing.

The two table rows that are not measurements: the “Quality” row and the “~3-4x” figure of the memory savings are orders of magnitude (theoretical weight ratios and the QLoRA paper), not outputs of this notebook. What the run measures: the residual footprint of the 4-bit model after loading (2.72 GB) against its weights-only theory (0.41 GB), the loading peak of the same model (8.06 GB, above FP16 at 7.39 GB – the conversion transient dominates this peak), the QLoRA training peak of the nominal configuration (2.13 GB), and the perplexity on the retained corpus (29.440 after adapter vs 31.594 for the NF4 base alone). It is on these numbers – and not on the orders of magnitude of the table – that the reading of this notebook rests.

Verifying the “a 7B fits on 6 GB” claim: 4-bit weights = 0.5 byte per parameter, i.e. 3.5 GB for 7B, against 14 GB in FP16. The LoRA adapters and the paged optimizer apply to a small fraction of the parameters. The margin then depends on context length, batch size and activations: this is why the notebook measures the real peak instead of settling for weight arithmetic.

Retour au sommet