TExcelTAD

Mini Project: Scratch vs Feature Extraction vs LoRA

The course has argued that the best strategy depends on how many labels you have and how much a pretrained model knows about your task. This project tests that claim on one task, with one model architecture, on equal terms. You will train a movie-review sentiment classifier in three ways, at three label budgets, compare them with a classical baseline, and write up what you found, including what the numbers cannot tell you.

The brief

  • Task: classify one-sentence movie reviews from rotten_tomatoes as positive or negative (the data of sentence embeddings and LoRA with PEFT).
  • Model: google/bert_uncased_L-2_H-128_A-2, a 2-layer BERT with 4.4 million parameters, in three roles:
    1. Scratch: the same architecture, randomly initialised, every weight trained (training from scratch).
    2. Feature extraction: the pretrained model frozen, mean-pooled embeddings, logistic regression on top (feature extraction).
    3. LoRA: the pretrained model with rank-8 adapters on the query and value projections plus a new head (LoRA).
  • Baseline: TF-IDF of words and word pairs with logistic regression, the classical "from scratch" text model.
  • Label budgets: n=200n = 200, 500500 and 20002000 labelled sentences, always the first nn of the same shuffled pool of 2,000, so a larger budget contains the smaller ones.
  • Evaluation: a fixed validation set of 500 sentences for every choice (epoch, regularisation CC), and a fixed test set of 500 sentences, scored once per strategy and budget. Metric: accuracy (the test set is balanced: 49.4 % positive).
  • Fairness rules: the same tokenisation (48 word pieces), the same training loop (AdamW, batches of 32, up to 6 epochs, best validation epoch restored), learning rates set before looking at any result (5⋅10−45 \cdot 10^{-4} for scratch, 10−310^{-3} for LoRA as in the PEFT lesson), and the same seed.

Everything runs on a CPU in under a minute per step. The steps are recorded examples (they need PyTorch, Transformers and PEFT); the results table at the end runs in your browser.

Step 1: data and the baseline

The setup at the top (the 19 lines up to SIZES) is repeated in every step, so each step runs on its own.

python · try it yourself
import copy, warnings
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoTokenizer
from transformers.utils import logging
logging.set_verbosity_error()
warnings.filterwarnings("ignore", message="Could not find a config file")   # offline check of the model files

NAME = "google/bert_uncased_L-2_H-128_A-2"                   # 2 layers, hidden size 128, 4.4M parameters
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
pool = ds["train"].shuffle(seed=0).select(range(2000))       # labelled pool: the first n are used
val = ds["validation"].shuffle(seed=0).select(range(500))   # every choice (epoch, C) is made here
test = ds["test"].shuffle(seed=0).select(range(500))        # scored once per strategy and size
tok = AutoTokenizer.from_pretrained(NAME)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_pool, X_val, X_te = enc(pool), enc(val), enc(test)
y_pool, y_val, y_te = (torch.tensor(d["label"]) for d in (pool, val, test))
SIZES = [200, 500, 2000]

# Step 1: the baseline, TF-IDF of words and word pairs + logistic regression, C chosen on validation
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

print(f"pool {len(pool)}, validation {len(val)}, test {len(test)}; positive share in test {y_te.float().mean():.3f}")
txt_pool, txt_val, txt_te = list(pool["text"]), list(val["text"]), list(test["text"])
for n in SIZES:
    fit = lambda C: make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression(C=C, max_iter=5000)).fit(
        txt_pool[:n], y_pool[:n].numpy())
    v, C = max((fit(C).score(txt_val, y_val.numpy()), C) for C in [0.1, 1, 10, 100])
    print(f"TF-IDF + logistic  n={n:5d}  val {v:.3f} (C={C})  test {fit(C).score(txt_te, y_te.numpy()):.3f}")
pool 2000, validation 500, test 500; positive share in test 0.494
TF-IDF + logistic  n=  200  val 0.622 (C=10)  test 0.612
TF-IDF + logistic  n=  500  val 0.636 (C=10)  test 0.634
TF-IDF + logistic  n= 2000  val 0.716 (C=1)  test 0.712

The test set is balanced, so guessing gives about 0.5. TF-IDF goes from 0.612 with 200 labels to 0.712 with 2,000: a classical text model is a serious baseline once it has a couple of thousand examples, and anything more complex has to beat it.

Step 2: training BERT from scratch

python · try it yourself
import copy, warnings
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoTokenizer
from transformers.utils import logging
logging.set_verbosity_error()
warnings.filterwarnings("ignore", message="Could not find a config file")   # offline check of the model files

NAME = "google/bert_uncased_L-2_H-128_A-2"                   # 2 layers, hidden size 128, 4.4M parameters
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
pool = ds["train"].shuffle(seed=0).select(range(2000))       # labelled pool: the first n are used
val = ds["validation"].shuffle(seed=0).select(range(500))   # every choice (epoch, C) is made here
test = ds["test"].shuffle(seed=0).select(range(500))        # scored once per strategy and size
tok = AutoTokenizer.from_pretrained(NAME)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_pool, X_val, X_te = enc(pool), enc(val), enc(test)
y_pool, y_val, y_te = (torch.tensor(d["label"]) for d in (pool, val, test))
SIZES = [200, 500, 2000]

# Step 2: the same BERT architecture, randomly initialised and trained on the n labels
from transformers import AutoConfig, AutoModelForSequenceClassification

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        logits = model(input_ids=X["input_ids"], attention_mask=X["attention_mask"]).logits
    return (logits.argmax(1) == y).float().mean().item()

def train(model, n, lr, epochs=6):
    """AdamW, batches of 32; keep the epoch with the best validation accuracy, then test once."""
    opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
    g = torch.Generator().manual_seed(0)
    best = (-1.0, 0, None)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(n, generator=g).split(32):
            out = model(input_ids=X_pool["input_ids"][idx], attention_mask=X_pool["attention_mask"][idx], labels=y_pool[idx])
            opt.zero_grad(); out.loss.backward(); opt.step()
        v = accuracy(model, X_val, y_val)
        if v > best[0]:
            best = (v, epoch, copy.deepcopy(model.state_dict()))
    model.load_state_dict(best[2])
    return best[0], best[1], accuracy(model, X_te, y_te)

for n in SIZES:
    torch.manual_seed(0)
    model = AutoModelForSequenceClassification.from_config(AutoConfig.from_pretrained(NAME, num_labels=2))
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    v, e, a = train(model, n, lr=5e-4)
    print(f"scratch BERT       n={n:5d}  val {v:.3f} (epoch {e})  test {a:.3f}  trainable {trainable:,}")
scratch BERT       n=  200  val 0.544 (epoch 6)  test 0.540  trainable 4,386,178
scratch BERT       n=  500  val 0.596 (epoch 5)  test 0.584  trainable 4,386,178
scratch BERT       n= 2000  val 0.714 (epoch 2)  test 0.708  trainable 4,386,178

With random weights the 4.4 million parameters have to learn the meaning of every word piece from the labelled sentences alone. At 200 labels the model barely beats guessing (0.540), at 500 it reaches 0.584, and only at 2,000 does it catch up with TF-IDF (0.708). The best validation epoch is the last or second-to-last one at the small budgets, a sign that it was still learning slowly, and epoch 2 at 2,000 labels, where it starts to overfit soon after.

Step 3: feature extraction

python · try it yourself
import copy, warnings
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoTokenizer
from transformers.utils import logging
logging.set_verbosity_error()
warnings.filterwarnings("ignore", message="Could not find a config file")   # offline check of the model files

NAME = "google/bert_uncased_L-2_H-128_A-2"                   # 2 layers, hidden size 128, 4.4M parameters
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
pool = ds["train"].shuffle(seed=0).select(range(2000))       # labelled pool: the first n are used
val = ds["validation"].shuffle(seed=0).select(range(500))   # every choice (epoch, C) is made here
test = ds["test"].shuffle(seed=0).select(range(500))        # scored once per strategy and size
tok = AutoTokenizer.from_pretrained(NAME)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_pool, X_val, X_te = enc(pool), enc(val), enc(test)
y_pool, y_val, y_te = (torch.tensor(d["label"]) for d in (pool, val, test))
SIZES = [200, 500, 2000]

# Step 3: feature extraction, frozen pretrained BERT, mean-pooled embeddings + logistic regression
from transformers import AutoModel
from sklearn.linear_model import LogisticRegression

bert = AutoModel.from_pretrained(NAME).eval()
def embed(X):
    with torch.no_grad():
        h = bert(input_ids=X["input_ids"], attention_mask=X["attention_mask"]).last_hidden_state
    m = X["attention_mask"].unsqueeze(-1).float()
    return ((h * m).sum(1) / m.sum(1)).numpy()                # mean over the real tokens, padding ignored
E_pool, E_val, E_te = embed(X_pool), embed(X_val), embed(X_te)   # the backbone runs once
print("embeddings:", E_pool.shape, E_val.shape, E_te.shape)
for n in SIZES:
    fit = lambda C: LogisticRegression(C=C, max_iter=5000).fit(E_pool[:n], y_pool[:n].numpy())
    v, C = max((fit(C).score(E_val, y_val.numpy()), C) for C in [0.01, 0.1, 1, 10, 100])
    print(f"feature extraction n={n:5d}  val {v:.3f} (C={C})  test {fit(C).score(E_te, y_te.numpy()):.3f}  trainable {E_pool.shape[1] + 1}")
embeddings: (2000, 128) (500, 128) (500, 128)
feature extraction n=  200  val 0.668 (C=0.1)  test 0.656  trainable 129
feature extraction n=  500  val 0.688 (C=0.01)  test 0.680  trainable 129
feature extraction n= 2000  val 0.718 (C=0.1)  test 0.712  trainable 129

The backbone runs once over the 3,000 sentences, and each budget only refits a logistic regression with 129 parameters (128 weights and a bias). With 200 labels it reaches 0.656, more than TF-IDF (0.612) and far more than scratch (0.540); the validation set chose strong regularisation (C=0.1C = 0.1 and 0.010.01), as expected for few labels. At 2,000 labels it ties TF-IDF at 0.712.

Step 4: LoRA

python · try it yourself
import copy, warnings
import numpy as np
import torch
from datasets import load_dataset
from transformers import AutoTokenizer
from transformers.utils import logging
logging.set_verbosity_error()
warnings.filterwarnings("ignore", message="Could not find a config file")   # offline check of the model files

NAME = "google/bert_uncased_L-2_H-128_A-2"                   # 2 layers, hidden size 128, 4.4M parameters
ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
pool = ds["train"].shuffle(seed=0).select(range(2000))       # labelled pool: the first n are used
val = ds["validation"].shuffle(seed=0).select(range(500))   # every choice (epoch, C) is made here
test = ds["test"].shuffle(seed=0).select(range(500))        # scored once per strategy and size
tok = AutoTokenizer.from_pretrained(NAME)
enc = lambda d: tok(list(d["text"]), padding="max_length", truncation=True, max_length=48, return_tensors="pt")
X_pool, X_val, X_te = enc(pool), enc(val), enc(test)
y_pool, y_val, y_te = (torch.tensor(d["label"]) for d in (pool, val, test))
SIZES = [200, 500, 2000]

# Step 4: LoRA r=8 on the query and value projections of the pretrained BERT (+ the new head)
from transformers import AutoModelForSequenceClassification
from peft import LoraConfig, get_peft_model

def accuracy(model, X, y):
    model.eval()
    with torch.no_grad():
        logits = model(input_ids=X["input_ids"], attention_mask=X["attention_mask"]).logits
    return (logits.argmax(1) == y).float().mean().item()

def train(model, n, lr, epochs=6):
    """The same loop as step 2."""
    opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=lr)
    g = torch.Generator().manual_seed(0)
    best = (-1.0, 0, None)
    for epoch in range(1, epochs + 1):
        model.train()
        for idx in torch.randperm(n, generator=g).split(32):
            out = model(input_ids=X_pool["input_ids"][idx], attention_mask=X_pool["attention_mask"][idx], labels=y_pool[idx])
            opt.zero_grad(); out.loss.backward(); opt.step()
        v = accuracy(model, X_val, y_val)
        if v > best[0]:
            best = (v, epoch, copy.deepcopy(model.state_dict()))
    model.load_state_dict(best[2])
    return best[0], best[1], accuracy(model, X_te, y_te)

for n in SIZES:
    torch.manual_seed(0)
    model = AutoModelForSequenceClassification.from_pretrained(NAME, num_labels=2)
    model = get_peft_model(model, LoraConfig(task_type="SEQ_CLS", r=8, lora_alpha=16, target_modules=["query", "value"]))
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    v, e, a = train(model, n, lr=1e-3)
    print(f"LoRA r=8           n={n:5d}  val {v:.3f} (epoch {e})  test {a:.3f}  trainable {trainable:,}")
LoRA r=8           n=  200  val 0.618 (epoch 6)  test 0.582  trainable 8,450
LoRA r=8           n=  500  val 0.680 (epoch 5)  test 0.662  trainable 8,450
LoRA r=8           n= 2000  val 0.706 (epoch 5)  test 0.696  trainable 8,450

LoRA trains 8,450 parameters: 2×2×8×(128+128)=81922 \times 2 \times 8 \times (128 + 128) = 8192 in the adapters of the two layers' query and value matrices, plus the 258 of the new head. At 500 labels it is close to feature extraction (0.662 against 0.680); at 200 it is behind (0.582), and its best epoch was the last one, so it had not finished learning in 6 epochs at that budget; at 2,000 it reaches 0.696.

Step 5: the results table

The four steps' test accuracies, collected into one table. With 500 test sentences, a 95 % interval around an accuracy near 0.65 is about ±1.960.65⋅0.35/500≈±0.042\pm 1.96 \sqrt{0.65 \cdot 0.35 / 500} \approx \pm 0.042; the script lists which strategies are that close to the best one.

python · try it yourself
import numpy as np
import pandas as pd

# test accuracies copied from the outputs of steps 1 to 4 (500 test sentences each)
results = {
    "TF-IDF + logistic":  ([0.612, 0.634, 0.712], "TF-IDF vocabulary"),
    "scratch BERT":       ([0.540, 0.584, 0.708], 4_386_178),
    "feature extraction": ([0.656, 0.680, 0.712], 129),
    "LoRA r=8":           ([0.582, 0.662, 0.696], 8_450),
}
sizes = [200, 500, 2000]
table = pd.DataFrame({name: acc for name, (acc, _) in results.items()}, index=sizes).T
table.columns = [f"n={n}" for n in sizes]
table["trainable"] = [p if isinstance(p, str) else f"{p:,}" for _, p in results.values()]
print(table.to_string())

se = np.sqrt(0.65 * 0.35 / 500)                     # standard error of an accuracy near 0.65 on 500 sentences
print(f"\nstandard error ~ {se:.3f}; 95 % interval ~ +/- {1.96 * se:.3f}")
for n in sizes:
    col = table[f"n={n}"]
    close = col[col >= col.max() - 1.96 * se].index.tolist()
    top = col[col == col.max()].index.tolist()
    print(f"n={n:5d}: best {' = '.join(top)} ({col.max():.3f}); within 0.042 of it: {', '.join(close)}")
                    n=200  n=500  n=2000          trainable
TF-IDF + logistic   0.612  0.634   0.712  TF-IDF vocabulary
scratch BERT        0.540  0.584   0.708          4,386,178
feature extraction  0.656  0.680   0.712                129
LoRA r=8            0.582  0.662   0.696              8,450

standard error ~ 0.021; 95 % interval ~ +/- 0.042
n=  200: best feature extraction (0.656); within 0.042 of it: feature extraction
n=  500: best feature extraction (0.680); within 0.042 of it: feature extraction, LoRA r=8
n= 2000: best TF-IDF + logistic = feature extraction (0.712); within 0.042 of it: TF-IDF + logistic, scratch BERT, feature extraction, LoRA r=8

What the numbers say

  • Few labels favour reuse. At 200 labels feature extraction (0.656) is ahead of everything else, and it is the only strategy within 0.042 of the best. Scratch BERT is near chance. This is the steep left part of the label curve from the introduction, where pretrained features replace missing labels.
  • The advantage shrinks with labels. At 2,000 labels all four are within 0.016 of each other (0.696 to 0.712), well inside the noise. With enough labels for this task the pretrained knowledge of a tiny model stops mattering, and the cheap TF-IDF baseline is as good as anything.
  • LoRA did not beat feature extraction here. The backbone is very small (2 layers, width 128), so there is little for low-rank updates to adapt, and the training budget (6 epochs, one learning rate) was not tuned per budget. The PEFT lesson found full fine-tuning slightly ahead of LoRA on this model; neither result says much about LoRA on a 7-billion-parameter model, where it is the only affordable way to adapt the weights at all.
  • Costs differ by orders of magnitude. Feature extraction trained 129 numbers and ran the backbone once; LoRA trained 8,450 and ran the backbone forward and backward for every batch and epoch; scratch trained 4.4 million.

What the numbers cannot say: one seed, one split and one small model. Differences under about 0.04 are not significant at 500 test sentences, and the comparison is unpaired (a paired test on the same sentences, below, is stricter). A different backbone (the 384-dimensional all-MiniLM-L6-v2 reached 0.728 with only 1,000 labels and a linear head in sentence embeddings) would move every pretrained number up.

Extensions

  1. Seeds. Repeat steps 2 to 4 with seeds 0 to 4 (model initialisation and batch order) and report the mean and standard deviation for each cell of the table.
  2. A paired test. Save each strategy's predictions on the 500 test sentences. For two strategies A and B, count bb, the sentences A gets right and B wrong, and cc, the reverse. McNemar's test compares (∣b−c∣−1)2/(b+c)(\lvert b - c \rvert - 1)^2 / (b + c) with 3.84 (the 95 % point of a chi-squared distribution with one degree of freedom); above it, the difference is significant. Pairing removes the noise of which sentences happen to be in the test set.
  3. Full fine-tuning as a fourth arm: the step 4 loop without get_peft_model, learning rate 10−410^{-4}. Is the gap to LoRA larger at 200 or at 2,000 labels?
  4. A stronger backbone for feature extraction: SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") instead of the tiny BERT. How many labels does TF-IDF then need to catch up?
  5. Active learning for the budget: instead of the first 200 sentences of the pool, pick 200 by uncertainty with the feature-extraction model (query strategies, the labelling loop). Does it beat random choice at the same budget?
  6. Pseudo-labels: label the remaining 1,800 pool sentences with the 200-label feature-extraction model, keep the confident ones, and retrain (pseudo-labelling).
  7. Cost: time each step (wall clock, CPU) and add a column. Which strategy gives the most accuracy per second of training at each budget?

Write-up template

Copy this into your notes and fill it in; keep it to one page.

markdown
# Strategy comparison: <task>

## Question
Which training strategy gives the best <metric> for <task> at <label budgets>, and at what cost?

## Setup
- Data: <source, licence>, pool <N> labelled, validation <N>, test <N>; class balance <..>
- Split: <random / grouped / by time> because <deployment reason>
- Model(s): <name, size, pretrained on what>
- Strategies: scratch / feature extraction / LoRA (r=<..>, targets <..>) / baseline <..>
- Fixed in advance: tokenisation <..>, optimiser <..>, learning rates <..>, max epochs <..>, seeds <..>
- Chosen on validation: <epoch, C, ...>; test set used once per cell

## Results
| strategy | n=<a> | n=<b> | n=<c> | trainable params | train time |
|---|---|---|---|---|---|
| ... | | | | | |
Uncertainty: 95 % interval about +/- <..> (test size <..>); seeds <..>; paired test <..>

## Findings
1. <what wins at small budgets, by how much, and is it beyond the noise>
2. <what happens as labels grow>
3. <cost per strategy>

## Limits
<one model, one split, seeds, untuned hyperparameters, domain of the pretrained model>

## Recommendation
<strategy> for <situation>, because <evidence>. Next experiment: <..>

Checklist

  • Validation and test sets fixed before any training; test scored once per cell.
  • Every choice (epoch, CC, rank, learning rate) made on validation only.
  • Same tokenisation, loop and seeds for all neural strategies.
  • A classical baseline in the table.
  • Trainable parameters and training cost reported next to accuracy.
  • Differences compared with the test-set uncertainty, not just ranked.
  • The limits of the experiment stated in the write-up.

Test yourself

In this project, at 200 labels, which strategy was clearly ahead, beyond the 95 % uncertainty of the test set?

  1. Scratch BERT
  2. TF-IDF + logistic regression
  3. Feature extraction
  4. LoRA r=8

At 2,000 labels the four strategies scored between 0.696 and 0.712 on 500 test sentences. What is the right conclusion?

  1. TF-IDF and feature extraction are the best models
  2. LoRA is worse than TF-IDF
  3. The differences are within the noise; more seeds or a paired test are needed to separate them
  4. Pretraining always hurts with many labels

Why did every strategy choose its epoch and regularisation on the validation set instead of the test set?

  1. The validation set is larger
  2. Choices made on the test set make its score optimistic, so it no longer estimates performance on new data
  3. The test set has no labels
  4. It makes training faster