REAL PYTORCH · CPU TRAINING AND AUTOGRAD

Project: Transfer sentiment across domains

Train on Amazon and Yelp, select on their validation partition, then report untouched IMDb performance.

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: Transfer sentiment across domains →

Your task

Train on Amazon and Yelp, select on their validation partition, then report untouched IMDb performance. 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
"""Domain transfer: train on Amazon/Yelp, select on their validation rows, test on IMDb."""
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(domain_holdout=True, 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='domain-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: Transfer sentiment across domains works

The idea

A sentiment model trained on phone accessory and restaurant reviews may lean on words specific to those domains. To test whether it learned sentiment in general, this project trains on Amazon and Yelp sentences, selects its checkpoint on held-back Amazon and Yelp sentences, and only then scores IMDb film reviews, a domain it never saw.

Keeping all of IMDb out of training and model selection is the point. A random split would mix the three sources into every partition and report in-domain accuracy, which is usually higher. The gap between the validation and IMDb scores is the price of the domain shift. The model is BERT-Tiny with LoRA: the pretrained weights stay frozen, and only small matrices on the attention query and value layers, plus the classifier, are trained.

How it works

  1. Call ft.dataset(domain_holdout=True), which sends every IMDb sentence to test and splits Amazon and Yelp 80/20 into train and validation.
  2. Load ft.pretrained('lora'), hash all parameters and the frozen ones separately, and build AdamW over the trainable weights with lr=1e-3.
  3. Train with shuffled minibatches, cross-entropy and gradient clipping, exactly as in full fine-tuning.
  4. After each epoch, score the Amazon and Yelp validation rows and keep the best state by (macro_f1, -loss).
  5. Restore that state and evaluate the IMDb test split once.
  6. Export adapter.pt, reload it onto a fresh base, and record the largest difference in validation logits as adapter_reload_max_error.

What it costs

Trainable
≈4,400 of 4.4M weights
Test domain
IMDb, never trained on
Saved file
adapter and head only

Only the LoRA matrices and the classifier receive gradients, under 1% of the parameters, but every step still runs the whole frozen network forward and backpropagates through its activations.

Where it is used

  • The WILDS benchmark evaluates models on held-out hospitals, countries, users or time periods to measure this kind of distribution shift.
  • Blitzer, Dredze and Pereira built the 2007 Multi-Domain Sentiment Dataset of Amazon reviews to study sentiment transfer between product categories.
  • The data here comes from Kotzias and co-authors' 2015 paper, which collected labelled sentences from Amazon, IMDb and Yelp reviews.

Watch out for

  • Letting IMDb rows into validation: the checkpoint is then tuned to the target domain and the transfer score stops being a fair test.
  • Reporting the Amazon and Yelp validation score as if it predicted performance on film reviews.
  • Saving the adapter without the base model revision and LoRA settings: loaded onto a different base, the same matrices mean something else.