OvisOCR3-Arabic-workdir / code /common /select_data.py
aziz9788's picture
Initial commit
cf8c8d4
Raw History Blame Contribute Delete
6.19 kB
"""Choose which training records to spend compute on. Writes a canonical JSONL subset.
Modes (combine them by running one after another):
sieve drop records whose label is structurally broken: empty, unclosed tags or math, ragged tables,
a decoding loop in the label (FireRed-OCR's rule-based "sieve"; DADC's consistency filters).
hard keep the records the current model gets most wrong, from a common.vlm_infer predictions file.
Records above --max-cer are dropped as likely label noise, not hard cases (FireRed routes
those to review; MinerU-Diffusion's hard-sample stage and SP-DocReader also train on residual errors).
entropy keep the records where the model is least certain of the ground-truth tokens (mean token
entropy under teacher forcing). FD-RL picks its RL set the same way from rollouts
(top 50% of 16k candidates); teacher forcing is a cheaper proxy that needs no sampling.
balance cap each source (and level) so no single source dominates; rare sources keep everything
(FireRed-OCR's stratified sampling).
python -m common.select_data sieve --input train.jsonl --out train.clean.jsonl
python -m common.select_data hard --input train.jsonl --preds runs/ovisocr3_train.jsonl --keep 0.3 --out hard.jsonl
python -m common.select_data entropy --input train.jsonl --model data/models/OvisOCR3 --adapter runs/lora --keep 0.5 --out grpo.jsonl
python -m common.select_data balance --input train.jsonl --per-source 5000 --out balanced.jsonl
"""
import argparse
import random
from collections import defaultdict
import torch
from .rewards import r_closure, r_table
from .score import cer, has_loop, norm
from .vlm_utils import read_jsonl, write_jsonl, resolve_prompt
def sieve(rows):
kept, why = [], defaultdict(int)
for r in rows:
t = r.get("text", "")
reason = ("empty" if not t.strip() else "unclosed" if r_closure(t) < 1 else
"ragged_table" if r_table(t) < 1 else "loop" if has_loop(t) else None)
if reason:
why[reason] += 1
else:
kept.append(r)
print("dropped:", dict(why))
return kept
def hard(rows, preds_path, keep, max_cer, min_cer):
preds = {p["id"]: p for p in read_jsonl(preds_path) if "pred" in p}
scored = []
for r in rows:
p = preds.get(r["id"])
if p is None:
continue
c = cer(norm(p["pred"]), norm(r["text"]))
if min_cer <= c <= max_cer:
scored.append((c, r))
scored.sort(key=lambda x: -x[0])
n = int(len(scored) * keep) if keep <= 1 else int(keep)
print(f"{len(preds)} predictions, {len(scored)} within CER [{min_cer}, {max_cer}], keeping {n}")
return [r for _, r in scored[:n]]
@torch.no_grad()
def entropy(rows, model_path, adapter, keep, max_pixels, prompt):
from .vlm_utils import Codec, load_policy, with_answer
model, processor, _ = load_policy(model_path, adapter, 8)
model.eval()
device = next(model.parameters()).device
codec = Codec(processor, prompt, max_pixels)
scored = []
for r in rows:
enc = codec.prompt_inputs(r, device)
y = codec.answer_ids(r["text"])
inputs, L0 = with_answer(enc, y)
keep_idx = torch.arange(L0 - 1, L0 - 1 + len(y), device=device)
logp = torch.log_softmax(model(**inputs, logits_to_keep=keep_idx, use_cache=False).logits[0].float(), -1)
h = float(-(logp.exp() * logp).sum(-1).mean())
scored.append((h, r))
scored.sort(key=lambda x: -x[0])
n = int(len(scored) * keep) if keep <= 1 else int(keep)
print(f"mean entropy: top {scored[0][0]:.3f}, median {scored[len(scored) // 2][0]:.3f}; keeping {n}")
return [r for _, r in scored[:n]]
def balance(rows, per_source, seed):
groups = defaultdict(list)
for r in rows:
groups[(r.get("source"), r.get("level"))].append(r)
rng = random.Random(seed)
out = []
for key, rs in sorted(groups.items(), key=lambda kv: str(kv[0])):
rng.shuffle(rs)
out += rs[:per_source]
print(f"{key}: {len(rs)} -> {min(len(rs), per_source)}")
rng.shuffle(out)
return out
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("mode", choices=["sieve", "hard", "entropy", "balance"])
ap.add_argument("--input", required=True, help="canonical JSONL")
ap.add_argument("--out", required=True)
ap.add_argument("--preds", help="hard: predictions JSONL from common.vlm_infer on the same records")
ap.add_argument("--keep", type=float, default=0.3, help="fraction (<=1) or count (>1) to keep")
ap.add_argument("--max-cer", type=float, default=0.6, help="hard: above this, treat as label noise")
ap.add_argument("--min-cer", type=float, default=0.0)
ap.add_argument("--model", help="entropy: model path")
ap.add_argument("--adapter", help="entropy: LoRA adapter of the model to score with")
ap.add_argument("--max-pixels", type=int, default=1280 * 1280)
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("--per-source", type=int, default=5000, help="balance: cap per (source, level)")
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args(argv)
a.prompt = resolve_prompt(a.prompt, a.prompt_file)
rows = read_jsonl(a.input)
if a.mode == "sieve":
out = sieve(rows)
elif a.mode == "hard":
if not a.preds:
ap.error("hard needs --preds")
out = hard(rows, a.preds, a.keep, a.max_cer, a.min_cer)
elif a.mode == "entropy":
if not a.model:
ap.error("entropy needs --model")
out = entropy(rows, a.model, a.adapter, a.keep, a.max_pixels, a.prompt)
else:
out = balance(rows, a.per_source, a.seed)
write_jsonl(a.out, out)
print(f"{len(rows)} -> {len(out)} records: {a.out}")
if __name__ == "__main__":
main()