REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: Fine-tune pretrained BERT

Update the complete pretrained encoder; select a checkpoint on validation macro-F1 and evaluate the test once.

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: Fine-tune pretrained BERT →

Your task

Update the complete pretrained encoder; select a checkpoint on validation macro-F1 and evaluate the test once. 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
"""Full pretrained BERT fine-tuning with validation selection and untouched final test."""
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('full')
    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=2e-4, 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='full', 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))
    torch.save(model.state_dict(), output / 'model.pt')
    report['artifact_bytes'] = (output / 'model.pt').stat().st_size
    ft.save_json(output / 'report.json', report)
    return report

About this algorithm

How Project: Fine-tune pretrained BERT works

The idea

Fine-tuning starts from a network that already knows general language patterns and continues training it on a small labelled task. This project loads real pretrained weights for BERT-Tiny, a two-layer BERT with about 4.4 million parameters, puts a fresh two-class classifier on top, and updates every weight on sentiment sentences from Amazon, IMDb and Yelp reviews.

The procedure around the training loop is what makes the result trustworthy. Repeated sentences are collapsed before the split into train, validation and test, so no text sits in two partitions. After each epoch the model is scored on validation, and the checkpoint with the best macro-F1 is kept. The test split is evaluated once, on that checkpoint. A score used to choose the model cannot also be the score you report.

How it works

  1. Load the splits with ft.dataset, encode each one into fixed-length token ids and masks, and load the model with ft.pretrained('full').
  2. Hash the parameters, build AdamW over all trainable weights with lr=2e-4, and score validation once as a baseline.
  3. Each epoch, shuffle the training order with a seeded generator and run minibatches through cross-entropy, backward, gradient clipping at 1.0 and optimizer.step().
  4. After each epoch, evaluate on validation and copy the weights if (macro_f1, -loss) beats the best so far.
  5. Restore the best weights, then evaluate validation again and the test split once.
  6. Save model.pt and a report.json holding metrics, history, split ids and the parameter hashes from before and after.

What it costs

Trainable
all ≈4.4M parameters
AdamW state
2 moments per weight
Saved file
full model, ≈17.5 MB

Every weight receives a gradient and AdamW stores two moment values for each one, so training holds several times the model's size in memory, all on the CPU.

Where it is used

  • Devlin and co-authors' 2018 BERT paper fine-tuned all parameters for each task and set new best results on GLUE and SQuAD.
  • Google released BERT-Tiny, the 2-layer, 128-hidden model used here, as one of 24 smaller BERT models in 2020.
  • Hugging Face's Trainer with load_best_model_at_end=True reloads the checkpoint that had the best validation metric when training finishes.

Watch out for

  • Choosing the checkpoint by test score: the reported test number is then optimistic, because it was used for selection.
  • Using a from-scratch learning rate such as 1e-2: large steps wipe out the pretrained weights. This project uses 2e-4 with gradient clipping.
  • Splitting rows at random while a sentence appears more than once, which can put the same text in both train and test.