Hugging Face: DistilBERT¶
Fine-tune DistilBERT on an IMDB subset with the Trainer API. A small callback prints the evaluation results.
| Framework | Hugging Face Transformers |
| Task | Text classification |
Install¶
Plus the K-Veritas CLI.
train.py¶
Only the KV lines and the callback are new.
import numpy as np
import torch
from datasets import load_dataset
from transformers import (
AutoTokenizer, AutoModelForSequenceClassification,
TrainingArguments, Trainer, TrainerCallback,
)
SEED = 42
torch.manual_seed(SEED)
print(f"KV seed {SEED}")
MODEL = "distilbert-base-uncased"
print("KV phase data")
raw = load_dataset("stanfordnlp/imdb")
train_ds = raw["train"].shuffle(seed=SEED).select(range(2000))
test_ds = raw["test"].shuffle(seed=SEED).select(range(1000))
tokenizer = AutoTokenizer.from_pretrained(MODEL)
def tok(batch):
return tokenizer(batch["text"], truncation=True, padding="max_length", max_length=128)
train_ds = train_ds.map(tok, batched=True).rename_column("label", "labels")
test_ds = test_ds.map(tok, batched=True).rename_column("label", "labels")
model = AutoModelForSequenceClassification.from_pretrained(MODEL, num_labels=2)
n_params = sum(p.numel() for p in model.parameters())
print(f"KV model params={n_params} arch=distilbert precision=fp16")
print(f"KV workload dataset_size={len(train_ds)} epochs=2 batch_size=16 seq_len=128")
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=1)
return {"accuracy": float((preds == labels).mean())}
class KVeritas(TrainerCallback):
def on_evaluate(self, args, state, control, metrics=None, **kwargs):
for key, value in (metrics or {}).items():
if isinstance(value, (int, float)):
name = key.replace("eval_", "").replace("/", "_")
print(f"KV {name}={float(value):.4f} step={int(state.epoch or 0)}")
args = TrainingArguments(
output_dir="./_out",
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=2,
eval_strategy="epoch",
logging_strategy="no",
save_strategy="no",
report_to="none",
fp16=torch.cuda.is_available(),
seed=SEED,
)
trainer = Trainer(
model=model, args=args,
train_dataset=train_ds, eval_dataset=test_ds,
processing_class=tokenizer, compute_metrics=compute_metrics,
callbacks=[KVeritas()],
)
print("KV phase train")
trainer.train()
print("KV phase evaluate")
final = trainer.evaluate()
acc = float(final["eval_accuracy"])
print(f"KV test_accuracy={acc:.4f}")
print(f"KV claim accuracy={acc:.4f}")
print(f"final accuracy={acc:.4f}", flush=True)
Run it¶
Result¶
2 epochs on a 2,000-example subset: about 83% accuracy. Each epoch's evaluation results are in the report.