Objective: understand LoRA by building it, without peft. By the end of this notebook you will be able to write a pure-PyTorch LoRALinear, prove that the canonical initialization leaves the model unchanged, train it on a real mini-task, and explain why merging the adapter is not bit-exact.
Prerequisites: PyTorch basics (tensors, autograd, nn.Linear) and fine-tuning fundamentals — see FT-01.
Duration: ~30 min · Level: intermediate · Hardware: CPU is enough (the displayed timings are measured on GPU, a few seconds per epoch).
Position in the series: FT-01 to FT-06 use peft and ready-to-use HuggingFace models. This notebook takes the mechanism apart — the W' = W + (alpha/r) * B @ A decomposition, the A ~ N, B = 0 initialization, gradient propagation, merging — so that the SOTA notebooks stop being black boxes. The following notebooks remain the reference for industrial use: FT-01 (LoRA with peft on GPT-2), FT-02 (4-bit QLoRA), FT-06 (vision-language).
Checking the environment
Before any computation, we check the effective engine: PyTorch version, GPU availability, and a fixed seed so that the measurements are reproducible.
import copyimport timeimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom torchvision import datasets, transformsSEED =42torch.manual_seed(SEED)np.random.seed(SEED)DEV ="cuda"if torch.cuda.is_available() else"cpu"print(f"PyTorch {torch.__version__}")print(f"numpy {np.__version__}")print(f"device {DEV}"+ (f" ({torch.cuda.get_device_name(0)})"if DEV =="cuda"else""))print(f"graine {SEED}")
The mini-task of this notebook (section 3) runs on CPU as well as on GPU; only the duration changes (a few seconds per epoch on an RTX 3090, noticeably more on CPU). All the following cells run as-is on both — the measured values (accuracies, norms, merge drift) are the ones produced by the run, not constants copied over.
1. The problem: W' = W + delta_W costs |delta_W| parameters
Full fine-tuning learns a complete delta: for a d -> k layer, you must store and update d x k parameters — plus the optimizer states (Adam carries two copies: moment and variance). On GPT-2 (124M parameters), that is the full price, even when the target task only moves the model within a tiny subspace.
LoRA’s hypothesis (Hu et al., 2021) is that this delta has an intrinsically low rank:
\[W' = W + \frac{\alpha}{r} \cdot B A, \qquad A \in \mathbb{R}^{r \times d},\ B \in \mathbb{R}^{k \times r},\ r \ll \min(d, k)\]
The budget drops from d x k to r (d + k). On this notebook’s toy layer (512 -> 10, r = 4):
full
LoRA r=4
delta parameters
512 x 10 = 5,120
4 x (512 + 10) = 2,088
delta share
100%
40.8%
Two design choices make this decomposition trainable from the base model, without disturbing it:
B = 0 at initialization: the delta is exactly zero, so W' = W at step 0 — the adapted model starts identical to the base model, whatever A is.
W is frozen (requires_grad = False): only A and B receive gradients. The graph of the frozen weights can be discarded, and a trained adapter stores in r (d + k) values instead of d x k.
The alpha / r factor (the scaling) decouples the effective magnitude from the rank: you can change r without changing the scale of the learned signal.
LoRALinear: the decomposition in pure PyTorch
No peft import below — the class fits in about twenty lines, and each of its details is one of the three invariants from section 1.
class LoRALinear(nn.Module):"""y = x @ W.T + (alpha / r) * (x @ A.T) @ B.T -- W gele, seuls A et B vivent. Initialisation canonique (Hu et al. 2021) : A ~ N(0, 1/in_features) -- random, direction disponible B = 0 -- donc le delta vaut exactement 0 au pas 0 """def__init__(self, base: nn.Linear, r: int, alpha: float):super().__init__()assert r >0, "le rang doit etre strictement positif"self.base = basefor p inself.base.parameters(): p.requires_grad_(False) # invariant 2 : W geleself.r, self.alpha = r, alphaself.scaling = alpha / r dev, dt = base.weight.device, base.weight.dtypeself.A = nn.Parameter( torch.randn(r, base.in_features, device=dev, dtype=dt)* (1.0/ base.in_features **0.5) )self.B = nn.Parameter( torch.zeros(base.out_features, r, device=dev, dtype=dt) ) # invariant 1 : B = 0def forward(self, x):# Deux matmuls de rang r plutot qu'un matmul dense : c'est le coeur# de l'economie -- et l'ordre (x @ A.T) @ B.T, pas x @ (A.T @ B.T),# car cette derniere aurait le cout du full a chaque appel.returnself.base(x) +self.scaling * ((x @self.A.T) @self.B.T)@torch.no_grad()def merged_weight(self):"""W + (alpha/r) * B @ A : ce que l'adaptateur devient apres fusion."""returnself.base.weight +self.scaling * (self.B @self.A)lora_head = LoRALinear(nn.Linear(512, 10), r=4, alpha=8)print(lora_head)
requires_grad_(False) on the base parameters: the gradient never reaches W. This is not a naming convention, it is the autograd graph being cut.
B is born zero: whatever the value drawn for A, the product B @ A is zero — the adapted model starts exactly where the base model stands.
(x @ A.T) @ B.T and not x @ (A.T @ B.T).T: we multiply left first, then right, passing through the rank-r space. Doing the merge before the forward would cost d x k per call — exactly what LoRA avoids.
One implementation detail worth knowing: here alpha = 8 and r = 4, so scaling = 2.0. The paper’s convention is alpha fixed once (often 8 or 16) and r varied — the scaling then compensates the rank so that changing r does not change the scale of the learned signal.
2. The invariants, checked on real tensors
Claiming “the delta is zero at the start” and “W receives no gradient” is one thing; checking it on the actual autograd graph is another. The three controls below are the ones you would write in a unit test of the module.
d, k, r =512, 10, 4base = nn.Linear(d, k)layer = LoRALinear(base, r=r, alpha=8)x = torch.randn(64, d)# -- invariant 1 : B = 0 => LoRA(x) == base(x) exactement ---------------with torch.no_grad(): ecart_init = (layer(x) - base(x)).abs().max().item()# -- invariant 2 : W gele => aucun gradient n'atteint base ---------------loss = layer(x).pow(2).mean()loss.backward()w_grad = base.weight.grad# -- budget : forme fermee r * (d + k) -------------------------------------n_train =sum(p.numel() for p in layer.parameters() if p.requires_grad)n_total =sum(p.numel() for p in layer.parameters())fermee = r * (d + k)print(f"ecart initial max|LoRA(x) - W(x)| = {ecart_init:.3e}"f" {'(exactement 0)'if ecart_init ==0.0else'(NON NUL -- init non canonique)'}")print(f"gradient sur W {w_grad if w_grad isnotNoneelse'None'}"f" {'(correct : coupe)'if w_grad isNoneelse'(FUITE)'}")print(f"gradient sur A / B : {layer.A.grad isnotNone} / {layer.B.grad isnotNone}")print(f"parametres entrainables : {n_train} = r*(d+k) = {fermee}"f" {'(verifie)'if n_train == fermee else'(ECART)'}")print(f"sur {n_total} parametres totaux : {n_train / n_total:.2%}")
ecart initial max|LoRA(x) - W(x)| = 0.000e+00 (exactement 0)
gradient sur W None (correct : coupe)
gradient sur A / B : True / True
parametres entrainables : 2088 = r*(d+k) = 2088 (verifie)
sur 7218 parametres totaux : 28.93%
Reading the result: the initial identity is exact
Three readings, in order of importance:
max|LoRA(x) - W(x)| = 0.000e+00 — not “close to zero”, not “on the order of machine epsilon”: exactly zero. This is an algebraic identity (0 @ A = 0), not a numerical approximation. Any implementation that displays something else here has a non-canonical initialization — this is the test to write first.
base.weight.grad is None: autograd did not even allocate a gradient for W. Freezing is not a matter of speed, it is a cut in the graph.
2,088 = 4 x (512 + 10): the parameter count checked against the closed form. This is the figure that replaces the “~0.5% of parameters” claims from papers — here on a toy layer where the ratio is not spectacular; it becomes one when d and k are 4096 (r=4: 0.2% of the delta).
3. Mini-task: adapting a frozen classifier to the “photo negative”
For the demonstration to have a stake, you need a base model competent on its training domain and incompetent on the target domain. Fashion-MNIST lends itself to this with a one-line shift: pixel inversion (x -> 1 - x), the photographic negative.
The protocol:
train a small CNN (3 conv blocks + a linear head, ~29k parameters) on the inverted images;
measure its accuracy on the inverted test set (its domain) and on the normal test set (the target);
freeze the whole network, then adapt it to the normal domain twice: once with LoRA r = 4 on two layers, once with full fine-tuning of the same two layers — same epochs, same optimizer, same learning rate.
A multiplicative luminance shift (x * 0.4) would not do: a conv + ReLU + max-pool stack without normalization is positively homogeneous, it absorbs the rescaling and the measured gap stays on the order of a point. Inversion, on the other hand, genuinely moves the distribution.
import osDATA_DIR = os.path.join(os.path.expanduser("~"), ".cache", "ft00a") # telecharge une foistf = transforms.ToTensor()train_set = datasets.FashionMNIST(DATA_DIR, train=True, download=True, transform=tf)test_set = datasets.FashionMNIST(DATA_DIR, train=False, download=True, transform=tf)train_loader = torch.utils.data.DataLoader(train_set, batch_size=256, shuffle=True)test_loader = torch.utils.data.DataLoader(test_set, batch_size=512, shuffle=False)print(f"Fashion-MNIST : {len(train_set)} images d'entrainement / {len(test_set)} de test")def inverse(x):# Le decalage de domaine : negatif photo.return1.0- xclass SmallCNN(nn.Module):# 3 blocs conv+pool puis une tete lineaire. ~29 k parametres.def__init__(self):super().__init__()self.c1 = nn.Conv2d(1, 16, 3, padding=1)self.c2 = nn.Conv2d(16, 32, 3, padding=1)self.c3 = nn.Conv2d(32, 64, 3, padding=1)self.fc = nn.Linear(64*3*3, 10)def forward(self, x): x = F.max_pool2d(F.relu(self.c1(x)), 2) # 28 -> 14 x = F.max_pool2d(F.relu(self.c2(x)), 2) # 14 -> 7 x = F.max_pool2d(F.relu(self.c3(x)), 2) # 7 -> 3returnself.fc(x.flatten(1))def n_params(m):returnsum(p.numel() for p in m.parameters())def evaluate(model, inverse_domain, loader): model.eval() good = tot =0with torch.no_grad():for x, y in loader:if inverse_domain: x = inverse(x) pred = model(x.to(DEV)).argmax(1).cpu() good += (pred == y).sum().item() tot += y.numel()return good / totdef train(model, inverse_domain, epochs=2, lr=1e-3): opt = torch.optim.Adam( [p for p in model.parameters() if p.requires_grad], lr=lr) model.train()for ep inrange(epochs): t0 = time.perf_counter()for x, y in train_loader:if inverse_domain: x = inverse(x) loss = F.cross_entropy(model(x.to(DEV)), y.to(DEV)) opt.zero_grad() loss.backward() opt.step()print(f" epoch {ep +1}/{epochs} loss={loss.item():.4f}"f" ({time.perf_counter() - t0:.1f}s)")print(f"modele de base : {n_params(SmallCNN())} parametres")
Fashion-MNIST : 60000 images d'entrainement / 10000 de test
modele de base : 29066 parametres
epoch 1/2 loss=0.5497 (3.7s)
epoch 2/2 loss=0.3756 (3.1s)
test INVERSE (son domaine) : 0.8325
test NORMAL (la cible) : 0.0363
Reading the result: competent on its domain, mute on the target
The base model reaches ~0.83 on the inverted test set — it did learn the task. On the normal test set it collapses to ~0.04, below chance (1/10 = 0.10): it is not merely ignorant, it answers systematically off-target. This is exactly the situation where adaptation makes sense: the low-level features (contours, textures) remain useful, but they are being read “backwards”.
This is also the regime of real use cases: a pre-trained model competent somewhere, and a target that shifts it. We do not start from scratch — we adapt.
4. Two adaptations of the same frozen network: LoRA r = 4 vs full
We freeze a copy of the base model, then build two adaptations:
LoRA: two adapters — the last convolutional block and the linear head, each at rank 4. The rest of the network (the first two blocks) stays frozen.
full: the same two layers, fully unfrozen.
Same number of epochs, same optimizer, same learning rate. The only difference is the number of trainable parameters — that is the variable whose effect we measure.
For the convolutional layer, the decomposition has one subtlety compared to the linear case: A is an in -> r convolution (k x k kernel) and B a 1 x 1 convolution r -> out. The budget becomes r * (in * k² + out), not r * (in + out) — the 3 x 3 kernel weighs nine times as much.
class LoRAConv2d(nn.Module):"""y = conv(x, W) + (alpha/r) * conv_1x1(conv_3x3(x, A), B) -- W gele."""def__init__(self, base: nn.Conv2d, r: int, alpha: float):super().__init__()self.base = basefor p inself.base.parameters(): p.requires_grad_(False)self.r, self.alpha = r, alphaself.scaling = alpha / rself.A = nn.Conv2d(base.in_channels, r, base.kernel_size, stride=base.stride, padding=base.padding, bias=False, device=base.weight.device, dtype=base.weight.dtype)self.B = nn.Conv2d(r, base.out_channels, 1, bias=False, device=base.weight.device, dtype=base.weight.dtype) nn.init.kaiming_uniform_(self.A.weight, a=5**0.5) nn.init.zeros_(self.B.weight) # meme invariant : delta nul au pas 0def forward(self, x):returnself.base(x) +self.scaling *self.B(self.A(x))def trainable(m):returnsum(p.numel() for p in m.parameters() if p.requires_grad)# -- reseau gele -----------------------------------------------------------------frozen = copy.deepcopy(base_model)for p in frozen.parameters(): p.requires_grad_(False)# -- adaptation LoRA : deux adaptateurs de rang 4 ----------------------------------lora_model = copy.deepcopy(frozen)lora_model.c3 = LoRAConv2d(lora_model.c3, r=4, alpha=8).to(DEV)lora_model.fc = LoRALinear(lora_model.fc, r=4, alpha=8).to(DEV)n_lora = trainable(lora_model)t_lora = n_params(lora_model)conv3_A =4* (32*3*3) # r * (in * k^2)conv3_B =64*4*1*1# out * rfc_budget =4* (576+10) # r * (in + out)print(f"LoRA parametres entrainables : {n_lora} / {t_lora} ({n_lora / t_lora:.2%})")print(f" dont conv3 (r=4) : {conv3_A + conv3_B}"f" = r*(in*k^2) + out*r = {conv3_A} + {conv3_B}")print(f" dont fc (r=4) : {fc_budget} = r*(in+out)")# -- adaptation full : les memes deux couches, degelrees ---------------------------full_model = copy.deepcopy(frozen)for m_ in (full_model.c3, full_model.fc):for p in m_.parameters(): p.requires_grad_(True)n_full = trainable(full_model)print(f"full parametres entrainables : {n_full} / {n_params(full_model)}"f" ({n_full / n_params(full_model):.2%})")
LoRA parametres entrainables : 3752 / 32818 (11.43%)
dont conv3 (r=4) : 1408 = r*(in*k^2) + out*r = 1152 + 256
dont fc (r=4) : 2344 = r*(in+out)
full parametres entrainables : 24266 / 29066 (83.49%)
print("[LoRA] adaptation au domaine normal, 2 epochs")torch.manual_seed(SEED)train(lora_model, inverse_domain=False)acc_lora = evaluate(lora_model, inverse_domain=False, loader=test_loader)print("\n[full] adaptation au domaine normal, 2 epochs")torch.manual_seed(SEED)train(full_model, inverse_domain=False)acc_full = evaluate(full_model, inverse_domain=False, loader=test_loader)print()print("="*74)print(f"{'configuration':<28}{'exactitude':>12}{'params entr.':>14}{'part':>9}")print("-"*74)print(f"{'base, test inverse':<28}{acc_base_inv:>12.4f}{'(gele)':>14}{'':>9}")print(f"{'base, test normal':<28}{acc_base_norm:>12.4f}{'(gele)':>14}{'':>9}")print(f"{'LoRA r=4 (2 couches)':<28}{acc_lora:>12.4f}{n_lora:>14}{n_lora / t_lora:>9.2%}")print(f"{'full (memes 2 couches)':<28}{acc_full:>12.4f}{n_full:>14}"f"{n_full / n_params(full_model):>9.2%}")print("="*74)
[LoRA] adaptation au domaine normal, 2 epochs
epoch 1/2 loss=1.0449 (3.9s)
epoch 2/2 loss=0.5406 (4.0s)
[full] adaptation au domaine normal, 2 epochs
epoch 1/2 loss=0.5569 (3.8s)
epoch 2/2 loss=0.3553 (3.8s)
==========================================================================
configuration exactitude params entr. part
--------------------------------------------------------------------------
base, test inverse 0.8325 (gele)
base, test normal 0.0363 (gele)
LoRA r=4 (2 couches) 0.7351 3752 11.43%
full (memes 2 couches) 0.8242 24266 83.49%
==========================================================================
Reading the result: what 3,752 parameters recover
To read from the table above, in this order:
The frozen network recovers nothing on its own — the “base, normal test” row is the starting point of the adaptation, not an optimistic floor.
LoRA recovers most of the gap: from ~0.04 to ~0.74, with 3,752 trainable parameters out of 32,818 (11.4%). The delta learned by two rank-4 adapters restores the majority of what the same unfrozen layers recover in full.
Full fine-tuning does better (~0.82), and this must be said: a rank 4 is a 4-dimensional subspace per layer — it captures the dominant shift, not all of it. The trade-off is the budget: 24,266 trained parameters, that is 6.5x more, plus the Adam states that go with them (two copies per parameter), whereas the adapter stores and shares in 3,752 values.
On this 29k-parameter toy, two layers already represent 83% of the model — the “11% of the parameters” ratio is therefore nothing spectacular here. LoRA’s argument plays out at the scale of real matrices: on a 4096 x 4096 layer, rank 4 costs 0.2% of the delta; on full GPT-2, the ratios measured in FT-01 fall below one percent. The mechanism is exactly the one you have just written by hand; only the size of the matrices changes.
5. Merging: W + (alpha/r) * B @ A, and why it is not bit-exact
After training, the adapter can be merged: W is replaced by W + (alpha/r) * B @ A and A and B are discarded. The model becomes an ordinary nn.Linear again — zero serving cost, zero inference-time dependency.
Intuition says “same model”. Floating-point arithmetic says no. Compare the two paths on the same input:
unmerged: x @ W.T + scaling * ((x @ A.T) @ B.T)
merged: x @ (W + scaling * (B @ A)).T
Same mathematics, different association order — and in IEEE 754, floating-point addition is not associative. Merging is a rewriting of the computation, not an identity.
# L'adaptateur entraine de la tete lineairelora_fc = lora_model.fc# Reconstruction de la couche fusionnee : poids merges, meme biaismerged_fc = nn.Linear(lora_fc.base.in_features, lora_fc.base.out_features).to(DEV)with torch.no_grad(): merged_fc.weight.copy_(lora_fc.merged_weight()) merged_fc.bias.copy_(lora_fc.base.bias)x_probe = torch.randn(128, lora_fc.base.in_features, device=DEV)with torch.no_grad(): drift32 = (merged_fc(x_probe) - lora_fc(x_probe)).abs().max().item()# Controle : la meme comparaison en float64, ou l'epsilon est 2^29 fois plus petitin_f, out_f = lora_fc.base.in_features, lora_fc.base.out_featureslora64 = LoRALinear(nn.Linear(in_f, out_f), r=4, alpha=8).double()with torch.no_grad(): lora64.base.weight.copy_(lora_fc.base.weight.detach().cpu()) lora64.base.bias.copy_(lora_fc.base.bias.detach().cpu()) lora64.A.copy_(lora_fc.A.detach().cpu()) lora64.B.copy_(lora_fc.B.detach().cpu())x64 = torch.randn(128, in_f, dtype=torch.float64)y_adapter64 = lora64(x64)y_merged64 = x64 @ lora64.merged_weight().T + lora64.base.biasdrift64 = (y_merged64 - y_adapter64).abs().max().item()delta_norm = (lora_fc.scaling * (lora_fc.B @ lora_fc.A)).norm().item()w_norm = lora_fc.base.weight.norm().item()print(f"derive max float32 |merged(x) - LoRA(x)| = {drift32:.3e}")print(f"controle float64 (epsilon ~2e-16) = {drift64:.3e}")print(f"||delta W|| = {delta_norm:.4f} vs ||W|| = {w_norm:.4f}"f" (le delta vaut {delta_norm / w_norm:.0%} du poids)")
derive max float32 |merged(x) - LoRA(x)| = 1.907e-06
controle float64 (epsilon ~2e-16) = 3.109e-15
||delta W|| = 1.5101 vs ||W|| = 3.2893 (le delta vaut 46% du poids)
Reading the result: merging is a rewriting, not an identity
float32: the drift is on the order of 1e-6 — tiny, but non-zero, and it is not a bug: it is the price of re-associating the operations. At the scale of the float32 epsilon (1.2e-7), a drift of 1e-6 on a 576-dimensional vector is exactly what associational rounding produces.
The float64 control confirms the diagnosis: the same comparison in double precision drops by nearly nine orders of magnitude. If the drift came from an implementation error, it would not move with precision.
The learned delta is not small: ||delta W|| is a substantial fraction of ||W|| (typically half of it here). This is not a cosmetic adjustment — the adapter durably moved the layer, and the merge preserves that.
Practical consequence: if a pipeline compares a model bit-for-bit before and after merging, it will find a difference — and it will be right. The correct guarantee is “equivalent up to the precision’s epsilon”, not “identical”. It is the same family of distinction as for any numerical rewriting: equivalent and identical are two different claims, and only the latter is proven bit-for-bit.
Preparing the exercises
The three exercises are progressive: the first varies the rank and measures the budget, the second decouples alpha from the rank, the third has you re-write the merge and its verification. Each cell runs as-is (the stubs do not raise an error); your job is to replace the TODOs.
# Exercice 1 : le rang et le budget# TODO etudiant : completez budget(r) pour qu'elle retourne le nombre de# parametres entrainables d'un LoRALinear(512 -> 10, rang r), puis verifiez# que la part du delta (budget / 5120) decroit comme attendu pour# r dans [1, 2, 4, 8, 16, 64]. Enfin, pour r = 64 : que vaut le budget# compare au full (5120) ? Que se passe-t-il quand r >= min(512, 10) ?def budget(r, d=512, k=10):# Indice : forme fermee de la section 2. result =None# TODO etudiantreturn resultprint("Exercice 1 a completer -- budget(r) retourne", budget(4))
Exercice 1 a completer -- budget(r) retourne None
Exercise 2: decoupling alpha from the rank
The class ties the two through scaling = alpha / r. Two configurations (r=4, alpha=4) and (r=4, alpha=16) have the same rank but scalings of 1 and 4: the second allows a delta four times as large, at the cost of steeper dynamics (a risk of instability if the learning rate is not reduced).
# Exercice 2 : alpha vs r# TODO etudiant : entrainez deux LoRALinear (r=4, alpha=4) et (r=4, alpha=16)# sur la meme mini-tache de regression (par ex. ajuster y = sinus bruite),# avec le MEME optimizer et le MEME learning rate (1e-2), 200 pas chacun.# Mesurez ||delta W|| final pour chacun, et la perte finale. Constatez :# - le scaling multiplie l'ampleur du delta ;# - a learning rate egal, alpha=16 descend... ou diverge. Lequel ?def compare_alpha(d=64, k=8, steps=200):# Indice : reutilisez la boucle de la section 2 (loss.backward + Adam),# sur deux modeles separes, graine identique avant chaque tirage. result =None# TODO etudiantreturn resultprint("Exercice 2 a completer -- compare_alpha() retourne", compare_alpha())
Exercice 2 a completer -- compare_alpha() retourne None
Exercise 3: re-writing the merge and bounding its drift
merged_weight() already exists; write its counter-check: rebuild the merged layer, compare it to the adapted layer on a batch of inputs, and bound the drift as a function of the precision.
# Exercice 3 : fusion et borne de derive# TODO etudiant : ecrivez derive_fusion(layer, n_echantillons=256) qui# retourne l'ecart max |merged(x) - LoRA(x)| pour des x aleatoires.# Testez-la en float32 puis en float64 (layer.double()) et verifiez que la# derive suit l'epsilon de la precision -- c'est le controle de la section 5.def derive_fusion(layer, n_echantillons=256):# Indice : nn.Linear(in, out).weight.copy_(...) pour la couche fusionnee ;# n'oubliez pas le biais ; restez sous torch.no_grad(). result =None# TODO etudiantreturn resultprint("Exercice 3 a completer -- derive_fusion() retourne", derive_fusion(lora_model.fc))
Exercice 3 a completer -- derive_fusion() retourne None
Summary
notion
what to remember
the decomposition
W' = W + (alpha/r) * B @ A, budget r (d + k) instead of d x k (conv: r (in k² + out))
the initialization
A ~ N, B = 0 ⇒ W' = Wexactly at step 0 — checkable in one test
the freeze
requires_grad_(False) cuts the graph: W does not even receive an allocated gradient
the training
only A, B move; the adapter stores in r (d + k) values
the measurement
rank 4 on 2 layers: ~11% of the parameters, most of the accuracy recovered — full does better, at 6.5x the budget
the merge
equivalent up to epsilon, never bit-exact: re-association is not identity
Next step: the same mechanism at industrial scale — FT-01 (LoRA peft on GPT-2), FT-02 (QLoRA: 4-bit base + adapters), FT-06 (vision-language). You will recognize in them every piece you have just written by hand.