File size: 11,409 Bytes
24aaa76 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | """VLMB generic fine-tune loop for VLMs that need their maker's code (amendment 3.2 C1, rule 0.11).
One adapter per model (adapters/ad_<short>.py) loads the pinned maker code and turns (images, texts) into a loss
and greedy predictions. This loop is model-independent: AdamW, cosine schedule with 3% warm-up, effective batch 32
by gradient accumulation, bf16 autocast over fp32 master weights, gradient checkpointing, a wall-time cap, checkpoints
every N minutes that resume exactly (model, optimizer, scheduler, step, samples seen, RNG, cumulative train time).
The sample sequence is a TSV (columns id, image, text, unit at least) read in row order; sample k of the run is row
k mod len. Every arm reads the same file, so every arm sees the same sequence.
usage: vlmb_train.py --short S --model-dir D --seq SEQ.tsv --out OUTDIR --lr LR [--samples 150000] [--eff-batch 32]
[--micro-batch 8] [--max-hours 3.0] [--ckpt-minutes 30] [--steps N] [--save-at-step K --exit-after-save]
[--device cuda|cpu] [--threads N] [--seed 20261121]
"""
import argparse
import hashlib
import importlib
import json
import math
import os
import random
import shutil
import sys
import time
from datetime import datetime, timezone
for k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
os.environ.pop(k, None)
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
os.environ.setdefault("PYTHONDONTWRITEBYTECODE", "1")
ap = argparse.ArgumentParser()
ap.add_argument("--short", required=True)
ap.add_argument("--model-dir", required=True)
ap.add_argument("--seq", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--lr", type=float, required=True)
ap.add_argument("--lr-source", default="")
ap.add_argument("--samples", type=int, default=150000)
ap.add_argument("--eff-batch", type=int, default=32)
ap.add_argument("--micro-batch", type=int, default=8)
ap.add_argument("--max-hours", type=float, default=3.0)
ap.add_argument("--ckpt-minutes", type=float, default=30.0)
ap.add_argument("--steps", type=int, default=0, help="stop after this many optimizer steps (smoke test)")
ap.add_argument("--save-at-step", type=int, default=0)
ap.add_argument("--exit-after-save", action="store_true")
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--seed", type=int, default=20261121)
ap.add_argument("--warmup-frac", type=float, default=0.03)
ap.add_argument("--weight-decay", type=float, default=0.0)
ap.add_argument("--max-grad-norm", type=float, default=1.0)
ap.add_argument("--no-gc", action="store_true", help="disable gradient checkpointing")
ap.add_argument("--precision", default="amp_bf16", choices=["amp_bf16", "pure_bf16"])
args = ap.parse_args()
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import torch # noqa: E402
from PIL import Image # noqa: E402
if args.threads:
torch.set_num_threads(args.threads)
dev = torch.device(args.device)
use_cuda = dev.type == "cuda"
os.makedirs(args.out, exist_ok=True)
LOG = os.path.join(args.out, "train_log.jsonl")
CK = os.path.join(args.out, "ckpt_last")
def now():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def log(rec):
rec = dict(rec, utc=now())
with open(LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
print(json.dumps(rec, ensure_ascii=False), flush=True)
# ---- sample sequence -------------------------------------------------------------------------------------------
rows = []
with open(args.seq, encoding="utf-8", newline="") as f:
hdr = f.readline().rstrip("\n").split("\t")
ci = {h: i for i, h in enumerate(hdr)}
for line in f:
p = line.rstrip("\n").split("\t")
rows.append((p[ci["id"]], p[ci["image"]], p[ci["text"]], p[ci["unit"]] if "unit" in ci else ""))
seq_sha = hashlib.sha256(open(args.seq, "rb").read()).hexdigest()
assert rows, "empty sequence"
total_steps = math.ceil(args.samples / args.eff_batch)
accum = max(1, args.eff_batch // args.micro_batch)
assert accum * args.micro_batch == args.eff_batch, "eff batch must be a multiple of the micro batch"
warmup = max(1, int(round(args.warmup_frac * total_steps)))
def lr_at(step): # step = number of optimizer steps already taken
if step < warmup:
return args.lr * (step + 1) / warmup
prog = (step - warmup) / max(1, total_steps - warmup)
return args.lr * 0.5 * (1.0 + math.cos(math.pi * min(1.0, prog)))
# ---- model ------------------------------------------------------------------------------------------------------
t_load = time.time()
ad_mod = importlib.import_module("adapters.ad_" + args.short)
adapter = ad_mod.Adapter(args.model_dir, dev, args.precision)
model = adapter.model
model.train()
if not args.no_gc:
adapter.enable_gradient_checkpointing()
params = [p for p in model.parameters() if p.requires_grad]
n_train = sum(p.numel() for p in {id(p): p for p in params}.values())
n_all = sum(p.numel() for p in {id(p): p for p in model.parameters()}.values())
opt = torch.optim.AdamW(params, lr=args.lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=args.weight_decay,
fused=use_cuda)
state = {"step": 0, "samples_seen": 0, "train_seconds": 0.0, "ckpt_saves": 0, "resumed_from": []}
if os.path.exists(os.path.join(CK, "state.json")):
st = json.load(open(os.path.join(CK, "state.json")))
sd = torch.load(os.path.join(CK, "model.pt"), map_location="cpu", weights_only=True)
missing, unexpected = model.load_state_dict(sd, strict=False)
assert not missing and not unexpected, f"resume mismatch {missing[:5]} {unexpected[:5]}"
del sd
opt.load_state_dict(torch.load(os.path.join(CK, "optim.pt"), map_location="cpu", weights_only=True))
rng = torch.load(os.path.join(CK, "rng.pt"), map_location="cpu", weights_only=False)
torch.set_rng_state(rng["torch"])
if use_cuda and rng.get("cuda") is not None:
torch.cuda.set_rng_state(rng["cuda"])
random.setstate(rng["py"])
state.update(st)
state["resumed_from"] = st.get("resumed_from", []) + [st["step"]]
chk = sum(float(p.detach().float().double().sum()) for p in params[:50])
log({"event": "resumed", "step": state["step"], "samples_seen": state["samples_seen"],
"param_checksum_first50": chk, "saved_checksum_first50": st.get("param_checksum_first50")})
else:
random.seed(args.seed)
torch.manual_seed(args.seed)
log({"event": "start", "short": args.short, "model_dir": args.model_dir, "lr": args.lr,
"lr_source": args.lr_source, "samples_target": args.samples, "eff_batch": args.eff_batch,
"micro_batch": args.micro_batch, "accum": accum, "total_steps": total_steps, "warmup_steps": warmup,
"max_hours": args.max_hours, "precision": args.precision, "grad_ckpt": not args.no_gc,
"seq": args.seq, "seq_sha256": seq_sha, "seq_rows": len(rows), "params_all": n_all,
"params_trainable": n_train, "seed": args.seed, "torch": torch.__version__,
"transformers": __import__("transformers").__version__, "device": str(dev),
"gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "job": os.environ.get("SLURM_JOB_ID", ""),
"adapter_notes": getattr(adapter, "NOTES", "")})
log({"event": "loaded", "load_seconds": round(time.time() - t_load, 1)})
def save_ckpt(final=False):
t0 = time.time()
tmp = CK + ".tmp"
if os.path.exists(tmp):
shutil.rmtree(tmp)
os.makedirs(tmp)
torch.save(model.state_dict(), os.path.join(tmp, "model.pt"))
torch.save(opt.state_dict(), os.path.join(tmp, "optim.pt"))
torch.save({"torch": torch.get_rng_state(), "cuda": torch.cuda.get_rng_state() if use_cuda else None,
"py": random.getstate()}, os.path.join(tmp, "rng.pt"))
st = dict(state)
st["param_checksum_first50"] = sum(float(p.detach().float().double().sum()) for p in params[:50])
st["saved_utc"] = now()
json.dump(st, open(os.path.join(tmp, "state.json"), "w"), indent=1)
if os.path.exists(CK):
shutil.rmtree(CK)
os.rename(tmp, CK)
state["ckpt_saves"] += 1
log({"event": "ckpt_saved", "step": state["step"], "samples_seen": state["samples_seen"],
"seconds": round(time.time() - t0, 1), "final": final})
def load_batch(start, n):
ims, txs, ids = [], [], []
for k in range(start, start + n):
rid, path, text, _ = rows[k % len(rows)]
ims.append(Image.open(path).convert("RGB"))
txs.append(text)
ids.append(rid)
return ims, txs, ids
# ---- train ------------------------------------------------------------------------------------------------------
cap_s = args.max_hours * 3600.0
last_ck = time.time()
stop_reason = None
if use_cuda:
torch.cuda.reset_peak_memory_stats()
while True:
if state["samples_seen"] >= args.samples:
stop_reason = "reached_P"
break
if state["train_seconds"] >= cap_s:
stop_reason = "time_cap"
break
if args.steps and state["step"] >= args.steps:
stop_reason = "steps_limit"
break
t0 = time.time()
lr = lr_at(state["step"])
for g in opt.param_groups:
g["lr"] = lr
opt.zero_grad(set_to_none=True)
tot_loss, tot_tok = 0.0, 0
for a in range(accum):
ims, txs, _ = load_batch(state["samples_seen"] + a * args.micro_batch, args.micro_batch)
loss, ntok = adapter.loss(ims, txs)
(loss / accum).backward()
tot_loss += float(loss.detach()) / accum
tot_tok += int(ntok)
gn = torch.nn.utils.clip_grad_norm_(params, args.max_grad_norm)
opt.step()
if use_cuda:
torch.cuda.synchronize()
state["step"] += 1
state["samples_seen"] += args.eff_batch
dt = time.time() - t0
state["train_seconds"] += dt
if state["step"] <= 20 or state["step"] % 10 == 0:
log({"event": "step", "step": state["step"], "samples_seen": state["samples_seen"], "loss": round(tot_loss, 5),
"target_tokens": tot_tok, "grad_norm": round(float(gn), 4), "lr": lr, "step_seconds": round(dt, 3),
"train_seconds": round(state["train_seconds"], 1),
"peak_mem_gib": round(torch.cuda.max_memory_allocated() / 2**30, 2) if use_cuda else None})
if not math.isfinite(tot_loss):
stop_reason = "nonfinite_loss"
break
if args.save_at_step and state["step"] == args.save_at_step:
save_ckpt()
if args.exit_after_save:
log({"event": "exit_after_save", "step": state["step"]})
sys.exit(0)
elif time.time() - last_ck >= args.ckpt_minutes * 60:
save_ckpt()
last_ck = time.time()
save_ckpt(final=True)
flags = []
if stop_reason == "time_cap" and state["samples_seen"] < args.samples:
flags.append("short of P")
json.dump({"short": args.short, "stop_reason": stop_reason, "flags": flags, "step": state["step"],
"samples_seen": state["samples_seen"], "train_seconds": round(state["train_seconds"], 1),
"lr": args.lr, "lr_source": args.lr_source, "seq_sha256": seq_sha, "updated_utc": now()},
open(os.path.join(args.out, "train_summary.json"), "w"), indent=1)
log({"event": "done", "stop_reason": stop_reason, "flags": flags, "step": state["step"],
"samples_seen": state["samples_seen"]})
|