llm-124m / code /finetune.py
alexander2323's picture
Upload folder using huggingface_hub
dc9424f verified
Raw History Blame Contribute Delete
7.48 kB
"""
finetune.py - stage two: teach the pretrained model to answer questions.
Starts from a checkpoint written by train.py and continues training on
human-written question/answer pairs, so the model learns the shape
Context: <optional passage>
Question: <question>
Answer: <answer><end-of-text>
Loss is computed only on the answer tokens, so the model learns to produce
answers, not to predict questions. The result is saved in the same checkpoint
format as train.py, so generate.py and chat.py can load it.
Data (both human-written, no model-generated text):
databricks/databricks-dolly-15k 15k instruction/answer pairs, all of them
google-research-datasets/nq_open 88k real search questions with short Wikipedia answers
Example (on the GPU server, a few minutes on one card):
python finetune.py --ckpt out_124M/ckpt.pt --out out_chat
"""
import argparse
import json
import math
import os
import random
import time
import tiktoken
import torch
from model import GPT, GPTConfig
EOT = 50256
def format_example(question, answer, context=""):
prompt = ""
if context:
prompt += "Context: " + context.strip() + "\n\n"
prompt += "Question: " + question.strip() + "\nAnswer:"
return prompt, " " + answer.strip()
def load_examples():
from datasets import load_dataset
from huggingface_hub import hf_hub_download
examples = [] # (prompt, answer)
path = hf_hub_download("databricks/databricks-dolly-15k", "databricks-dolly-15k.jsonl",
repo_type="dataset")
n_dolly = 0
with open(path) as f:
for line in f:
row = json.loads(line)
if not row["response"].strip():
continue
examples.append(format_example(row["instruction"], row["response"], row.get("context", "")))
n_dolly += 1
nq = load_dataset("google-research-datasets/nq_open", split="train")
n_nq = 0
for row in nq:
q = row["question"].strip()
if not q or not row["answer"]:
continue
q = q[0].upper() + q[1:]
if not q.endswith("?"):
q += "?"
examples.append(format_example(q, row["answer"][0]))
n_nq += 1
return examples, n_dolly, n_nq
def tokenize(enc, examples, max_len):
"""Returns list of (input_ids, target_ids) with targets = -1 on prompt tokens."""
out = []
for prompt, answer in examples:
p = enc.encode_ordinary(prompt)
a = enc.encode_ordinary(answer) + [EOT]
ids = (p + a)[:max_len + 1]
if len(ids) < 2 or len(p) >= len(ids) - 1:
continue # answer got truncated away
x = ids[:-1]
y = [-1] * (len(p) - 1) + ids[len(p):] # predict answer tokens (and EOT) only
assert len(x) == len(y)
out.append((x, y))
return out
def make_batch(items, device):
L = max(len(x) for x, _ in items)
X = torch.full((len(items), L), EOT, dtype=torch.long)
Y = torch.full((len(items), L), -1, dtype=torch.long)
for i, (x, y) in enumerate(items):
X[i, :len(x)] = torch.tensor(x)
Y[i, :len(y)] = torch.tensor(y)
return X.to(device, non_blocking=True), Y.to(device, non_blocking=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True, help="pretrained checkpoint from train.py")
ap.add_argument("--out", default="out_chat")
ap.add_argument("--epochs", type=int, default=2)
ap.add_argument("--batch", type=int, default=32, help="examples per step")
ap.add_argument("--lr", type=float, default=3e-5)
ap.add_argument("--warmup-steps", type=int, default=50)
ap.add_argument("--weight-decay", type=float, default=0.1)
ap.add_argument("--max-len", type=int, default=1024)
ap.add_argument("--val-examples", type=int, default=500)
ap.add_argument("--log-every", type=int, default=50)
ap.add_argument("--seed", type=int, default=1337)
args = ap.parse_args()
random.seed(args.seed)
torch.manual_seed(args.seed)
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
device_type = "cuda" if device.startswith("cuda") else "cpu"
use_bf16 = device_type == "cuda"
os.makedirs(args.out, exist_ok=True)
log_f = open(os.path.join(args.out, "log.txt"), "a")
def log(msg):
print(msg, flush=True)
log_f.write(msg + "\n")
log_f.flush()
ckpt = torch.load(args.ckpt, map_location=device)
cfg = GPTConfig(**ckpt["config"])
model = GPT(cfg).to(device)
model.load_state_dict(ckpt["model"])
log(f"loaded {args.ckpt}: {model.num_params()/1e6:.1f}M parameters, pretrained {ckpt['step']} steps")
del ckpt
enc = tiktoken.get_encoding("gpt2")
examples, n_dolly, n_nq = load_examples()
random.shuffle(examples)
data = tokenize(enc, examples, min(args.max_len, cfg.block_size))
val, train = data[:args.val_examples], data[args.val_examples:]
log(f"examples: dolly={n_dolly} nq_open={n_nq} -> train={len(train)} val={len(val)}")
optimizer = model.configure_optimizers(args.weight_decay, args.lr, (0.9, 0.95), device_type)
steps_per_epoch = len(train) // args.batch
total_steps = steps_per_epoch * args.epochs
def lr_at(s):
if s < args.warmup_steps:
return args.lr * (s + 1) / args.warmup_steps
progress = min(1.0, (s - args.warmup_steps) / max(1, total_steps - args.warmup_steps))
return args.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress)))
def autocast():
if use_bf16:
return torch.autocast(device_type="cuda", dtype=torch.bfloat16)
return torch.autocast(device_type="cpu", enabled=False)
@torch.no_grad()
def evaluate():
model.eval()
total, n = 0.0, 0
for i in range(0, len(val), args.batch):
x, y = make_batch(val[i:i + args.batch], device)
with autocast():
_, loss = model(x, y)
total += loss.item()
n += 1
model.train()
return total / max(1, n)
log(f"device={device} batch={args.batch} steps/epoch={steps_per_epoch} total_steps={total_steps}")
log(f"before fine-tuning: val_loss {evaluate():.4f}")
model.train()
step = 0
t0 = time.time()
for epoch in range(args.epochs):
random.shuffle(train)
for i in range(steps_per_epoch):
lr = lr_at(step)
for g in optimizer.param_groups:
g["lr"] = lr
x, y = make_batch(train[i * args.batch:(i + 1) * args.batch], device)
with autocast():
_, loss = model(x, y)
loss.backward()
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
optimizer.zero_grad(set_to_none=True)
step += 1
if step % args.log_every == 0:
log(f"epoch {epoch+1} step {step}/{total_steps} loss {loss.item():.4f} "
f"lr {lr:.2e} norm {norm.item():.2f} {time.time()-t0:.0f}s")
log(f"epoch {epoch+1} done: val_loss {evaluate():.4f}")
torch.save({
"model": model.state_dict(),
"step": step,
"config": cfg.__dict__,
"args": vars(args),
"prompt_format": "Question: {question}\nAnswer:",
}, os.path.join(args.out, "ckpt.pt"))
log(f"saved {args.out}/ckpt.pt")
if __name__ == "__main__":
main()