REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: Train query/value LoRA adapters

Freeze BERT, insert rank-four Q/V adapters, train the classifier and export the exact base/tokenizer identity.

Run this Lab in Pythilo

Open Labs, choose its topic and tap Download entire topic, or Download entire category for all its Labs, including the required Python packages, then load the starter or worked answer and tap Trace. Progress, pause, resume and removal are in Downloads. Independent checks execute real CPU training and gradients.

That explicit download includes the shared UCI sentiment dataset/tokenizer and 17.7 MB pretrained BERT weights. Its source stays local. After setup it trains and evaluates offline; no API key is needed.

PyTorch is unavailable in this browser runtime. The code and lessons are readable here; execution and checks run in the app.

Pythilo on the App Store →

Download complete project source →

Read lesson: Project: Train query/value LoRA adapters →

Your task

Freeze BERT, insert rank-four Q/V adapters, train the classifier and export the exact base/tokenizer identity. Implement run_project(output, quick=False). Follow the reference report/artifact schema; the checks run quick=True with actual pretrained weights and real data. The full dataset is the default.

Starter

from pathlib import Path
import torch
import pythilo_finetune as ft


def run_project(output, quick=False):
    raise NotImplementedError("Implement the training, evidence and artifact contract in the task")
Inspect the worked answer
"""Query/value LoRA fine-tuning with frozen-base proof and a portable adapter artifact."""
from pathlib import Path
import random
import torch
from torch.nn import functional as F
import pythilo_finetune as ft


def run_project(output, quick=False):
    torch.set_num_threads(2)
    output = Path(output); output.mkdir(parents=True, exist_ok=True)
    data = ft.dataset(quick=quick)
    length, batch_size, epochs = (24, 8, 2) if quick else (48, 16, 4)
    train, valid, test = [ft.encode(data[key], length) for key in ('train', 'valid', 'test')]
    model = ft.pretrained('lora')
    before = ft.state_hash(model)
    frozen_before = ft.state_hash(model, frozen_only=True)
    optimizer = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=1e-3, weight_decay=.01)
    rng = random.Random(17)
    torch.manual_seed(317)
    baseline = ft.evaluate(model, valid)
    best, best_state, history, steps = None, None, [], 0
    for epoch in range(epochs):
        order = list(range(len(data['train']))); rng.shuffle(order)
        model.train()
        train_loss = 0.0
        for cursor in range(0, len(order), batch_size):
            ids, mask, labels = ft.minibatch(train, order[cursor:cursor + batch_size])
            optimizer.zero_grad(set_to_none=True)
            loss = F.cross_entropy(model(ids, mask), labels)
            if not torch.isfinite(loss): raise ValueError('Nonfinite training loss')
            loss.backward()
            torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], 1.0, error_if_nonfinite=True)
            optimizer.step(); steps += 1
            train_loss += loss.item() * len(labels)
        score = ft.evaluate(model, valid)
        history.append(dict(epoch=epoch + 1, train_loss=train_loss / len(order), **score))
        # The test split is not consulted for model selection.
        key = (score['macro_f1'], -score['loss'])
        if best is None or key > best:
            best, best_state = key, {name: value.detach().clone() for name, value in model.state_dict().items()}
    model.load_state_dict(best_state, strict=True)
    validation = ft.evaluate(model, valid)
    final_test = ft.evaluate(model, test)
    report = ft.provenance(data, model, optimizer)
    report.update(mode='lora', sequence_length=length, batch_size=batch_size, epochs=epochs, steps=steps,
                  baseline_validation=baseline, validation=validation, test=final_test, history=history,
                  parameters_before=before, parameters_after=ft.state_hash(model),
                  frozen_before=frozen_before, frozen_after=ft.state_hash(model, frozen_only=True))
    ft.export_adapter(model, output / 'adapter.pt')
    reloaded = ft.load_adapter(output / 'adapter.pt').eval()
    model.eval()
    with torch.no_grad():
        delta = (model(valid[0], valid[1]) - reloaded(valid[0], valid[1])).abs().max().item()
    report['adapter_reload_max_error'] = delta
    report['artifact_bytes'] = (output / 'adapter.pt').stat().st_size
    ft.save_json(output / 'report.json', report)
    return report

About this algorithm

How Project: Train query/value LoRA adapters works

The idea

LoRA fine-tunes a large model by training a small correction instead of the weights themselves. Each chosen linear layer keeps its pretrained weight frozen and adds the product of two narrow matrices, B @ A, scaled by alpha / rank. At rank 4 on a 128 by 128 weight, that is 1,024 trainable values in place of 16,384. B starts at zero, so at first the adapters change nothing.

This project wraps the query and value projections in both layers of a real BERT-Tiny, trains them with a new classifier head on sentiment sentences, and shows with parameter hashes that the frozen base did not change. An adapter is useless without its exact base, so the export includes a manifest with the base revision and checksums.

How it works

  1. Load the dataset and ft.pretrained('lora'), which freezes BERT and wraps query and value in LoRALinear with rank 4 and alpha 8.
  2. Hash all parameters and the frozen ones separately, then give AdamW only the parameters with requires_grad.
  3. For each epoch, shuffle the row order with a seeded random.Random and train on mini-batches with cross-entropy and a gradient norm cap of 1.
  4. After each epoch, evaluate on validation and keep the state with the best macro F1, using lower loss to break ties.
  5. Restore the best state, evaluate the test split once, and record that the frozen hash is unchanged.
  6. Export adapter.pt with its manifest, reload it with ft.load_adapter, and check that the reloaded logits match exactly.

What it costs

Trainable
4,354 of about 4.39M
Per step
full forward pass
Adapter file
LoRA matrices and head

The forward pass still runs the whole model; the savings are in gradients, optimizer state and the saved file, which cover only the adapters and the classifier head.

Where it is used

  • The LoRA paper by Hu and co-authors adapted only the query and value projections in most of its experiments.
  • Hugging Face PEFT targets the query and value modules by default when it adds LoRA to a BERT model.
  • Microsoft's loralib, released with the paper, saves only the adapter tensors through lora_state_dict(model).

Watch out for

  • Initialising both A and B to zero: the gradient of each is multiplied by the other, so the adapter never learns.
  • Forgetting to freeze the base, which silently turns the run into full fine-tuning; the Lab checks that under one percent of parameters are trainable.
  • Loading an adapter onto a different base revision or tokenizer; the Lab's load_adapter rejects a manifest that does not match.