Orchidia / scripts /tiny_overfit.py
Seedyai's picture
Add reproducible training bundle (src/requirements/scripts, no weights change)
2c53330 verified
Raw History Blame Contribute Delete
2.98 kB
"""Tiny overfit + forward + ckpt roundtrip smoke test (no full training)."""
import torch
from datasets import load_dataset
from torch.utils.data import DataLoader
import sys
sys.path.insert(0, ".")
from src.dataset import OpenJevFlatDataset, collate_flat_texts
from src.model import MiniClef4B
from src.utils import pick_dtype
DTYPE = pick_dtype("fp16" if torch.cuda.is_available() else "fp32")
print("loading backbone (this downloads ~8GB on first run)...")
model = MiniClef4B.create(backbone_id="Qwen/Qwen3.5-4B", dtype=DTYPE, freeze_backbone=True, max_length=512)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
print("backbone loaded, head params:", sum(p.numel() for p in model.head.parameters()))
ds = load_dataset("ZefanCai/Open-Jev", name="release-v2-redistributable", split="train[:8]")
flat = OpenJevFlatDataset(ds)
loader = DataLoader(flat, batch_size=2, collate_fn=collate_flat_texts)
batch = next(iter(loader))
print(f"batch questions={len(batch['K'])} K={batch['K']} kinds={batch['kinds']}")
out = model(batch)
print(f"forward OK loss={out['loss'].item():.4f} flat_logits={tuple(out['flat_logits'].shape)}")
# variable K/Q check
assert len(out["per_question_probs"]) == len(batch["K"])
for probs, k in zip(out["per_question_probs"], batch["K"]):
assert probs.shape[0] == k
assert abs(probs.sum().item() - 1.0) < 1e-4
print("variable K/Q OK; probs sum to 1")
# structured demo (spec example, unseen questions)
demo_state = {"text": "Customer received the wrong product and wants a refund."}
demo_schema = {"questions": [
{"id": "intent", "type": "categorical", "question": "What is the intent?", "choices": ["refund", "shipping", "complaint", "other"]},
{"id": "urgency", "type": "categorical", "question": "Urgency?", "choices": ["low", "medium", "high"]},
{"id": "escalate", "type": "boolean", "question": "Escalate?", "choices": ["yes", "no"]},
]}
pred = model.predict_structured(demo_state, demo_schema)
print("structured demo:", pred)
# ckpt roundtrip
model.save_head_only("/tmp/head_test.pt")
before = model.head.mlp[0].weight.detach().clone()
model.head.mlp[0].weight.data.zero_()
model.load_head_only("/tmp/head_test.pt", map_location="cpu")
after = model.head.mlp[0].weight.detach()
assert torch.allclose(before.cpu(), after.cpu()), "ckpt roundtrip failed"
print("ckpt save/load OK")
# tiny overfit: 8 samples, head-only, expect loss -> ~0
opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=1e-3)
model.train()
for step in range(60):
tot = 0
for b in loader:
o = model(b)
loss = o["loss"]
loss.backward()
opt.step()
opt.zero_grad()
tot += loss.item()
if step % 10 == 0:
print(f"overfit step {step} loss {tot/len(loader):.4f}")
final = tot / len(loader)
print(f"final tiny loss={final:.4f}")
assert final < 0.3, f"tiny overfit FAILED (loss {final:.4f} not close to 0)"
print("TINY OVERFIT PASSED")