REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: Merge and deploy a trained BERT adapter

Train and reload an adapter, merge Q/V deltas, export the complete classifier and check held-out logits after reload.

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: Merge and deploy a trained BERT adapter →

Your task

Train and reload an adapter, merge Q/V deltas, export the complete classifier and check held-out logits after reload. 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
"""Train, reload, merge Q/V adapters and check actual held-out inference parity."""
from pathlib import Path
import torch
import pythilo_finetune as ft
from finetune_projects.lora import run_project as train_adapter


def run_project(output, quick=False):
    output = Path(output)
    training = train_adapter(output, quick)
    adapter = ft.load_adapter(output / 'adapter.pt').eval()
    merged = ft.merge_adapter(adapter)
    data = ft.dataset(quick=quick)
    ids, mask, labels = ft.encode(data['test'], training['sequence_length'])
    # No training or threshold/model selection uses these test labels.
    with torch.no_grad():
        original_logits = adapter(ids, mask)
        merged_logits = merged(ids, mask)
    error = (original_logits - merged_logits).abs().max().item()
    if not torch.allclose(original_logits, merged_logits, atol=2e-5, rtol=1e-5):
        raise AssertionError('Merged inference differs from the loaded adapter')
    torch.save(merged.state_dict(), output / 'merged.pt')
    restored = ft.pretrained('full')
    restored.load_state_dict(torch.load(output / 'merged.pt', weights_only=True), strict=True)
    restored.eval()
    with torch.no_grad():
        reload_error = (restored(ids, mask) - merged_logits).abs().max().item()
    report = dict(training=training, quick=quick, merge_max_error=error, reload_max_error=reload_error,
                  merged_metrics=ft.metrics(merged_logits, labels), adapter_bytes=(output / 'adapter.pt').stat().st_size,
                  merged_bytes=(output / 'merged.pt').stat().st_size,
                  has_adapter_modules=any(isinstance(module, ft.LoRALinear) for module in merged.modules()),
                  deployment='The small adapter requires the exact base model; merged.pt contains the complete classifier state.')
    ft.save_json(output / 'merge-report.json', report)
    return report

About this algorithm

How Project: Merge and deploy a trained BERT adapter works

The idea

Every time a LoRA layer runs, it adds B @ A * scale on top of a frozen weight. That correction is itself a matrix with the same shape as the weight, so it can be added in once: W + B @ A * scale is an ordinary linear layer that gives the same outputs with no extra work at inference.

That leaves two ways to ship a fine-tuned model: a small adapter file that only works with its exact base, or a merged file that holds the complete classifier. This project trains an adapter, reloads it, merges the query and value layers, checks on test rows that the logits agree within a small tolerance, then saves and reloads the merged model and measures both file sizes.

How it works

  1. Train and export the adapter by calling the LoRA project's run_project.
  2. Reload it with ft.load_adapter, which rebuilds the pretrained base and verifies the manifest.
  3. Call ft.merge_adapter, which adds B @ A * scale to a copy of each query and value weight and swaps in a plain linear layer.
  4. Run the adapter model and the merged model on the encoded test split under torch.no_grad() and compare their logits with torch.allclose.
  5. Save the merged state_dict to merged.pt, load it into ft.pretrained('full') with strict=True, and check the logits again.
  6. Write a report with both errors, the test metrics, both file sizes and whether any adapter module remains.

What it costs

Merge
4 matrix additions
Inference
same as the base model
File size
merged > 100× adapter

Merging is a one-time addition for each adapted layer; afterwards the model runs like the original, at the price of shipping every weight instead of a small adapter.

Where it is used

  • Hugging Face PEFT's merge_and_unload() folds LoRA weights into the base model and returns it without adapter layers.
  • The LoRA paper points out that merged weights add no inference latency compared with the original model.
  • The Diffusers library offers fuse_lora() to merge loaded LoRA weights into a pipeline's model weights.

Watch out for

  • Leaving out the alpha / rank scale when adding B @ A, which changes the merged outputs.
  • Expecting bit-identical logits: adding the matrices first rounds differently from adding two outputs, so the Lab compares with a tolerance.
  • Deleting the base after exporting only the adapter; adapter.pt holds the LoRA matrices and the head, not a complete model.