Download code/common/selfplay.py from aziz9788/OvisOCR3-Arabic-workdir: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/datasets/aziz9788/OvisOCR3-Arabic-workdir/resolve/main/code/common/selfplay.py
- Command line
-
hf download hf://datasets/aziz9788/OvisOCR3-Arabic-workdir/code/common/selfplay.py
-
curl -L -o selfplay.py https://huggingface.co/datasets/aziz9788/OvisOCR3-Arabic-workdir/resolve/main/code/common/selfplay.py
7.69 kB
| """Discrepancy-aware self-play after SFT (SP-DocReader, arXiv 2610.11148). | |
| Each round: | |
| 1. The current model (the "opponent", frozen for the round) reads every training image greedily. | |
| 2. Reading Discrepancy Masking: a longest common subsequence over model tokens aligns the reading | |
| with the ground truth; the unmatched positions in each sequence are the ones still wrong. | |
| 3. The model is trained on those positions only, with their full original prefixes: | |
| Reading Discrepancy Loss softplus(beta * (delta(reading) - delta(truth))) | |
| delta(z) = sum of log p over z's unmatched tokens, minus the opponent's | |
| Focused Fidelity Loss lambda * NLL of the unmatched ground-truth tokens | |
| Pages the model already reads perfectly contribute nothing, so compute goes to the residual errors. | |
| The paper reports SFT + 3 rounds on 30k pages beating plain SFT on 120k pages (Qwen3-VL-4B). | |
| Paper settings: lambda 0.5, greedy readings, 1,024 new tokens, 3 rounds; beta is not stated (0.1 is SPIN's). | |
| python -m common.selfplay --model data/models/OvisOCR3 --adapter data/runs/ovisocr3-lora-r16 \ | |
| --train data/prepared/canonical/train.jsonl --output data/runs/ovisocr3-selfplay --rounds 3 | |
| Differences from the paper: the paper trains only a separate OCR-encoder module of DocVLM; here a | |
| LoRA adapter on the language model is trained, which works for any model in this toolkit. | |
| """ | |
| import argparse | |
| import math | |
| import random | |
| import time | |
| from pathlib import Path | |
| import torch | |
| from .vlm_utils import Codec, answer_logprobs, generate, load_policy, read_jsonl, write_jsonl, resolve_prompt | |
| def lcs_unmatched(ref, hyp): | |
| """Unmatched positions in ref and hyp after one longest-common-subsequence alignment. | |
| Walks from the start using suffix LCS lengths: equal tokens match; otherwise advance the index | |
| that keeps the longer suffix LCS, advancing the hypothesis index on ties (as in the paper). | |
| """ | |
| n, m = len(ref), len(hyp) | |
| suf = [[0] * (m + 1) for _ in range(n + 1)] | |
| for i in range(n - 1, -1, -1): | |
| row, nxt, ri = suf[i], suf[i + 1], ref[i] | |
| for j in range(m - 1, -1, -1): | |
| row[j] = nxt[j + 1] + 1 if ri == hyp[j] else max(nxt[j], row[j + 1]) | |
| i = j = 0 | |
| um_ref, um_hyp = [], [] | |
| while i < n and j < m: | |
| if ref[i] == hyp[j]: | |
| i += 1 | |
| j += 1 | |
| elif suf[i + 1][j] > suf[i][j + 1]: | |
| um_ref.append(i) | |
| i += 1 | |
| else: | |
| um_hyp.append(j) | |
| j += 1 | |
| um_ref += range(i, n) | |
| um_hyp += range(j, m) | |
| return um_ref, um_hyp | |
| def collect(model, codec, rows, max_new, device): | |
| """Opponent readings, unmatched positions and the opponent's scores at those positions.""" | |
| model.eval() | |
| recs, perfect = [], 0 | |
| for r in rows: | |
| enc = codec.prompt_inputs(r, device) | |
| y = codec.answer_ids(r["text"]) | |
| yhat = generate(model, enc, max_new, codec.end_id)[0] | |
| ey, eh = lcs_unmatched(y, yhat) | |
| if not ey and not eh: | |
| perfect += 1 | |
| continue | |
| recs.append({"row": r, "y": y, "yhat": yhat, "ey": ey, "eh": eh, | |
| "s_y": float(answer_logprobs(model, enc, y, ey).sum()), | |
| "s_h": float(answer_logprobs(model, enc, yhat, eh).sum()) if eh else 0.0}) | |
| return recs, perfect | |
| def train_round(model, codec, recs, n_total, args, device): | |
| model.train() | |
| opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=args.lr, weight_decay=0.0) | |
| steps = max(1, math.ceil(len(recs) / args.grad_accum)) | |
| sched = torch.optim.lr_scheduler.LambdaLR( | |
| opt, lambda s: min(1.0, (s + 1) / max(1, int(0.1 * steps))) * 0.5 * (1 + math.cos(math.pi * min(s, steps) / steps))) | |
| random.shuffle(recs) | |
| # Batch averaging uses every page, perfect ones included (they add no gradient), as in the paper. | |
| scale = len(recs) / max(1, n_total) | |
| log = [] | |
| for k, rec in enumerate(recs): | |
| enc = codec.prompt_inputs(rec["row"], device) | |
| s_y = answer_logprobs(model, enc, rec["y"], rec["ey"]).sum() | |
| s_h = answer_logprobs(model, enc, rec["yhat"], rec["eh"]).sum() if rec["eh"] else s_y.new_zeros(()) | |
| d_y, d_h = s_y - rec["s_y"], s_h - rec["s_h"] | |
| rdm = torch.nn.functional.softplus(args.beta * (d_h - d_y)) | |
| ffl = -s_y | |
| loss = (rdm + args.lam * ffl) * scale / args.grad_accum | |
| loss.backward() | |
| log.append((float(rdm), float(ffl))) | |
| if (k + 1) % args.grad_accum == 0 or k + 1 == len(recs): | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| sched.step() | |
| opt.zero_grad(set_to_none=True) | |
| return log | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--adapter", help="SFT LoRA adapter to start from (recommended); otherwise a new LoRA") | |
| ap.add_argument("--lora", type=int, default=16) | |
| ap.add_argument("--train", required=True, help="canonical JSONL") | |
| ap.add_argument("--output", required=True) | |
| ap.add_argument("--limit", type=int, default=0) | |
| ap.add_argument("--rounds", type=int, default=3) | |
| ap.add_argument("--beta", type=float, default=0.1) | |
| ap.add_argument("--lam", type=float, default=0.5, help="Focused Fidelity Loss weight") | |
| ap.add_argument("--lr", type=float, default=5e-5) | |
| ap.add_argument("--grad-accum", type=int, default=4) | |
| ap.add_argument("--max-new", type=int, default=1024) | |
| ap.add_argument("--prompt", help="prompt for page records (default: the page prompt from data_prep); lines keep the line prompt") | |
| ap.add_argument("--prompt-file", help="read the page prompt from a file (e.g. a model's prompts/*.txt)") | |
| ap.add_argument("--max-pixels", type=int, default=1280 * 1280) | |
| ap.add_argument("--dtype", choices=["auto", "bf16", "fp16", "fp32"], default="auto") | |
| ap.add_argument("--gradient-checkpointing", action="store_true") | |
| ap.add_argument("--seed", type=int, default=0) | |
| a = ap.parse_args(argv) | |
| a.prompt = resolve_prompt(a.prompt, a.prompt_file) | |
| random.seed(a.seed) | |
| torch.manual_seed(a.seed) | |
| model, processor, dtype = load_policy(a.model, a.adapter, a.lora, a.dtype, a.gradient_checkpointing) | |
| device = next(model.parameters()).device | |
| codec = Codec(processor, a.prompt, a.max_pixels) | |
| rows = read_jsonl(a.train, a.limit) | |
| out = Path(a.output) | |
| history = [] | |
| for t in range(a.rounds): | |
| t0 = time.time() | |
| recs, perfect = collect(model, codec, rows, a.max_new, device) | |
| unmatched = sum(len(r["ey"]) for r in recs) | |
| print(f"round {t + 1}: {perfect}/{len(rows)} read perfectly, {unmatched} unmatched truth tokens", flush=True) | |
| if not recs: | |
| print("nothing left to correct; stopping") | |
| break | |
| log = train_round(model, codec, recs, len(rows), a, device) | |
| rdm = sum(x for x, _ in log) / len(log) | |
| ffl = sum(y for _, y in log) / len(log) | |
| history.append({"round": t + 1, "perfect": perfect, "pages": len(rows), "unmatched_truth_tokens": unmatched, | |
| "rdm_loss": rdm, "ffl_loss": ffl, "sec": round(time.time() - t0, 1)}) | |
| print(history[-1], flush=True) | |
| model.save_pretrained(out / f"round{t + 1}") | |
| processor.save_pretrained(out / f"round{t + 1}") | |
| write_jsonl(out / "history.jsonl", history) | |
| if torch.cuda.is_available(): | |
| print(f"peak GPU memory: {torch.cuda.max_memory_allocated() / 1e9:.2f} GB") | |
| if __name__ == "__main__": | |
| main() | |