FT-00c: LoRA SOTA — the same adaptation, this time with peft

Lancer : Codespaces Colab

Navigation: Index | 00b — Hyperparams | 00d — QLoRA SOTA

French version: FT-00c — LoRA SOTA

Objective: redo, with peft.LoraConfig + peft.get_peft_model, exactly the LoRA adaptation built by hand in FT-00a — same task, same split, same seed, same hyperparameters — then measure what the ecosystem brings: trained parameters, accuracy, lines of code, fine-tuning time, adapter save/merge.

Prerequisites: FT-00a (the W' = W + (alpha/r) * B @ A decomposition, the initialization invariants, the merge) — this notebook is its industrial counterpart.

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

Position in the series: FT-00a dissects the mechanism; this notebook plugs the same mini-task into peft, the SOTA implementation maintained by HuggingFace, and completes the LLM coverage of 21_LoRA_FineTuning with a measured from-scratch vs library comparison on a controlled task. What follows remains FT-02 (4-bit QLoRA) and FT-06 (vision-language).

Checking the environment

Before any computation, we check the effective engine: PyTorch version, peft version, available device. The mini-task (section 1) runs on CPU in a few tens of seconds per epoch — no GPU resource is required.

import copy
import os
import tempfile
import time

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from peft import LoraConfig, PeftModel, get_peft_model
from torchvision import datasets, transforms

SEED = 42
torch.manual_seed(SEED)
np.random.seed(SEED)
DEV = "cuda" if torch.cuda.is_available() else "cpu"

import peft
print(f"PyTorch {torch.__version__}")
print(f"peft     {peft.__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}")
PyTorch 2.13.0+cpu
peft     0.21.2
numpy    2.2.6
device   cpu
graine   42

Reading the result: the execution environment

The comparison with FT-00a keeps its meaning because the protocol is reproduced identically (dataset, split, model, optimizer, seed): the accuracy comparison is valid. The execution environments differ — the committed FT-00a ran on GPU (torch 2.8.0+cu126, RTX 3090), this notebook on CPU (torch 2.13.0+cpu) — so the time comparison is not (section 4 accounts for this caveat on the time column). The FT-00a values quoted alongside serve as an order of magnitude, not a bit-exact reference. peft is the only dependency added to the protocol.

1. The FT-00a mini-task, reproduced identically

The protocol is the one from FT-00a section 3, without a single change:

  1. Fashion-MNIST, official split (60,000 train / 10,000 test), batches 256/512;
  2. a domain shift: the photographic negative x -> 1 - x;
  3. SmallCNN (3 conv blocks + linear head, ~29 k parameters), trained 2 epochs on the inverted images;
  4. the network is then frozen, then adapted to the normal domain with LoRA r = 4, alpha = 8 on the c3 and fc layers — 2 epochs, Adam 1e-3.

The only experimental variable in this notebook is the adapter implementation: the LoRALinear/LoRAConv2d classes hand-written in FT-00a, versus peft here.

DATA_DIR = os.path.join(os.path.expanduser("~"), ".cache", "ft00a")  # telecharge une fois

tf = transforms.ToTensor()
train_set = datasets.FashionMNIST(DATA_DIR, train=True, download=True, transform=tf)
test_set = datasets.FashionMNIST(DATA_DIR, train=False, download=True, transform=tf)
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.
    return 1.0 - x


class 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 -> 3
        return self.fc(x.flatten(1))


def n_params(m):
    return sum(p.numel() for p in m.parameters())


def evaluate(model, inverse_domain, loader):
    model.eval()
    good = tot = 0
    with 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 / tot


def 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 in range(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

Reading the result: the protocol is in place

Everything above is the code from FT-00a section 3, copied without modification — that is the methodological point: at the end of the notebook, any difference in outcome will be attributable only to the adapter implementation, not to the protocol.

The output displays the protocol in numbers: 60,000 training images and 10,000 test images, and a base model of 29,066 parameters — the rounded “~29 k” announced in section 1.

torch.manual_seed(SEED)
base_model = SmallCNN().to(DEV)
train(base_model, inverse_domain=True)

acc_base_inv = evaluate(base_model, inverse_domain=True, loader=test_loader)
acc_base_norm = evaluate(base_model, inverse_domain=False, loader=test_loader)
print(f"\ntest INVERSE (son domaine)  : {acc_base_inv:.4f}")
print(f"test NORMAL  (la cible)     : {acc_base_norm:.4f}")
print("valeurs commitees FT-00a    : 0.8325 / 0.0363")
  epoch 1/2  loss=0.5352  (23.4s)
  epoch 2/2  loss=0.3823  (24.7s)

test INVERSE (son domaine)  : 0.8347
test NORMAL  (la cible)     : 0.0430
valeurs commitees FT-00a    : 0.8325 / 0.0363

Reading the result: competent on its domain, mute on the target

The base model repeats the FT-00a journey: ~0.83 on the inverted test (its training domain), ~0.04 on the normal test. The committed FT-00a values are quoted alongside: same orders of magnitude, gaps of ~0.002 (inverted test) and ~0.007 (normal test). Same seed and same build do not guarantee bit-exactness on CPU — parallel arithmetic (multi-core reductions) is non-associative, and two runs of the same loop diverge at the epsilon level. The protocol reproduction is verified, not declared. The starting gap (~80 accuracy points) is the stake the adapter must recover.

2. LoraConfig + get_peft_model: all the machinery

FT-00a wrote two classes — LoRALinear and LoRAConv2d — then wired each target layer by hand, proving the invariants one by one (B = 0 at the start, W frozen, r * (d + k) budget). peft provides the same guarantees by contract:

  • r=4: the rank of the decomposition;
  • lora_alpha=8: the alpha/r = 2 factor, identical to FT-00a;
  • target_modules=["c3", "fc"]: the same two targeted layers;
  • lora_dropout=0.0, bias="none": the FT-00a protocol has neither dropout nor trainable bias.

The internal initialization of peft follows the same canonical convention as FT-00a: lora_A in kaiming-uniform, lora_B at zero — the delta is exactly 0 at step 0.

# -- reseau gele, copie frache du modele de base ------------------------------
frozen = copy.deepcopy(base_model)
for p in frozen.parameters():
    p.requires_grad_(False)

# -- les deux lignes qui remplacent les ~60 lignes de FT-00a -------------------
config = LoraConfig(r=4, lora_alpha=8, target_modules=["c3", "fc"],
                    lora_dropout=0.0, bias="none")
peft_model = get_peft_model(copy.deepcopy(frozen), config).to(DEV)

peft_model.print_trainable_parameters()

# -- verification des invariants, les memes que FT-00a section 2 ---------------
n_train = sum(p.numel() for p in peft_model.parameters() if p.requires_grad)
n_total = sum(p.numel() for p in peft_model.parameters())

x_probe = torch.randn(32, 1, 28, 28, device=DEV)
with torch.no_grad():
    ecart_init = (peft_model(x_probe) - frozen(x_probe)).abs().max().item()

loss = peft_model(x_probe).pow(2).mean()
loss.backward()
w_grad = next(peft_model.base_model.model.c1.parameters()).grad

conv3_budget = 4 * (32 * 3 * 3) + 64 * 4   # r*(in*k^2) + out*r, comme FT-00a
fc_budget = 4 * (576 + 10)                 # r*(in+out)

print(f"\necart initial  max|peft(x) - frozen(x)| = {ecart_init:.3e}"
      f"   {'(exactement 0 : B = 0)' if ecart_init == 0.0 else '(NON NUL)'}")
print(f"gradient sur W (c1)                      : "
      f"{'None (correct : coupe)' if w_grad is None else 'RECU (FUITE)'}")
print(f"budget attendu conv3 + fc (r=4)          : {conv3_budget + fc_budget}")
print(f"parametres entrainables peft             : {n_train}"
      f"   {'(identique a FT-00a)' if n_train == conv3_budget + fc_budget else '(ECART)'}")
trainable params: 3,752 || all params: 32,818 || trainable%: 11.4328

ecart initial  max|peft(x) - frozen(x)| = 0.000e+00   (exactement 0 : B = 0)
gradient sur W (c1)                      : None (correct : coupe)
budget attendu conv3 + fc (r=4)          : 3752
parametres entrainables peft             : 3752   (identique a FT-00a)

Reading the result: same invariants, zero classes written

Three observations, in FT-00a’s order:

  1. the delta is 0 at the start — peft initializes lora_B to zero, the adapted model’s output is bit-exact that of the frozen network;
  2. no gradient reaches the frozen weights — get_peft_model freezes the base automatically, where FT-00a had to write it (requires_grad_(False)) and then prove it;
  3. the budget is identical: 3,752 trainable parameters, the same closed form r*(in*k^2) + out*r for the conv and r*(in+out) for the linear. peft does neither more nor less than the FT-00a decomposition — it is the same mathematics, packaged.

3. Training: same optimizer, same seed, same 2 epochs

The FT-00a train loop drives the peft model without any modification: it only optimizes the requires_grad parameters, which are exactly the adapters.

print("[peft] adaptation au domaine normal, 2 epochs")
torch.manual_seed(SEED)
t0 = time.perf_counter()
train(peft_model, inverse_domain=False)
temps_peft = time.perf_counter() - t0

acc_peft = evaluate(peft_model, inverse_domain=False, loader=test_loader)
print(f"\ntemps de fine-tuning peft : {temps_peft:.1f}s")
print(f"exactitude peft  r=4       : {acc_peft:.4f}"
      f"   (FT-00a LoRA from scratch, commite : 0.7351)")
[peft] adaptation au domaine normal, 2 epochs
  epoch 1/2  loss=0.9408  (19.0s)
  epoch 2/2  loss=0.5247  (20.6s)

temps de fine-tuning peft : 39.6s
exactitude peft  r=4       : 0.7379   (FT-00a LoRA from scratch, commite : 0.7351)

Reading the result: what peft’s 3,752 parameters recover

The recovered accuracy is of the same order as FT-00a’s from-scratch version (0.7351 committed): ~0.70–0.75 after 2 epochs. The two numbers do not coincide exactly, and that is expected: the seed fixes the batch order (identical), but the adapter initialization draw differs — FT-00a drew A in its home-made classes, peft draws its own in its lora.LoRALayer module. Two different training trajectories, same means, same order of magnitude of recovery: that is the signature of an implementation equivalence, not an artifact.

4. The comparison table: from scratch (FT-00a) vs SOTA (peft)

The FT-00a columns quote the committed values of the FT-00a notebook (GPU run, torch 2.8.0+cu126 — a different environment from this one, cf. section 1); the peft columns are measured above. The lines of code count the adapter-specific code (the two classes + the per-layer wiring for FT-00a; the config + the call for peft), excluding the shared protocol.

FT00A_LORA_ACC, FT00A_LORA_PARAMS, FT00A_LORA_TEMPS = 0.7351, 3752, 7.9
FT00A_FULL_ACC, FT00A_FULL_PARAMS = 0.8242, 24266
LOC_FROM_SCRATCH, LOC_PEFT = 60, 2

print("=" * 100)
print(f"{'configuration':<30}{'exactitude':>11}{'params entr.':>13}"
      f"{'temps':>8}{'LOC':>7}{'ecosysteme':>25}")
print("-" * 100)
print(f"{'base gelee, test inverse':<30}{acc_base_inv:>11.4f}{'(gele)':>13}"
      f"{'-':>8}{'-':>7}{'-':>25}")
print(f"{'base gelee, test normal':<30}{acc_base_norm:>11.4f}{'(gele)':>13}"
      f"{'-':>8}{'-':>7}{'-':>25}")
print(f"{'peft r=4 (mesure ici)':<30}{acc_peft:>11.4f}{n_train:>13}"
      f"{temps_peft:>7.1f}s{LOC_PEFT:>5}{'save/load/merge, HF':>25}")
print(f"{'from scratch r=4 (FT-00a)':<30}{FT00A_LORA_ACC:>11.4f}{FT00A_LORA_PARAMS:>13}"
      f"{FT00A_LORA_TEMPS:>7.1f}s{LOC_FROM_SCRATCH:>5}{'aucun (fait maison)':>25}")
print(f"{'full 2 couches (FT-00a)':<30}{FT00A_FULL_ACC:>11.4f}{FT00A_FULL_PARAMS:>13}"
      f"{'7.6':>7}s{'2':>5}{'aucun':>25}")
print("=" * 100)
====================================================================================================
configuration                  exactitude params entr.   temps    LOC               ecosysteme
----------------------------------------------------------------------------------------------------
base gelee, test inverse           0.8347       (gele)       -      -                        -
base gelee, test normal            0.0430       (gele)       -      -                        -
peft r=4 (mesure ici)              0.7379         3752   39.6s    2      save/load/merge, HF
from scratch r=4 (FT-00a)          0.7351         3752    7.9s   60      aucun (fait maison)
full 2 couches (FT-00a)            0.8242        24266    7.6s    2                    aucun
====================================================================================================

Reading the result: why from scratch, when SOTA

  • Accuracy: the three adaptations (peft, from scratch, full) recover the same order of magnitude. The full fine-tuning of the same layers stays ahead — 6.5x more free parameters buy a few points.
  • Budget: peft and the from-scratch version free exactly the same 3,752 parameters (11% of the network) — the library adds nothing to the budget, it guarantees it.
  • LOC: lines to write, test and maintain — that is the manufacturing cost versus the abstraction cost.
  • Time: the CPU run measured here is several times slower than the 7.9 s committed for the from-scratch version (GPU) — the measurement cell prints the exact value; the two runs share neither device nor build, so this ratio does not measure a peft overhead. The adapter does add, per targeted layer, extra kernels (here lora_A 3x3 conv + lora_B 1x1 conv) and a module indirection, but this effect is invisible on this pair of runs; on an LLM it is anyway drowned in the cost of the backbone’s forward.
  • Ecosystem: that is the real dividing line. The peft adapter is a portable artifact (section 5): a few serializable kilobytes, reloadable on any copy of the base, mergeable — and compatible with transformers.Trainer, accelerate, export. FT-00a’s home-made class has none of these rails.
  • From scratch remains irreplaceable for understanding and debugging: when a peft adapter misbehaves (rank too small, miscalibrated alpha), the diagnosis requires knowing what lives under the config.

5. The ecosystem: save_pretrained, PeftModel.from_pretrained, merge_and_unload

Three industrial gestures that FT-00a’s home-made class does not offer:

  1. save the adapter alone (save_pretrained) — a few KB, not the network;
  2. reload onto a pristine copy of the frozen network (PeftModel.from_pretrained) and verify the accuracy round-trips without loss;
  3. merge (merge_and_unload) — the peft equivalent of FT-00a’s section 5: W + (alpha/r) * B @ A rewritten into the weights, adapter dismantled.
# -- 1. sauver l'adaptateur seul ------------------------------------------------
adapter_dir = tempfile.mkdtemp(prefix="ft00c_adapter_")
peft_model.save_pretrained(adapter_dir)
tailles = sorted((os.path.basename(f), os.path.getsize(f)) for f in
                 [os.path.join(adapter_dir, f) for f in os.listdir(adapter_dir)])
print(f"adaptateur sauvegarde dans {os.path.basename(adapter_dir)}/")
for nom, octets in tailles:
    print(f"  {nom:<28}{octets:>8} octets")
print(f"  total                       {sum(o for _, o in tailles):>8} octets"
      f"   (le reseau complet : {n_params(base_model) * 4} octets en float32)")

# -- 2. recharger sur une copie vierge du reseau gele ---------------------------
recharge = PeftModel.from_pretrained(copy.deepcopy(frozen), adapter_dir).to(DEV)
acc_recharge = evaluate(recharge, inverse_domain=False, loader=test_loader)
print(f"\nexactitude apres save + reload : {acc_recharge:.4f}"
      f"   {'(identique)' if acc_recharge == acc_peft else f'(ecart {abs(acc_recharge - acc_peft):.1e})'}")

# -- 3. fusionner : W + (alpha/r) * B @ A, puis controler la derive --------------
proche = copy.deepcopy(peft_model).to(DEV)
fusionne = proche.merge_and_unload()

x_fusion = torch.randn(64, 1, 28, 28, device=DEV)
with torch.no_grad():
    derive = (fusionne(x_fusion) - peft_model(x_fusion)).abs().max().item()
acc_fusion = evaluate(fusionne, inverse_domain=False, loader=test_loader)

print(f"derive max |fusionne(x) - peft(x)| = {derive:.3e}   (epsilon float32)")
print(f"exactitude du modele fusionne      : {acc_fusion:.4f}")
adaptateur sauvegarde dans ft00c_adapter_rz_77w6p/
  README.md                       5074 octets
  adapter_config.json             1181 octets
  adapter_model.safetensors      15440 octets
  total                          21695 octets   (le reseau complet : 116264 octets en float32)

exactitude apres save + reload : 0.7379   (identique)
derive max |fusionne(x) - peft(x)| = 1.717e-05   (epsilon float32)
exactitude du modele fusionne      : 0.7379

Reading the result: the adapter is a portable artifact

  • Lightweight: ~15 KB of tensors (22 KB with the generated card and config) against ~116 KB for the full float32 network — a ~5x ratio here. On a 7B LLM in float16 (~14 GB of weights), the same r=4 adapter on the attention projections fits in a few tens of MB: a ratio on the order of 10^3. That is what makes adapter sharing viable.
  • Lossless round-trip: the accuracy after save_pretrained + from_pretrained is identical — the serialized adapter is the model, not an approximation.
  • The merge is not bit-exact: the measured drift (1.7e-05, i.e. ~140x the float32 epsilon accumulated over the depth of the convolutions) belongs to the same physics as the one demonstrated by hand in FT-00a section 5 — peft redoes the same W + (alpha/r) * B @ A rewrite, with the same non-associative arithmetic. The merged model’s accuracy is unchanged to the 4th decimal place.

6. Exercises

The three exercises are progressive: the first has you predict the budget before verifying it, the second has you build an integrity check of the save/load round-trip, the third transposes FT-00a’s exercise 3 (bounding the merge drift) to the peft side.

# Exercice 1 : le budget selon le rang, cote peft
# TODO etudiant : completez budget_peft(r) pour qu'elle retourne le nombre de
# parametres entrainables qu'un LoraConfig(r=r, lora_alpha=8,
# target_modules=["c3", "fc"]) liberera sur SmallCNN, SANS construire le modele
# (forme fermee uniquement). Verifiez ensuite votre prediction pour r dans
# [1, 2, 4, 8, 16] en construisant reellement le modele peft et en comptant
# sum(p.numel() for p in m.parameters() if p.requires_grad). Pour quel rang le
# budget depasse-t-il celui du full fine-tuning des deux couches (24 266) ?


def budget_peft(r, conv_in=32, conv_k=3, conv_out=64, fc_in=576, fc_out=10):
    # Indice : conv -> r*(in*k^2) + out*r ; lineaire -> r*(in + out).
    # Etape 1 : budget de la couche conv3 ciblee.
    # Etape 2 : budget de la tete fc ciblee.
    # Etape 3 : la somme des deux.
    result = None  # TODO etudiant
    return result


print("Exercice 1 a completer -- budget_peft(4) retourne", budget_peft(4))
Exercice 1 a completer -- budget_peft(4) retourne None

Exercise 2: an integrity check of the save/load round-trip

Section 5 verifies the accuracy after reloading. A stronger check compares the predictions themselves, image by image.

# Exercice 2 : le roundtrip est-il exact, prediction par prediction ?
# TODO etudiant : ecrivez verifie_roundtrip(peft_model, frozen, adapter_dir)
# qui (1) sauvegarde peft_model, (2) recharge sur une copie vierge de frozen,
# (3) compare les logits du couple (peft_model, recharge) sur tout le jeu de
# test NORMAL, et retourne le nombre d'images ou l'argmax differe.
# Resultat attendu : 0. Si vous obtenez autre chose, le roundtrip a une perte.


def verifie_roundtrip(peft_model, frozen, adapter_dir):
    # Indice : reutilisez evaluate() en boucle ou ecrivez la double boucle ;
    # comparer les argmax suffit (les logits float32 peuvent diverger a 1e-7).
    # Etape 1 : save_pretrained vers un NOUVEAU dossier temporaire.
    # Etape 2 : PeftModel.from_pretrained(copy.deepcopy(frozen), ...).
    # Etape 3 : comptez les desaccords d'argmax sur test_loader (domaine normal).
    result = None  # TODO etudiant
    return result


print("Exercice 2 a completer -- verifie_roundtrip() retourne",
      verifie_roundtrip(peft_model, frozen, adapter_dir))
Exercice 2 a completer -- verifie_roundtrip() retourne None

Exercise 3: bound the drift of merge_and_unload

The merge rewrites W + (alpha/r) * B @ A into the weights — FT-00a’s section 5 shows by hand why the rewrite is not bit-exact. Transpose the check to the peft side.

# Exercice 3 : fusion et borne de derive, cote peft
# TODO etudiant : ecrivez derive_fusion_peft(peft_model, n_echantillons=64)
# qui retourne l'ecart max |fusionne(x) - peft(x)| sur des x aleatoires
# (meme graine avant chaque serie de tirages). Comparez float32 puis, si votre
# machine le permet, apres .double() sur tout le graphe : la derive doit suivre
# l'epsilon de la precision, comme dans FT-00a section 5.


def derive_fusion_peft(peft_model, n_echantillons=64):
    # Indice : copy.deepcopy(peft_model) AVANT merge_and_unload (le modele
    # original est demonte par la fusion) ; torch.no_grad() partout ;
    # meme torch.manual_seed(SEED) avant chaque tirage de x pour comparer
    # les deux modeles sur les MEMES entrees.
    # Etape 1 : copie profonde + fusion.
    # Etape 2 : tirage de x sous graine fixee.
    # Etape 3 : ecart max entre les deux sorties.
    result = None  # TODO etudiant
    return result


print("Exercice 3 a completer -- derive_fusion_peft() retourne",
      derive_fusion_peft(peft_model))
Exercice 3 a completer -- derive_fusion_peft() retourne None

Summary

notion what to remember
LoraConfig + get_peft_model replace the hand-written adapter from FT-00a; the invariants (frozen base, B = 0, closed budget) are guaranteed by the library instead of being proven by hand
identical budget peft frees exactly the same 3,752 parameters as the from-scratch version (r*(in*k^2) + out*r for conv, r*(in+out) for linear) — the library adds nothing to the budget
comparable accuracy same seed and same protocol: the recovery is of the same order; only the adapter initialization draw differs
save_pretrained / from_pretrained the adapter is a portable artifact of a few KB, exact on the round-trip — the foundation of adapter sharing (HuggingFace Hub…)
merge_and_unload the W + (alpha/r) * B @ A merge on the library side, with the same float32 epsilon drift demonstrated by hand in FT-00a
when to use what from scratch to understand and debug (FT-00a); peft to produce — HuggingFace ecosystem, Trainer, accelerate, export

To go further: 21_LoRA_FineTuning applies this same peft to a HuggingFace LLM; FT-02 adds 4-bit quantization (QLoRA) to it; FT-06 extends it to vision-language.

Retour au sommet