code for H200 job
Browse filesFiles changed (12)
- README.mdAdded+11
- code/build_data.pyAdded+394
- code/build_mm_hf.pyAdded+335
- code/build_text2.pyAdded+148
- code/build_text3.pyAdded+134
- code/build_text4.pyAdded+211
- code/demos.pyAdded+202
- code/media.pyAdded+59
- code/mmjev.pyAdded+836
- code/mmjev_eval.pyAdded+200
- code/pipeline.pyAdded+315
- code/train.pyAdded+328
1234567891011# omnijev-work — training workspace (work in progress)
Code, logs, results and training checkpoints of **OmniJev / MM-Jev**: Jev-style typed decisions(`noul` / `choice` / `score`) on Gemma 3n E4B with text, image, audio and video states.This is a scratch workspace synced by the training job; the finished model is published separately.
* `code/` – training / evaluation code (MM-Jev architecture: option tree in one pass, KV-share truncation, modality exit + latent memory, sibling bridge, MatFormer width slicing)* `run/` – pipeline log, results.json, checkpoints (LoRA + decision heads + latents)
Base model: google/gemma-3n-E4B-it (Gemma terms of use apply to derivatives).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394"""Build the MM-Jev train / eval sets and cache the frozen tower features (run inside the Colab kernel, `jev` loaded).
Every record: dict(task, modality, state=[Seg with cached features], q=question dict, y=gold option index, raw=raw mediafor the latency subset or None). Tower features are cached once (the towers are frozen), so training runs the LM only."""import io, json, random, time, urllib.requestimport numpy as np, torchfrom datasets import load_datasetfrom mmjev import Seg, options_offrom media import shapes_image, beeps, moving_video, COLORS, SHAPES
rng = random.Random(0)nrng = np.random.default_rng(0)LOG = open("/content/build.log", "a")
def log(*a): print(*a, file=LOG, flush=True)
N_RAW = 12 # eval items per task that keep raw media for end-to-end latency
IMG_GRID, FRAME_GRID = 8, 4 # cache grids at the resolution the LM consumes (64 / 16 tokens): 16x / 64x less RAM
def img_feat(images, grid=IMG_GRID): g = jev.vision_tower_features(images).float() return torch.nn.functional.avg_pool2d(g, g.shape[-1] // grid).half().cpu()
def aud_feat(clips): out = [] for s in range(0, len(clips), 16): out += [a.cpu() for a in jev.audio_tower_features(clips[s:s + 16])] return out
def finish(recs, kind): """Batch-encode media of records whose state holds raw media, keep raw for the first N_RAW eval items.""" for split in ("train", "eval"): rs = [r for r in recs if r["split"] == split] for i, r in enumerate(rs): r["raw"] = [Seg(s.kind, s.data, s.audio, s.fps) for s in r["state"]] if (split == "eval" and i < N_RAW) else None if kind == "image": for s in range(0, len(recs), 32): chunk = recs[s:s + 32] f = img_feat([r["state"][0].data for r in chunk]) for r, x in zip(chunk, f): r["state"][0] = Seg("image", x) elif kind == "audio": for s in range(0, len(recs), 64): chunk = recs[s:s + 64] f = aud_feat([r["state"][0].data for r in chunk]) for r, x in zip(chunk, f): r["state"][0] = Seg("audio", x) elif kind == "video": for r in recs: sg = r["state"][0] fr = img_feat(sg.data, FRAME_GRID) au = aud_feat([sg.audio])[0] if sg.audio is not None else None r["state"][0] = Seg("video", fr, au, sg.fps) return recs
def rec(task, mod, split, state, q, y, target=None): """One state, one or more questions. y: gold option index per question; target: soft distribution per question.""" qs = q if isinstance(q, list) else [q] ys = [int(v) for v in (y if isinstance(y, list) else [y])] if target is None: target = [[1.0 if i == yy else 0.0 for i in range(len(options_of(qq)[0]))] for qq, yy in zip(qs, ys)] return dict(task=task, modality=mod, split=split, state=state, qs=qs, ys=ys, targets=target)
# ------------------------------------------------------------------------------------------ textdef build_text(n_tr=500, n_ev=200): out = [] b = load_dataset("google/boolq") for split, ds, n in (("train", b["train"], n_tr), ("eval", b["validation"], n_ev)): for ex in ds.shuffle(seed=0).select(range(n)): q = ex["question"].strip().capitalize() + "?" out.append(rec("boolq", "text", split, [Seg("text", ex["passage"])], {"type": "noul", "instructions": f"Based on the passage: {q}"}, int(ex["answer"]))) db = load_dataset("fancyzhx/dbpedia_14") names = db["train"].features["label"].names crit = {n.lower(): "" for n in names} for split, ds, n in (("train", db["train"], n_tr), ("eval", db["test"], n_ev)): for ex in ds.shuffle(seed=0).select(range(n)): out.append(rec("dbpedia14", "text", split, [Seg("text", ex["title"] + ". " + ex["content"])], {"type": "choice", "instructions": "Which category does this entity belong to?", "criteria": crit}, ex["label"])) sst = load_dataset("SetFit/sst5") levels = ["very negative", "negative", "neutral", "positive", "very positive"] for split, ds, n in (("train", sst["train"], n_tr), ("eval", sst["test"], n_ev)): for ex in ds.shuffle(seed=0).select(range(n)): out.append(rec("sst5", "text", split, [Seg("text", "Review: " + ex["text"])], {"type": "score", "instructions": "How positive is the sentiment of this review?", "criteria": levels}, ex["label"])) for r in out: r["raw"] = None return out
def build_jevbench(): base = "https://raw.githubusercontent.com/fstandhartinger/jevbench/main/datasets/public/" out = [] for tier in ("easy", "original", "hard"): for line in urllib.request.urlopen(base + f"{tier}.jsonl", timeout=60).read().decode().splitlines(): if not line.strip(): continue t = json.loads(line) q, st = t["question"], t["state"] st = st if isinstance(st, str) else json.dumps(st, ensure_ascii=False) crit = q.get("criteria") if q["type"] == "noul": crit = crit or {} qq = {"type": "noul", "instructions": q["instructions"], "criteria": {"yes": crit.get("true", "yes"), "no": crit.get("false", "no")}} exp = str(t["expected"]).lower() y = 1 if exp in ("true", "yes", "1") else 0 elif q["type"] == "score": qq = {"type": "score", "instructions": q["instructions"], "criteria": list(crit)} y = int(t["expected"]) else: qq = {"type": "choice", "instructions": q["instructions"], "criteria": {k: (v or "") for k, v in (crit or {}).items()} if isinstance(crit, dict) else {k: "" for k in (crit or t["labels"])}} y = list(qq["criteria"]).index(str(t["expected"])) r = rec(f"jevbench_{tier}", "text", "eval", [Seg("text", st)], qq, y) r["family"] = t.get("family"); r["raw"] = None out.append(r) return out
# ------------------------------------------------------------------------------------------ imagedef build_image(n_ok=(800, 300), n_pope=(600, 300), n_cnt=(400, 150)): out = [] ok = load_dataset("HuggingFaceM4/A-OKVQA") for split, ds, n in (("train", ok["train"], n_ok[0]), ("eval", ok["validation"], n_ok[1])): for ex in ds.shuffle(seed=0).select(range(n)): out.append(rec("aokvqa", "image", split, [Seg("image", ex["image"].convert("RGB"))], {"type": "choice", "instructions": ex["question"], "criteria": {c: "" for c in ex["choices"]}}, ex["correct_choice_idx"])) pope = load_dataset("lmms-lab/POPE", split="test").shuffle(seed=0) imgs = sorted(set(pope["image_source"])) rng.shuffle(imgs) ev_imgs = set(imgs[: len(imgs) // 4]) ctr = {"train": 0, "eval": 0} for ex in pope: split = "eval" if ex["image_source"] in ev_imgs else "train" if ctr[split] >= (n_pope[1] if split == "eval" else n_pope[0]): continue ctr[split] += 1 out.append(rec("pope", "image", split, [Seg("image", ex["image"].convert("RGB"))], {"type": "noul", "instructions": ex["question"]}, int(ex["answer"].strip().lower() == "yes"))) if all(ctr[s] >= (n_pope[1] if s == "eval" else n_pope[0]) for s in ctr): break words = ["zero", "one", "two", "three", "four", "five"] for split, n in (("train", n_cnt[0]), ("eval", n_cnt[1])): for _ in range(n): k = rng.randint(0, 5) objs, tries = [], 0 while len(objs) < k and tries < 200: tries += 1 cx, cy, r_ = rng.uniform(0.12, 0.88), rng.uniform(0.12, 0.88), rng.uniform(0.05, 0.1) if all((cx - o[2]) ** 2 + (cy - o[3]) ** 2 > (r_ + o[4] + 0.03) ** 2 for o in objs): objs.append((rng.choice(SHAPES), rng.choice(list(COLORS)), cx, cy, r_)) out.append(rec("count_syn", "image", split, [Seg("image", shapes_image(objs, size=768))], {"type": "score", "instructions": "How many shapes are in the image?", "criteria": words}, len(objs))) return finish(out, "image")
# ------------------------------------------------------------------------------------------ audiodef build_audio(n_ch=(600, 200), n_no=(500, 200), n_bp=(300, 120)): import librosa esc = load_dataset("ashraq/esc50", split="train") cats = sorted(set(esc["category"])) pretty = lambda c: c.replace("_", " ") clips = {"train": [], "eval": []} for ex in esc: a = ex["audio"] y16 = librosa.resample(np.asarray(a["array"], np.float32), orig_sr=a["sampling_rate"], target_sr=16000) clips["eval" if ex["fold"] == 5 else "train"].append((y16, ex["category"])) out = [] for split in ("train", "eval"): pool = clips[split] idx = rng.sample(range(len(pool)), min(len(pool), n_ch[0] if split == "train" else n_ch[1])) for i in idx: y, c = pool[i] opts = [c] + rng.sample([x for x in cats if x != c], 4) rng.shuffle(opts) out.append(rec("esc50_choice", "audio", split, [Seg("audio", y)], {"type": "choice", "instructions": "Which sound is in the recording?", "criteria": {pretty(o): "" for o in opts}}, opts.index(c))) idx = rng.sample(range(len(pool)), min(len(pool), n_no[0] if split == "train" else n_no[1])) for j, i in enumerate(idx): y, c = pool[i] pos = j % 2 == 0 ask = c if pos else rng.choice([x for x in cats if x != c]) out.append(rec("esc50_noul", "audio", split, [Seg("audio", y)], {"type": "noul", "instructions": f"Does the recording contain the sound of {pretty(ask)}?"}, int(pos))) words = ["zero", "one", "two", "three", "four", "five"] for split, n in (("train", n_bp[0]), ("eval", n_bp[1])): for _ in range(n): k = rng.randint(0, 5) out.append(rec("beeps_count", "audio", split, [Seg("audio", beeps(k, freq=rng.choice([440.0, 660.0, 880.0, 1200.0]), rng=nrng))], {"type": "score", "instructions": "How many beeps are in the audio?", "criteria": words}, k)) return finish(out, "audio")
# ------------------------------------------------------------------------------------------ videoclass _VidList(list): """Encodes each video record as soon as it is appended; keeps raw frames only for the first N_RAW eval items.""" def __init__(self): super().__init__(); self.n_eval = {}
def append(self, r): k = r["task"] keep_raw = r["split"] == "eval" and self.n_eval.get(k, 0) < N_RAW if r["split"] == "eval": self.n_eval[k] = self.n_eval.get(k, 0) + 1 sg = r["state"][0] r["raw"] = [Seg(sg.kind, sg.data, sg.audio, sg.fps)] if keep_raw else None au = aud_feat([sg.audio])[0] if sg.audio is not None else None r["state"][0] = Seg("video", img_feat(sg.data, FRAME_GRID), au, sg.fps) super().append(r)
def build_video(n_dir=(300, 120), n_chg=(250, 100), n_fl=(250, 100), n_av=(200, 80)): out = _VidList() dirs = ["left", "right", "up", "down"] col = list(COLORS) for split, n in (("train", n_dir[0]), ("eval", n_dir[1])): for _ in range(n): d, c, s = rng.choice(dirs), rng.choice(col), rng.choice(SHAPES) fr = moving_video(s, c, d, size=768, rng=nrng) out.append(rec("vid_direction", "video", split, [Seg("video", fr, fps=2.0)], {"type": "choice", "instructions": f"In which direction does the {c} {s} move?", "criteria": {x: "" for x in dirs}}, dirs.index(d))) for split, n in (("train", n_chg[0]), ("eval", n_chg[1])): for j in range(n): c, s = rng.choice(col), rng.choice(SHAPES) chg = j % 2 == 0 fr = moving_video(s, c, rng.choice(dirs), size=768, rng=nrng, change_to=rng.choice([x for x in col if x != c]) if chg else None) out.append(rec("vid_color_change", "video", split, [Seg("video", fr, fps=2.0)], {"type": "noul", "instructions": f"Does the {s} change its colour during the video?"}, int(chg))) for split, n in (("train", n_fl[0]), ("eval", n_fl[1])): for _ in range(n): k = rng.randint(0, 3) fr = moving_video(rng.choice(SHAPES), rng.choice(col), rng.choice(dirs), size=768, flashes=k, rng=nrng) out.append(rec("vid_flash_count", "video", split, [Seg("video", fr, fps=2.0)], {"type": "score", "instructions": "How many times does the background flash bright yellow?", "criteria": ["never", "once", "twice", "three times"]}, k)) for split, n in (("train", n_av[0]), ("eval", n_av[1])): for j in range(n): has = j % 2 == 0 fr = moving_video(rng.choice(SHAPES), rng.choice(col), rng.choice(dirs), size=768, rng=nrng) au = beeps(rng.randint(1, 4), rng=nrng) if has else beeps(0, rng=nrng) out.append(rec("vid_av_beep", "video", split, [Seg("video", fr, audio=au, fps=2.0)], {"type": "noul", "instructions": "Can beeping tones be heard in the video's soundtrack?"}, int(has))) return list(out)
# ------------------------------------------------------------------------------------------ public benchmarksdef build_typed_decisions(): """LocalLLaMA/typed-decisions: 1,200 train cases (6,000 decisions) and 400 test cases (2,000 decisions), gold = teacher distributions. Scored exactly like the Laya notebook.""" out = [] for split, hf in (("train", "train"), ("eval", "test")): for row in load_dataset("LocalLLaMA/typed-decisions", "all", split=hf): state = json.loads(row["state"]); qd = json.loads(row["questions"]); gold = json.loads(row["gold"]) st = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False) qs, ys, tg, names = [], [], [], [] for qid, q in qd.items(): g, t, crit = gold[qid], q["type"], q.get("criteria") if t == "noul": crit = crit or {} qq = {"type": "noul", "instructions": q["instructions"], "criteria": {"no": crit.get("false", "no"), "yes": crit.get("true", "yes")}} pt = float(g.get("noul", g.get("probabilities", {}).get("true", 0.5))) dist = [1 - pt, pt] y = int(str(g["label"]).lower() == "true") elif t == "score": crit = list(crit) if isinstance(crit, list) else [str(i) for i in range(4)] qq = {"type": "score", "instructions": q["instructions"], "criteria": crit} dist = [float(g.get("probabilities", {}).get(str(i), 0.0)) for i in range(len(crit))] y = int(g.get("label", round(g.get("score", 0)))) else: keys = list(crit) qq = {"type": "choice", "instructions": q["instructions"], "criteria": {k: (crit[k] or "") for k in keys}} dist = [float(g.get("probabilities", {}).get(k, 0.0)) for k in keys] y = keys.index(str(g["label"])) ssum = sum(dist) dist = [d / ssum for d in dist] if ssum > 0 else [1 / len(dist)] * len(dist) qs.append(qq); ys.append(y); tg.append(dist); names.append(qid) r = rec("typed_decisions", "text", split, [Seg("text", st)], qs, ys, tg) r.update(workflow=row["workflow"], qnames=names, gold=gold, qraw=qd, raw=None) out.append(r) return out
def build_btzsc(seed=20260917, n=100): """AbdelStark/jev-benchmarks pilot-v1 protocol: btzsc/btzsc @ fef2a2a, 100 class-balanced test examples per set.""" import random as _r from collections import defaultdict out = [] for off, (name, task) in enumerate((("agnews", "topic"), ("emotiondair", "emotion"), ("banking77", "intent"))): rows = load_dataset("btzsc/btzsc", name=name, split="test", revision="fef2a2ac62b69c58670047dddf045c53d7c3cb5e") binary = [int(v) for v in rows["labels"]]; texts = [str(v) for v in rows["text"]] k = next(i for i in range(1, len(texts)) if texts[i] != texts[0]) labels = [str(rows[i]["hypothesis"]) for i in range(k)] vidx, targets = [], [] for si in range(len(rows) // k): v = binary[si * k:(si + 1) * k] if sum(v) == 1: vidx.append(si); targets.append(v.index(1)) by = defaultdict(list) for i, t in enumerate(targets): by[t].append(i) rr = _r.Random(seed + off) for v in by.values(): rr.shuffle(v) chosen = [] while len(chosen) < min(n, len(targets)): prog = False for c in sorted(by): if by[c] and len(chosen) < n: chosen.append(by[c].pop()); prog = True if not prog: break for pos in sorted(chosen): si = vidx[pos] r = rec(f"btzsc_{name}", "text", "eval", [Seg("text", texts[si * k])], {"type": "choice", "instructions": "Which single label best describes the input text?", "criteria": {l: "" for l in labels}}, targets[pos]) r["raw"] = None out.append(r) return out
def build_massive_xnli(n_intent=500, n_xnli=1000): out = [] for lang in ("en", "ko"): ds = load_dataset("mteb/amazon_massive_scenario", lang, split="test") labels = sorted(set(ds["label_text"])) crit = {l.replace("_", " "): "" for l in labels} for ex in ds: r = rec(f"massive_scenario_{lang}", "text", "eval", [Seg("text", ex["text"])], {"type": "choice", "instructions": "Which scenario (domain) does this user request belong to?", "criteria": crit}, labels.index(ex["label_text"])) r["raw"] = None; out.append(r) ds = load_dataset("mteb/amazon_massive_intent", "en", split="test").shuffle(seed=0) labels = sorted(set(ds["label_text"])) crit = {l.replace("_", " "): "" for l in labels} for ex in ds.select(range(n_intent)): r = rec("massive_intent_en", "text", "eval", [Seg("text", ex["text"])], {"type": "choice", "instructions": "Which intent does this user request express?", "criteria": crit}, labels.index(ex["label_text"])) r["raw"] = None; out.append(r) x = load_dataset("facebook/xnli", "en", split="test").shuffle(seed=0).select(range(n_xnli)) names = ["entailment", "neutral", "contradiction"] for ex in x: r = rec("xnli_en", "text", "eval", [Seg("text", f"Premise: {ex['premise']}\nHypothesis: {ex['hypothesis']}")], {"type": "choice", "instructions": "What is the relation between the premise and the hypothesis?", "criteria": {"entailment": "the premise implies the hypothesis", "neutral": "the premise neither implies nor contradicts the hypothesis", "contradiction": "the premise contradicts the hypothesis"}}, ex["label"]) r["raw"] = None; out.append(r) return out
if globals().get("RUN_BUILD_MAIN", True): t0 = time.time() DATA = globals().get("DATA", {}) for name, fn in (("text", build_text), ("jevbench", build_jevbench), ("typed", build_typed_decisions), ("btzsc", build_btzsc), ("massive_xnli", build_massive_xnli), ("text2", lambda: (exec(open("/content/build_text2.py").read(), globals()), DATA["text2"])[1]), ("image", build_image), ("audio", build_audio), ("video", build_video)): try: _ = DATA[name]; log(f"[{name}] cached"); continue except (NameError, KeyError): pass t1 = time.time() DATA[name] = fn() import gc; gc.collect() log(f"[{name}] {len(DATA[name])} records in {time.time() - t1:.0f}s") torch.save(DATA, "/content/mmjev_data.pt") log(f"DONE {sum(len(v) for v in DATA.values())} records, {time.time() - t0:.0f}s")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335"""Multimodal train / eval records from public Hugging Face datasets only (no synthetic media).
image : A-OKVQA, POPE (from base.pt) + ScienceQA-IMG, AI2D, VQAv2-small (yes/no -> noul, how-many -> score, other -> choice)audio : ESC-50 (from the audio part) + Clotho-AQA (yes/no), UrbanSound8K (fold 10 held out), Speech Commands v0.02video : TempCompass (multi-choice / yes-no / caption matching, split by video), MV-Bench-mini, UCF101-subset, Kinetics-mini
Features are cached at the grid the LM consumes (image 8x8 -> 64 tokens, video frame 4x4 -> 16 tokens); a few eval itemsper task keep their raw media for end-to-end latency and demo cards. Builders take `jev` and return record lists."""import glob, io, os, random, re, subprocess, tarfile, zipfileimport numpy as np, torchfrom datasets import Audio, load_datasetfrom huggingface_hub import hf_hub_download, snapshot_downloadfrom mmjev import Seg
N_RAW = 12IMG_GRID, FRAME_GRID = 8, 4
def _rec(task, mod, split, state, qs, ys): qs = qs if isinstance(qs, list) else [qs] ys = ys if isinstance(ys, list) else [ys] from mmjev import options_of tg = [[1.0 if i == y else 0.0 for i in range(len(options_of(q)[0]))] for q, y in zip(qs, ys)] return dict(task=task, modality=mod, split=split, state=state, qs=qs, ys=ys, targets=tg, raw=None)
def _img_feats(jev, ims, grid=IMG_GRID): g = jev.vision_tower_features(ims).float() return torch.nn.functional.avg_pool2d(g, g.shape[-1] // grid).half().cpu()
def _encode_images(jev, recs): """Replace PIL images in record states by cached grids; keep raw for the first N_RAW eval items of each task.""" cnt = {} for r in recs: if r["split"] == "eval": cnt[r["task"]] = cnt.get(r["task"], 0) + 1 if cnt[r["task"]] <= N_RAW: r["raw"] = [Seg(s.kind, s.data) for s in r["state"]] for s in range(0, len(recs), 32): chunk = recs[s:s + 32] f = _img_feats(jev, [r["state"][0].data.convert("RGB") for r in chunk]) for r, x in zip(chunk, f): r["state"][0] = Seg("image", x) return recs
def _letters(opts): return {o: "" for o in opts} if len(set(opts)) == len(opts) else {f"{chr(65 + i)}. {o}": "" for i, o in enumerate(opts)}
# ------------------------------------------------------------------------------------------ imagedef scienceqa(jev, n_tr=1500, n_ev=500): out = [] for split, hf, n in (("train", "train", n_tr), ("eval", "test", n_ev)): ds = load_dataset("lmms-lab/ScienceQA-IMG", split=hf).shuffle(seed=0) k = 0 for ex in ds: if k >= n: break if ex["image"] is None: continue opts = eval(ex["choices"]) if isinstance(ex["choices"], str) else list(ex["choices"]) q = ex["question"] + (f"\nHint: {ex['hint']}" if ex.get("hint") else "") crit = _letters([str(o) for o in opts]) out.append(_rec("scienceqa_img", "image", split, [Seg("image", ex["image"])], {"type": "choice", "instructions": q, "criteria": crit}, int(ex["answer"]))); k += 1 return _encode_images(jev, out)
def ai2d(jev, n_ev=600): ds = load_dataset("lmms-lab-encoder/ai2d", split="test").shuffle(seed=0) out = [] for i, ex in enumerate(ds): opts = eval(ex["options"]) if isinstance(ex["options"], str) else list(ex["options"]) split = "eval" if i < n_ev else "train" out.append(_rec("ai2d", "image", split, [Seg("image", ex["image"])], {"type": "choice", "instructions": ex["question"], "criteria": _letters([str(o) for o in opts])}, int(ex["answer"]))) return _encode_images(jev, out)
def vqav2(jev, n=6000, eval_frac=0.15, seed=0): rng = random.Random(seed) ds = load_dataset("merve/vqav2-small", split="validation").shuffle(seed=seed).select(range(n)) qtype = lambda q: " ".join(q.lower().split()[:3]) pool = {} for ex in ds: pool.setdefault(qtype(ex["question"]), []).append(ex["multiple_choice_answer"]) out = [] for i, ex in enumerate(ds): split = "eval" if i < n * eval_frac else "train" q, a = ex["question"], str(ex["multiple_choice_answer"]).strip().lower() st = [Seg("image", ex["image"])] if a in ("yes", "no"): out.append(_rec("vqav2_yesno", "image", split, st, {"type": "noul", "instructions": q}, int(a == "yes"))) elif q.lower().startswith("how many") and a.isdigit() and int(a) <= 10: out.append(_rec("vqav2_count", "image", split, st, {"type": "score", "instructions": q, "criteria": [str(k) for k in range(11)]}, int(a))) else: cands = [x for x in set(pool[qtype(q)]) if x != a] if len(cands) < 3: continue opts = [a] + rng.sample(cands, 3); rng.shuffle(opts) out.append(_rec("vqav2_other", "image", split, st, {"type": "choice", "instructions": q, "criteria": {o: "" for o in opts}}, opts.index(a))) return _encode_images(jev, out)
# ------------------------------------------------------------------------------------------ audiodef _decode(a, sr=16000): import soundfile as sf, librosa y, s = sf.read(io.BytesIO(a["bytes"]), dtype="float32", always_2d=False) if y.ndim > 1: y = y.mean(1) return librosa.resample(y, orig_sr=s, target_sr=sr) if s != sr else y
def _encode_audio(jev, recs): cnt = {} for r in recs: if r["split"] == "eval": cnt[r["task"]] = cnt.get(r["task"], 0) + 1 if cnt[r["task"]] <= N_RAW: r["raw"] = [Seg("audio", r["state"][0].data)] for s in range(0, len(recs), 32): chunk = recs[s:s + 32] feats = jev.audio_tower_features([r["state"][0].data[:16000 * 30] for r in chunk]) for r, f in zip(chunk, feats): r["state"][0] = Seg("audio", f.cpu()) return recs
def clotho_aqa(jev, n_tr=1500, n_ev=400): out = [] for split, pat, n in (("train", "clotho_aqa_val_filtered-*", n_tr), ("eval", "clotho_aqa_test_filtered-*", n_ev)): files = f"hf://datasets/lmms-lab-audio/ClothoAQA/clotho_aqa/{pat}.parquet" ds = load_dataset("parquet", data_files=files, split="train") acol = next(c for c in ds.column_names if "audio" in c.lower() or c in ("context",)) ds = ds.cast_column(acol, Audio(decode=False)).shuffle(seed=0) qcol = next(c for c in ds.column_names if "question" in c.lower()) anscol = next(c for c in ds.column_names if c.lower() in ("answer", "answers", "label")) k = 0 for ex in ds: if k >= n: break a = str(ex[anscol]).strip().lower() if a not in ("yes", "no"): continue out.append(_rec("clotho_aqa", "audio", split, [Seg("audio", _decode(ex[acol]))], {"type": "noul", "instructions": ex[qcol]}, int(a == "yes"))); k += 1 return _encode_audio(jev, out)
def urbansound(jev, shards=6, n_tr=1500, n_ev=400): files = sorted(f for f in [s.rfilename for s in __import__("huggingface_hub").HfApi().dataset_info("danavery/urbansound8K").siblings] if f.endswith(".parquet"))[:shards] ds = load_dataset("parquet", data_files=[f"hf://datasets/danavery/urbansound8K/{f}" for f in files], split="train") ds = ds.cast_column("audio", Audio(decode=False)).shuffle(seed=0) classes = sorted(set(ds["class"])) crit = {c.replace("_", " "): "" for c in classes} out, k = [], {"train": 0, "eval": 0} for ex in ds: split = "eval" if str(ex["fold"]) == "10" else "train" if k[split] >= (n_ev if split == "eval" else n_tr): continue out.append(_rec("urbansound8k", "audio", split, [Seg("audio", _decode(ex["audio"]))], {"type": "choice", "instructions": "Which sound is in the recording?", "criteria": crit}, classes.index(ex["class"]))); k[split] += 1 return _encode_audio(jev, out)
def speech_commands(jev, n_tr=1500, n_ev=400): out = [] for split, pat, n in (("train", "data/train/train-00000-of-*.parquet", n_tr), ("eval", "data/test/test-00000-of-*.parquet", n_ev)): ds = load_dataset("parquet", data_files=f"hf://datasets/pollen-robotics/speech-commands-v0.02/{pat}", split="train") ds = ds.cast_column("audio", Audio(decode=False)).shuffle(seed=0) words = sorted(set(ds["label"]) - {"_background_noise_", "_silence_", "_unknown_"}) crit = {w: "" for w in words} k = 0 for ex in ds: if k >= n: break if ex["label"] not in crit: continue out.append(_rec("speech_commands", "audio", split, [Seg("audio", _decode(ex["audio"]))], {"type": "choice", "instructions": "Which word is spoken in the recording?", "criteria": crit}, words.index(ex["label"]))); k += 1 return _encode_audio(jev, out)
# ------------------------------------------------------------------------------------------ videodef _frames(path, n=8): import cv2 from PIL import Image cap = cv2.VideoCapture(path) tot = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0 fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 if tot <= 0: return None, None idx = np.linspace(0, tot - 1, n).round().astype(int) out = [] for i in idx: cap.set(cv2.CAP_PROP_POS_FRAMES, int(i)) ok, fr = cap.read() if ok: out.append(Image.fromarray(fr[:, :, ::-1])) cap.release() if len(out) < 2: return None, None eff_fps = (len(out) - 1) / max((idx[-1] - idx[0]) / fps, 1e-3) return out, eff_fps
def _video_rec(jev, task, split, path, qs, ys, keep_raw): fr, fps = _frames(path) if fr is None: return None r = _rec(task, "video", split, [Seg("video", _img_feats(jev, fr, FRAME_GRID), None, fps)], qs, ys) if keep_raw: r["raw"] = [Seg("video", fr, None, fps)] return r
def _parse_mc(text, kind): """TempCompass question text -> (instructions, options).""" lines = text.split("\n") if kind == "mc": opts = [re.sub(r"^[A-Z]\.\s*", "", l).strip() for l in lines[1:] if re.match(r"^[A-Z]\.", l)] return lines[0], opts opts = [re.sub(r"^Option \d+:\s*", "", l).strip() for l in lines[1:] if l.startswith("Option")] return lines[0], opts
def tempcompass(jev, eval_frac=0.25): root = "/content/pipe/raw/tempcompass" if not os.path.exists(root): z = hf_hub_download("lmms-eval/TempCompass", "tempcompass_videos.zip", repo_type="dataset") zipfile.ZipFile(z).extractall(root) vids = {os.path.splitext(os.path.basename(p))[0]: p for p in glob.glob(f"{root}/**/*.mp4", recursive=True)} per = {} for cfg, kind in (("multi-choice", "mc"), ("caption_matching", "cm"), ("yes_no", "yn")): for ex in load_dataset("lmms-eval/TempCompass", cfg, split="test"): vid = str(ex["video_id"]) if vid not in vids: continue if kind == "yn": a = str(ex["answer"]).strip().lower() if a not in ("yes", "no"): continue per.setdefault(vid, []).append(({"type": "noul", "instructions": ex["question"]}, int(a == "yes"))) else: ins, opts = _parse_mc(ex["question"], kind) ans = re.sub(r"^([A-Z]\.|Option \d+:)\s*", "", str(ex["answer"])).strip() if ans not in opts or len(set(opts)) != len(opts): continue per.setdefault(vid, []).append(({"type": "choice", "instructions": ins, "criteria": {o: "" for o in opts}}, opts.index(ans))) keys = sorted(per); random.Random(0).shuffle(keys) n_ev = int(len(keys) * eval_frac) out = [] for i, vid in enumerate(keys): split = "eval" if i < n_ev else "train" qa = per[vid] for s in range(0, len(qa), 4): # up to 4 questions per state / call chunk = qa[s:s + 4] r = _video_rec(jev, "tempcompass", split, vids[vid], [q for q, _ in chunk], [y for _, y in chunk], keep_raw=split == "eval" and i < N_RAW) if r: out.append(r) return out
def mvbench_mini(jev, eval_frac=0.25): import csv root = snapshot_download("firstep-ai/MV-Bench-mini", repo_type="dataset") rows = list(csv.DictReader(open(f"{root}/resampled_data.csv", encoding="utf-8-sig"))) random.Random(0).shuffle(rows) out = [] for i, r in enumerate(rows): path = os.path.join(root, r["relpath"]) if not os.path.exists(path): continue opts = [str(o) for o in eval(r["candidates"])] if r["answer"] not in opts or len(set(opts)) != len(opts): continue split = "eval" if i < len(rows) * eval_frac else "train" rec = _video_rec(jev, "mvbench_mini", split, path, {"type": "choice", "instructions": r["question"], "criteria": {o: "" for o in opts}}, opts.index(r["answer"]), keep_raw=split == "eval" and i < N_RAW) if rec: out.append(rec) return out
def ucf101_subset(jev): root = "/content/pipe/raw/ucf" if not os.path.exists(root): tarfile.open(hf_hub_download("sayakpaul/ucf101-subset", "UCF101_subset.tar.gz", repo_type="dataset")).extractall(root) paths = glob.glob(f"{root}/**/*.avi", recursive=True) cls = lambda p: os.path.basename(os.path.dirname(p)) classes = sorted(set(cls(p) for p in paths)) crit = {re.sub(r"(?<!^)([A-Z])", r" \1", c).lower(): "" for c in classes} out, n_raw = [], 0 for p in sorted(paths): split = "eval" if "/test/" in p else "train" if "/train/" in p else "eval" r = _video_rec(jev, "ucf101", split, p, {"type": "choice", "instructions": "Which action is shown in the video?", "criteria": crit}, classes.index(cls(p)), keep_raw=split == "eval" and n_raw < N_RAW) if r: n_raw += int(r["raw"] is not None) out.append(r) return out
def kinetics_mini(jev, eval_frac=0.25): root = snapshot_download("nateraw/kinetics-mini", repo_type="dataset") paths = sorted(glob.glob(f"{root}/**/*.mp4", recursive=True)) cls = lambda p: os.path.basename(os.path.dirname(p)) classes = sorted(set(cls(p) for p in paths)) crit = {c.replace("_", " "): "" for c in classes} random.Random(0).shuffle(paths) out = [] for i, p in enumerate(paths): split = "eval" if i < len(paths) * eval_frac else "train" r = _video_rec(jev, "kinetics_mini", split, p, {"type": "choice", "instructions": "Which activity is shown in the video?", "criteria": crit}, classes.index(cls(p)), keep_raw=split == "eval" and i < N_RAW) if r: out.append(r) return out
BUILDERS = {"scienceqa": scienceqa, "ai2d": ai2d, "vqav2": vqav2, "clotho_aqa": clotho_aqa, "urbansound": urbansound, "speech_commands": speech_commands, "tempcompass": tempcompass, "mvbench_mini": mvbench_mini, "ucf101": ucf101_subset, "kinetics_mini": kinetics_mini}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Extra TEXT training data, disjoint from every benchmark we report (no AG News, DAIR Emotion, Banking77, MASSIVE,XNLI, JevBench, typed-decisions). Appended to DATA["text2"] (train split only)."""import random, tracebackfrom datasets import load_datasetfrom mmjev import Seg
rng = random.Random(1)out = []
def add(task, state, q, y): r = rec(task, "text", "train", [Seg("text", state)], q, y) r["raw"] = None out.append(r)
def safe(fn): try: fn() except Exception: log("text2 skip", fn.__name__, traceback.format_exc()[-300:])
def mnli(n=900): ds = load_dataset("nyu-mll/multi_nli", split="train").shuffle(seed=1).select(range(n)) crit = {"entailment": "the premise implies the hypothesis", "neutral": "the premise neither implies nor contradicts the hypothesis", "contradiction": "the premise contradicts the hypothesis"} for i, ex in enumerate(ds): if ex["label"] not in (0, 1, 2): continue st = f"Premise: {ex['premise']}\nHypothesis: {ex['hypothesis']}" if i % 2: add("mnli", st, {"type": "choice", "instructions": "What is the relation between the premise and the hypothesis?", "criteria": crit}, ex["label"]) else: add("mnli", st, {"type": "noul", "instructions": "Does the premise imply the hypothesis?"}, int(ex["label"] == 0))
def clinc(n=700): ds = load_dataset("clinc/clinc_oos", "plus", split="train").shuffle(seed=1) names = ds.features["intent"].names ds = ds.filter(lambda e: names[e["intent"]] != "oos").select(range(n)) for ex in ds: k = rng.choice([8, 16, 32, 64, 100]) gold = names[ex["intent"]] opts = [gold] + rng.sample([x for x in names if x not in (gold, "oos")], k - 1) rng.shuffle(opts) add("clinc150", ex["text"], {"type": "choice", "instructions": "Which single label best describes the input text?", "criteria": {o.replace("_", " "): "" for o in opts}}, opts.index(gold))
def goemo(n=700): ds = load_dataset("google-research-datasets/go_emotions", "simplified", split="train").shuffle(seed=1) names = ds.features["labels"].feature.names ds = ds.filter(lambda e: len(e["labels"]) == 1 and names[e["labels"][0]] != "neutral").select(range(n)) for ex in ds: gold = names[ex["labels"][0]] k = rng.choice([6, 10, 27]) opts = [gold] + rng.sample([x for x in names if x not in (gold, "neutral")], k - 1) rng.shuffle(opts) add("goemotions", ex["text"], {"type": "choice", "instructions": "Which emotion does the text express?", "criteria": {o: "" for o in opts}}, opts.index(gold))
def yahoo(n=500): ds = load_dataset("community-datasets/yahoo_answers_topics", split="train").shuffle(seed=1).select(range(n)) names = ds.features["topic"].names for ex in ds: st = f"Question: {ex['question_title']} {ex['question_content']}\nAnswer: {ex['best_answer']}"[:1500] add("yahoo_topics", st, {"type": "choice", "instructions": "Which topic is this post about?", "criteria": {x: "" for x in names}}, ex["topic"])
def yelp(n=500): ds = load_dataset("Yelp/yelp_review_full", split="train").shuffle(seed=1).select(range(n)) lv = ["1 star, terrible", "2 stars, poor", "3 stars, average", "4 stars, good", "5 stars, excellent"] for ex in ds: add("yelp", ex["text"][:1500], {"type": "score", "instructions": "What star rating does this review give?", "criteria": lv}, ex["label"])
def policies(n=600): """JevBench-style bounded policy checks, programmatic gold.""" rules = [("a receipt is provided", "the customer has a receipt", "the customer has no receipt"), ("the purchase was made within 30 days", "the purchase was 12 days ago", "the purchase was 45 days ago"), ("the item is unused", "the item is unopened", "the item has been used"), ("the account is verified", "the account is verified", "the account is not verified"), ("the amount is below $500", "the amount is $120", "the amount is $1,300"), ("a manager approved it", "a manager approved it", "no manager approval was given"), ("the request comes from the account owner", "the account owner made the request", "a third party made the request")] actions = ["issue a refund", "approve the transfer", "grant the exception", "release the order"] for _ in range(n): rs = rng.sample(rules, rng.randint(2, 3)) ok = [rng.random() < 0.7 for _ in rs] facts = [r[1] if o else r[2] for r, o in zip(rs, ok)] rng.shuffle(facts) act = rng.choice(actions) st = (f"Policy: we {act} only if " + " and ".join(r[0] for r in rs) + ". Case: " + "; ".join(facts) + ".") if rng.random() < 0.5: add("policy_syn", st, {"type": "noul", "instructions": f"Under the stated policy, may we {act}?"}, int(all(ok))) else: n_ok = sum(ok) add("policy_syn", st, {"type": "choice", "instructions": "What should happen under the policy?", "criteria": {"allow": "every condition holds", "deny": "at least one condition fails"}}, 0 if all(ok) else 1)
def snake(n=400): """Snake-game states (demo task, disclosed in the card); gold = safe move that best approaches the food, ties broken by free space (flood fill).""" import sys; sys.path.insert(0, "/content") from demos import Snake, DIRS, OPP def space(g, d): hx, hy = g.body[0]; start = (hx + DIRS[d][0], hy + DIRS[d][1]) seen, st, blocked = {start}, [start], set(g.body[:-1]) while st and len(seen) < 60: x, y = st.pop() for dx, dy in DIRS.values(): c = (x + dx, y + dy) if 0 <= c[0] < g.n and 0 <= c[1] < g.n and c not in blocked and c not in seen: seen.add(c); st.append(c) return len(seen) def best(g): hx, hy = g.body[0]; fx, fy = g.food cand = [d for d in DIRS if d != OPP[g.dir] and not g.blocked(d)] if not cand: return None return max(cand, key=lambda d: (space(g, d) >= len(g.body), -(abs(fx - hx - DIRS[d][0]) + abs(fy - hy - DIRS[d][1])), space(g, d))) made = 0 for seed in range(10_000): g = Snake(seed=seed) while g.alive and made < n and g.steps < 120: b = best(g) if b is None: break if rng.random() < 0.35: q = g.question() add("snake_syn", g.state_text(), q, list(q["criteria"]).index(b)); made += 1 g.step(b if rng.random() > 0.1 else rng.choice([d for d in DIRS if d != OPP[g.dir]])) if made >= n: break
for f in (mnli, clinc, goemo, yahoo, yelp, policies, snake): safe(f)DATA["text2"] = out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Public Jev-style typed-decision corpora for training (DATA["text3"], train split only), decontaminated: * tasksource/procedural-typed-decisions (Apache-2.0): structured states, several typed questions, exact labels * n4ze3m/typed-decisions-synth (MIT): 149 domains, multi-question, soft teacher labels * tasksource/tasksource-jev-typed-decisions: real labels from 670 sources -- every source that overlaps a benchmark we report (AG News, emotion, Banking77, MASSIVE, XNLI, JevBench, typed-decisions) is excludedEvery candidate whose state matches an eval state (normalised prefix hash) is dropped as well."""import hashlib, json, random, refrom datasets import load_dataset, get_dataset_config_namesfrom mmjev import Seg, options_of
rng = random.Random(7)BANNED_SRC = re.compile(r"ag_?news|emotion|banking|massive|xnli|jev|typed|clinc|amazon_massive", re.I)
def norm(t): return hashlib.md5(re.sub(r"\s+", " ", str(t).lower())[:300].encode()).hexdigest()
EVAL_HASH = {norm(s.data) for v in DATA.values() for r in v if r["split"] == "eval" for s in r["state"] if s.kind == "text"}out, dropped = [], {"contaminated": 0, "banned_source": 0, "bad": 0}
def convert_q(q): t, crit = q["type"], q.get("criteria") if t == "noul": c = crit or {} return {"type": "noul", "instructions": q["instructions"], "criteria": {"no": c.get("false", "no"), "yes": c.get("true", "yes")}} if t == "score": return {"type": "score", "instructions": q["instructions"], "criteria": [str(x) for x in crit]} if isinstance(crit, list): crit = {str(x): "" for x in crit} return {"type": "choice", "instructions": q["instructions"], "criteria": {str(k): str(v or "") for k, v in crit.items()}}
def soft_target(qq, ans): labels, _ = options_of(qq) if qq["type"] == "noul": p = float(ans.get("noul", ans.get("probabilities", {}).get("true", 0.5)) if isinstance(ans, dict) else ans) return [1 - p, p] pr = ans.get("probabilities", {}) if isinstance(ans, dict) else {} v = [float(pr.get(l, 0.0)) for l in labels] if sum(v) <= 0 and isinstance(ans, dict) and "choice" in ans and ans["choice"] in labels: v = [1.0 if l == ans["choice"] else 0.0 for l in labels] s = sum(v) return [x / s for x in v] if s > 0 else None
def add_case(task, state, qs, answers): if norm(state) in EVAL_HASH: dropped["contaminated"] += 1; return Q, Y, T = [], [], [] for qid, q in qs.items(): try: qq = convert_q(q); tg = soft_target(qq, answers[qid]) except Exception: tg = None if tg is None or len(tg) < 2 or len(tg) > 80: continue Q.append(qq); T.append(tg); Y.append(int(max(range(len(tg)), key=lambda i: tg[i]))) if not Q: dropped["bad"] += 1; return r = rec(task, "text", "train", [Seg("text", state[:4000])], Q[:6], Y[:6], T[:6]) r["raw"] = None out.append(r)
def procedural(per_cfg=160): for cfg in get_dataset_config_names("tasksource/procedural-typed-decisions"): ds = load_dataset("tasksource/procedural-typed-decisions", cfg, split="train").shuffle(seed=7) for ex in ds.select(range(min(per_cfg, len(ds)))): add_case(f"procedural:{cfg}", ex["state"], json.loads(ex["questions"]), json.loads(ex["answers"]))
def synth(n=1800): ds = load_dataset("json", data_files="hf://datasets/n4ze3m/typed-decisions-synth/data/train.jsonl", split="train") for ex in ds.shuffle(seed=7).select(range(min(n, len(ds)))): st = ex["state"] if isinstance(ex["state"], str) else json.dumps(ex["state"], ensure_ascii=False) add_case("typed_synth", st, json.loads(ex["questions"]) if isinstance(ex["questions"], str) else ex["questions"], json.loads(ex["teacher"]) if isinstance(ex["teacher"], str) else ex["teacher"])
def tasksource(n=2500): ds = load_dataset("tasksource/tasksource-jev-typed-decisions", split="train", streaming=True).shuffle(seed=7, buffer_size=20000) got = 0 for ex in ds: if got >= n: break if BANNED_SRC.search(ex["source"] or ""): dropped["banned_source"] += 1; continue try: opts = json.loads(ex["options"]) if ex["options"] else [] tgt = json.loads(ex["target"]) except Exception: continue kind, st = ex["kind"], ex["state"] or "" if len(st) > 3000 or norm(st) in EVAL_HASH: dropped["contaminated" if norm(st) in EVAL_HASH else "bad"] += 1; continue if kind == "noul": p = float(tgt[-1] if isinstance(tgt, list) else tgt) q = {"type": "noul", "instructions": ex["question"]}; t = [1 - p, p] elif kind in ("choice", "score") and 2 <= len(opts) <= 40 and len(tgt) == len(opts): if kind == "score": q = {"type": "score", "instructions": ex["question"], "criteria": [str(o)[:120] for o in opts]} elif max(len(str(o)) for o in opts) > 60: # long options: letter labels, text as criterion keys = [chr(65 + i) for i in range(len(opts))] q = {"type": "choice", "instructions": ex["question"], "criteria": {k: str(o)[:300] for k, o in zip(keys, opts)}} else: q = {"type": "choice", "instructions": ex["question"], "criteria": {str(o): "" for o in opts}} if len(q["criteria"]) != len(opts): continue t = [float(x) for x in tgt]; s = sum(t) if s <= 0: continue t = [x / s for x in t] else: continue r = rec(f"tasksource:{ex['source'].split('/')[0]}", "text", "train", [Seg("text", st)], q, int(max(range(len(t)), key=lambda i: t[i])), [t]) r["raw"] = None out.append(r); got += 1
for f in (procedural, synth, tasksource): try: f() log(f"[text3] {f.__name__}: total {len(out)} dropped {dropped}") except Exception: import traceback log(f"[text3] {f.__name__} FAILED {traceback.format_exc()[-600:]}")DATA["text3"] = outlog(f"[text3] DONE {len(out)} records, dropped {dropped}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211"""Large public typed-decision corpora -> MM-Jev train records. Each builder returns a list of records; pipeline.py cachesevery part to disk, so a crash / disconnect only redoes the part in flight.
Benchmark sources are removed by name (tasksource): AG News, emotion (DAIR), Banking77, MASSIVE, XNLI."""import ast, json, random, refrom datasets import load_datasetfrom mmjev import Seg, options_of
BANNED = re.compile(r"(^|/)(ag_news|emotion|banking77|massive|xnli)(/|$)|multilingual/massive|multilingual/xnli", re.I)MAX_OPTS, MAX_STATE = 100, 3500
def _rec(task, state, qs, targets): ys = [int(max(range(len(t)), key=lambda i: t[i])) for t in targets] return dict(task=task, modality="text", split="train", state=[Seg("text", str(state)[:MAX_STATE])], qs=qs, ys=ys, targets=targets, raw=None)
def _norm(t): t = [max(0.0, float(x)) for x in t] s = sum(t) return [x / s for x in t] if s > 0 else None
def _parse(x): if isinstance(x, (list, dict)): return x try: return json.loads(x) except Exception: return ast.literal_eval(x)
def row_question(kind, question, options, target): """Row-schema (Open-Jev / SargeDev / tasksource): options list + target distribution -> (question, target).""" options = [str(o) for o in options] if kind == "noul" and len(target) == 1: target = [1 - float(target[0]), float(target[0])] options = ["false", "true"] target = _norm(target) if target is None or len(options) != len(target) or not (2 <= len(options) <= MAX_OPTS): return None if kind == "noul": p = target[-1] if len(target) == 2 else target[0] return {"type": "noul", "instructions": question}, [1 - p, p] if kind == "score": return {"type": "score", "instructions": question, "criteria": [o[:160] for o in options]}, target crit = {} for i, o in enumerate(options): if ": " in o and len(o.split(": ", 1)[0]) <= 40: k, v = o.split(": ", 1) elif len(o) > 60: k, v = f"option {i + 1}", o else: k, v = o, "" crit[k.strip()] = v[:300] if len(crit) != len(options): return None return {"type": "choice", "instructions": question, "criteria": crit}, target
def grouped_rows(rows, task, n_groups, rng, state_key="state_json"): groups = {} for r in rows: groups.setdefault(r["group_id"], []).append(r) keys = list(groups); rng.shuffle(keys) out = [] for g in keys[:n_groups]: qs, ts, st = [], [], None for r in groups[g][:6]: st = st if st is not None else _parse(r[state_key]) if r[state_key] else "" got = row_question(r["kind"], r["question"], _parse(r["options"]), _parse(r["target"])) if got: qs.append(got[0]); ts.append(got[1]) if qs: st = st if isinstance(st, str) else json.dumps(st, ensure_ascii=False) out.append(_rec(task, st, qs, ts)) return out
def openjev_v11(n_ctrl=5000, n_wanli=1500, seed=11): rng = random.Random(seed) ds = load_dataset("ZefanCai/Open-Jev-v1.1", "community-hard-mix-v2-redistributable", split="train") rows = ds.to_list() wanli = [r for r in rows if "wanli" in (r["source"] or "").lower()] ctrl = [r for r in rows if "wanli" not in (r["source"] or "").lower()] return grouped_rows(ctrl, "openjev_v11", n_ctrl, rng) + grouped_rows(wanli, "openjev_v11_wanli", n_wanli, rng)
def openjev_v2(n=3000, seed=12): ds = load_dataset("ZefanCai/Open-Jev", "release-v2-redistributable", split="train") return grouped_rows(ds.to_list(), "openjev_v2", n, random.Random(seed))
def bev(cfgs=(("default", 4000), ("hard_50k", 3000), ("numeric_temporal", 1500), ("skills", 2000)), seed=13): out = [] for cfg, n in cfgs: ds = load_dataset("avbiswas/bev-decision", cfg, split="train").shuffle(seed=seed).select(range(n)) for ex in ds: qs_raw = _parse(ex["questions_json"]) qs, ts = [], [] for qid, q in list(qs_raw.items())[:6]: t, crit, lab = q["type"], q.get("criteria"), q.get("label") if t == "noul": p = float(lab) if isinstance(lab, (int, float)) and not isinstance(lab, bool) else float(bool(lab)) qs.append({"type": "noul", "instructions": q["instructions"]}); ts.append([1 - p, p]) elif t == "score": crit = list(crit) lv = int(lab) if lab is not None else 0 if not (0 <= lv < len(crit)): continue qs.append({"type": "score", "instructions": q["instructions"], "criteria": [str(c) for c in crit]}) ts.append([1.0 if i == lv else 0.0 for i in range(len(crit))]) else: crit = crit if isinstance(crit, dict) else {str(c): "" for c in crit} keys = list(crit) if str(lab) not in keys or not (2 <= len(keys) <= MAX_OPTS): continue qs.append({"type": "choice", "instructions": q["instructions"], "criteria": {k: str(v or "") for k, v in crit.items()}}) ts.append([1.0 if k == str(lab) else 0.0 for k in keys]) if qs: out.append(_rec(f"bev:{cfg}", ex["state"], qs, ts)) return out
def tasksource(n=7000, shards=(0, 4, 8), many_frac=0.45, seed=14): """Non-streaming shards (the streaming shuffle walks whole shards); benchmark sources dropped by name; rows with >= 10 options over-sampled so the K distribution covers intent-style label spaces.""" rng = random.Random(seed) files = [f"hf://datasets/tasksource/tasksource-jev-typed-decisions/data/train-{i:05d}-of-00012.parquet" for i in shards] ds = load_dataset("parquet", data_files=files, split="train") ds = ds.filter(lambda b: [not BANNED.search(s or "") for s in b["source"]], batched=True) many, few = [], [] for ex in ds.shuffle(seed=seed).select(range(min(len(ds), 60000))): try: opts = _parse(ex["options"]) if ex["options"] else ["false", "true"] tgt = _parse(ex["target"]) except Exception: continue got = row_question(ex["kind"], ex["question"], opts, tgt if isinstance(tgt, list) else [1 - tgt, tgt]) if not got: continue r = _rec(f"tasksource:{(ex['source'] or '?').split('/')[0]}", ex["state"] or "", [got[0]], [got[1]]) (many if len(got[1]) >= 10 else few).append(r) k_many = min(len(many), int(n * many_frac)) return rng.sample(many, k_many) + rng.sample(few, min(len(few), n - k_many))
def jev_decisions(n=2000, seed=15): """Agent tool / action choice: candidates -> options, target candidate -> gold.""" rng = random.Random(seed) ds = load_dataset("samatv256/jev-decisions-v1", split="validation", streaming=True) out, seen = [], 0 for ex in ds: seen += 1 if seen > 60000 or len(out) >= n: break if ex["status"] != "trainable" or rng.random() > 0.25: continue try: cands = _parse(ex["candidates"]); tgt = _parse(ex["target"]) except Exception: continue if not (2 <= len(cands) <= 40) or not isinstance(tgt, dict) or not tgt.get("candidate_id"): continue keys = [c.get("name") or c.get("id") for c in cands] ids = [c.get("id") for c in cands] if tgt["candidate_id"] not in ids or len(set(keys)) != len(keys): continue crit = {k: str(c.get("description") or "")[:200] for k, c in zip(keys, cands)} st = ex["state"] if isinstance(ex["state"], str) else json.dumps(ex["state"], ensure_ascii=False) st = st[-MAX_STATE:] # keep the most recent part of long agent traces g = ids.index(tgt["candidate_id"]) out.append(_rec(f"jev_decisions:{ex['decision_type']}", st, [{"type": "choice", "instructions": "Which action or tool should the agent use next?", "criteria": crit}], [[1.0 if i == g else 0.0 for i in range(len(keys))]])) return out
def sargedev(n_v3=15000, n_v1=4000, seed=16): ds = load_dataset("json", data_files="hf://datasets/SargeDev/jev-distill-corpus-v3/train.jsonl", split="train") rng = random.Random(seed) by = {"yuri_v3": [], "yuri_v1": []} for i, s in enumerate(ds["source"]): if s in by: by[s].append(i) idx = rng.sample(by["yuri_v3"], min(n_v3, len(by["yuri_v3"]))) + rng.sample(by["yuri_v1"], min(n_v1, len(by["yuri_v1"]))) out = [] for ex in ds.select(idx): got = row_question(ex["kind"], ex["question"], ex["options"], ex["target"]) if got: out.append(_rec(f"sargedev:{ex['source']}", ex["state"], [got[0]], [got[1]])) return out
def clinc_full(n=1200, seed=17): """CLINC150 with the FULL 150-intent label space (K matched to many-label intent routing).""" ds = load_dataset("clinc/clinc_oos", "plus", split="train").shuffle(seed=seed) names = ds.features["intent"].names labels = [x for x in names if x != "oos"] ds = ds.filter(lambda e: names[e["intent"]] != "oos").select(range(n)) crit = {x.replace("_", " "): "" for x in labels} keys = list(crit) return [_rec("clinc150_full", ex["text"], [{"type": "choice", "instructions": "Which single label best describes the input text?", "criteria": crit}], [[1.0 if k == names[ex["intent"]].replace("_", " ") else 0.0 for k in keys]]) for ex in ds]
BUILDERS = {"openjev_v11": openjev_v11, "openjev_v2": openjev_v2, "bev": bev, "tasksource": tasksource, "jev_decisions": jev_decisions, "sargedev": sargedev, "clinc_full": clinc_full}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Model-card demos (run in the Colab kernel with the trained `jev`).
snake_demo : the model plays Snake from a TEXT state, one `choice` decision per tick; per-move latency overlaid.image/audio/video demos : several typed questions answered in ONE pass over a held-out sample, rendered as cards."""import os, time, random, subprocessimport numpy as np, torchfrom PIL import Image, ImageDraw, ImageFontfrom mmjev import Seg
OUT = "/content/demo_assets"os.makedirs(OUT, exist_ok=True)
def font(sz): for p in ("/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"): if os.path.exists(p): return ImageFont.truetype(p, sz) return ImageFont.load_default()
# ------------------------------------------------------------------------------------------ snakeDIRS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}OPP = {"up": "down", "down": "up", "left": "right", "right": "left"}
class Snake: def __init__(self, n=12, seed=0): self.n, self.rng = n, random.Random(seed) c = n // 2 self.body = [(c, c), (c - 1, c), (c - 2, c)] self.dir, self.alive, self.score, self.steps = "right", True, 0, 0 self.place_food()
def place_food(self): free = [(x, y) for x in range(self.n) for y in range(self.n) if (x, y) not in self.body] self.food = self.rng.choice(free)
def blocked(self, d): hx, hy = self.body[0] dx, dy = DIRS[d] nx, ny = hx + dx, hy + dy if not (0 <= nx < self.n and 0 <= ny < self.n): return "wall" if (nx, ny) in self.body[:-1]: return "own body" return None
def state_text(self): hx, hy = self.body[0] fx, fy = self.food dx, dy = fx - hx, fy - hy rel = [] if dx: rel.append(f"{abs(dx)} {'right' if dx > 0 else 'left'}") if dy: rel.append(f"{abs(dy)} {'down' if dy > 0 else 'up'}") blk = "; ".join(f"{d}: {self.blocked(d) or 'free'}" for d in DIRS) return (f"Snake game on a {self.n}x{self.n} board (x grows right, y grows down). Snake length {len(self.body)}, " f"head at x={hx}, y={hy}, moving {self.dir}. Food at x={fx}, y={fy}, i.e. {', '.join(rel) or 'here'} " f"from the head. Next cell in each direction -> {blk}. Moving into a wall or the snake's own body " f"ends the game; reversing into the neck ({OPP[self.dir]}) is not allowed.")
def question(self): return {"type": "choice", "instructions": "Which way should the snake move next to get closer to the food " "without dying?", "criteria": {"up": "move one cell up (y - 1)", "down": "move one cell down (y + 1)", "left": "move one cell left (x - 1)", "right": "move one cell right (x + 1)"}}
def step(self, d): if d == OPP[self.dir]: d = self.dir self.dir = d if self.blocked(d): self.alive = False return hx, hy = self.body[0] nh = (hx + DIRS[d][0], hy + DIRS[d][1]) self.body.insert(0, nh) if nh == self.food: self.score += 1 self.place_food() else: self.body.pop() self.steps += 1
def render(self, lat_ms, probs, cell=40): W = self.n * cell im = Image.new("RGB", (W + 360, W), (18, 20, 26)) d = ImageDraw.Draw(im) for x in range(self.n): for y in range(self.n): d.rectangle([x * cell, y * cell, x * cell + cell - 1, y * cell + cell - 1], outline=(32, 36, 44)) fx, fy = self.food d.ellipse([fx * cell + 6, fy * cell + 6, fx * cell + cell - 6, fy * cell + cell - 6], fill=(235, 70, 70)) for i, (x, y) in enumerate(self.body): c = (90, 220, 120) if i == 0 else (50, 160, 90) d.rounded_rectangle([x * cell + 3, y * cell + 3, x * cell + cell - 3, y * cell + cell - 3], 8, fill=c) f1, f2 = font(22), font(18) X = W + 20 d.text((X, 20), "MM-Jev plays Snake", fill=(240, 240, 240), font=f1) d.text((X, 52), "text state -> 1 choice / tick", fill=(150, 160, 175), font=f2) d.text((X, 100), f"apples {self.score}", fill=(235, 70, 70), font=f1) d.text((X, 132), f"moves {self.steps}", fill=(200, 200, 200), font=f1) col = (90, 220, 120) if lat_ms < 50 else (240, 200, 60) d.text((X, 180), f"decision {lat_ms:5.1f} ms", fill=col, font=f1) y0 = 230 for k, v in sorted(probs.items(), key=lambda kv: -kv[1]): d.text((X, y0), f"{k:>5s}", fill=(220, 220, 220), font=f2) d.rectangle([X + 70, y0 + 4, X + 70 + int(220 * v), y0 + 18], fill=(90, 160, 240)) d.text((X + 296, y0), f"{v:.2f}", fill=(180, 180, 180), font=f2) y0 += 30 return im
def snake_demo(jev, fc, max_steps=300, seed=3, fps=12, name="snake"): g = Snake(seed=seed) frames, lats = [], [] q = g.question() jev.decide(g.state_text(), [q], fc=fc, graph=True) # warm the graph bucket while g.alive and g.steps < max_steps: st = g.state_text() torch.cuda.synchronize(); t0 = time.perf_counter() r = jev.decide(st, [q], fc=fc, graph=True)[0] torch.cuda.synchronize(); ms = (time.perf_counter() - t0) * 1000 lats.append(ms) frames.append(g.render(ms, r["probabilities"])) g.step(r["choice"]) frames.append(g.render(lats[-1] if lats else 0, {})) d = f"{OUT}/{name}_frames"; os.makedirs(d, exist_ok=True) for i, f in enumerate(frames): f.save(f"{d}/{i:05d}.png") subprocess.run(f"ffmpeg -y -loglevel error -framerate {fps} -i {d}/%05d.png -c:v libx264 -pix_fmt yuv420p " f"-vf scale=trunc(iw/2)*2:trunc(ih/2)*2 {OUT}/{name}.mp4", shell=True) return dict(apples=g.score, moves=g.steps, died=not g.alive, p50_ms=float(np.median(lats)), p95_ms=float(np.percentile(lats, 95)), max_ms=float(np.max(lats)))
# ------------------------------------------------------------------------------------------ cardsdef _card(title, media_im, answers, lat_ms, subtitle=""): W = 1280 im = Image.new("RGB", (W, 620), (250, 250, 252)) d = ImageDraw.Draw(im) if media_im is not None: m = media_im.copy(); m.thumbnail((560, 560)) im.paste(m, (30, 30)) X = 620 d.text((X, 30), title, fill=(20, 20, 30), font=font(28)) if subtitle: d.text((X, 70), subtitle, fill=(110, 110, 125), font=font(18)) y = 115 for q, a in answers: d.text((X, y), q[:62], fill=(40, 40, 60), font=font(18)); y += 28 d.text((X + 20, y), a[:60], fill=(20, 110, 60), font=font(20)); y += 40 d.text((X, 570), f"{len(answers)} questions, one forward pass: {lat_ms:.0f} ms (towers included)", fill=(90, 90, 110), font=font(18)) return im
def _fmt(q, r): if q["type"] == "noul": return f"noul P(yes) = {r['noul']:.2f}" if q["type"] == "score": top = max(r["probabilities"].items(), key=lambda kv: kv[1]) return f"score level {r['level']} ({q['criteria'][r['level']]}), p={top[1]:.2f}" return f"choice {r['choice']} (p={r['probabilities'][r['choice']]:.2f})"
def _timed(jev, st, qs, fc): """decide() on a question list returns {index: answer}; hand back a list in question order.""" jev.decide(st, qs, fc=fc, graph=True) torch.cuda.synchronize(); t0 = time.perf_counter() r = jev.decide(st, qs, fc=fc, graph=True) torch.cuda.synchronize() return [r[i] for i in range(len(qs))], (time.perf_counter() - t0) * 1000
def image_demo(jev, fc, img, qs, name="demo_image", title="Image state"): r, ms = _timed(jev, [Seg("image", img)], qs, fc) _card(title, img, [(q["instructions"], _fmt(q, x)) for q, x in zip(qs, r)], ms, "768x768 input, 64 visual tokens").save(f"{OUT}/{name}.png") return r, ms
def audio_demo(jev, fc, wav, qs, name="demo_audio", title="Audio state"): import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(5.6, 3.0), dpi=100) t = np.arange(len(wav)) / 16000 ax.plot(t, wav, lw=0.4, color="#3b6fd8"); ax.set_xlabel("seconds"); ax.set_yticks([]) fig.tight_layout(); fig.canvas.draw() wim = Image.frombuffer("RGBA", fig.canvas.get_width_height(), fig.canvas.buffer_rgba()).convert("RGB") plt.close(fig) r, ms = _timed(jev, [Seg("audio", wav)], qs, fc) _card(title, wim, [(q["instructions"], _fmt(q, x)) for q, x in zip(qs, r)], ms, "16 kHz waveform, 6.25 tokens / s").save(f"{OUT}/{name}.png") return r, ms
def video_demo(jev, fc, frames, qs, audio=None, fps=2.0, name="demo_video", title="Video state"): r, ms = _timed(jev, [Seg("video", frames, audio=audio, fps=fps)], qs, fc) ans = [(q["instructions"], _fmt(q, x)) for q, x in zip(qs, r)] d = f"{OUT}/{name}_frames"; os.makedirs(d, exist_ok=True) for i, fr in enumerate(frames): _card(title, fr, ans, ms, f"{len(frames)} frames @768, 16 tokens/frame" + (" + soundtrack" if audio is not None else "")).save(f"{d}/{i:03d}.png") subprocess.run(f"ffmpeg -y -loglevel error -framerate {fps} -i {d}/%03d.png -c:v libx264 -pix_fmt yuv420p {OUT}/{name}.mp4", shell=True) return r, ms1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Synthetic media generators shared by tests, data building and benchmarks."""import numpy as npfrom PIL import Image, ImageDraw
COLORS = {"red": (220, 40, 40), "blue": (40, 80, 220), "green": (40, 170, 60), "yellow": (230, 200, 30), "purple": (140, 60, 180), "orange": (240, 130, 30)}SHAPES = ["circle", "square", "triangle"]
def draw_shape(d, shape, color, cx, cy, r): c = COLORS[color] if shape == "circle": d.ellipse([cx - r, cy - r, cx + r, cy + r], fill=c) elif shape == "square": d.rectangle([cx - r, cy - r, cx + r, cy + r], fill=c) else: d.polygon([(cx, cy - r), (cx - r, cy + r), (cx + r, cy + r)], fill=c)
def shapes_image(objs, size=384, bg=(245, 245, 240)): """objs: list of (shape, color, cx, cy, r) in [0,1] coords for cx, cy and fraction r.""" im = Image.new("RGB", (size, size), bg) d = ImageDraw.Draw(im) for shape, color, cx, cy, r in objs: draw_shape(d, shape, color, cx * size, cy * size, r * size) return im
def beeps(n, sr=16000, dur=4.0, freq=880.0, rng=None): """n short tone beeps spread over `dur` seconds, plus light noise.""" rng = rng or np.random.default_rng(0) t = np.zeros(int(sr * dur), np.float32) if n: starts = np.linspace(0.3, dur - 0.5, n) + rng.uniform(-0.05, 0.05, n) for s in starts: a = int(s * sr); L = int(0.18 * sr) tt = np.arange(L) / sr t[a:a + L] += 0.5 * np.sin(2 * np.pi * freq * tt) * np.hanning(L) t += rng.normal(0, 0.01, t.shape).astype(np.float32) return t
def moving_video(shape, color, direction, n_frames=8, size=320, flashes=0, change_to=None, rng=None): """A shape moving across the frame. flashes: number of frames where the background flashes white-yellow. change_to: the colour the shape switches to halfway through (None = no change).""" rng = rng or np.random.default_rng(0) frames = [] x0, y0 = rng.uniform(0.35, 0.65), rng.uniform(0.35, 0.65) dx = {"left": (-1, 0), "right": (1, 0), "up": (0, -1), "down": (0, 1)}[direction] span = 0.6 flash_idx = set(rng.choice(np.arange(1, n_frames - 1), size=flashes, replace=False).tolist()) if flashes else set() for i in range(n_frames): f = i / (n_frames - 1) - 0.5 cx = x0 + dx[0] * f * span; cy = y0 + dx[1] * f * span cx = min(max(cx, 0.1), 0.9); cy = min(max(cy, 0.1), 0.9) bg = (255, 250, 150) if i in flash_idx else (40, 40, 48) col = change_to if (change_to and i >= n_frames // 2) else color frames.append(shapes_image([(shape, col, cx, cy, 0.09)], size=size, bg=bg)) return frames123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836"""MM-Jev: a Jev-style typed decision model (noul / choice / score) on Gemma 3n E4B with multimodal state.
State = segments (text, image, audio, video = frames + optional soundtrack). Questions carry text only. Nothing isgenerated: every option is scored and the distribution is the model's own softmax over the options.
Architecture (see docs/architecture.md)---------------------------------------1. Option tree in one pass. [state] -> [question_j] -> [option_j1] [option_j2] ... packed in one sequence with a tree attention mask; every branch sees only its ancestors, position ids restart at the end of the question. The state is encoded once for all questions and options, and option order cannot matter (structural, like openjev).2. KV-share query truncation (exact). Gemma 3n layers 20-34 compute no K/V of their own (they read layers 18/19), so a token's state in those layers only feeds its own output: they run on the scoring tokens only (1 per option).3. Modality exit + latent memory. After layer k all media tokens (image / audio / video soft tokens) are dropped from the sequence. M learned latent tokens appended to every media segment, and the text tokens after it, have attended to the media in layers < k and carry what is needed forward (DyVTE / LLaVA-Mini / VoCo-LLaMA; 2512.07580 shows deep-layer visual tokens are no better than random).4. Elastic depth. A second decision head reads the hidden state after layer 19 (the last layer with its own K/V): exiting there skips 15 of 35 layers of weights (miniReranker-style mid-depth exit).5. Visual tokens. Input stays 768x768 (>= 720p). The 16x16 MobileNet-V5 grid is average-pooled before projection (2x2 -> 64 tokens per image, 4x4 -> 16 per video frame); near-duplicate video frames are dropped.6. Head. score = w . h(last token of branch), w initialised to E[Yes] - E[No] (zero-shot "is this answer correct?" log-odds). Loss: log score + ranked probability score for ordinal questions; per-type temperature post hoc."""from __future__ import annotations
import mathfrom dataclasses import dataclass, replace
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
QTYPES = {"noul": 0, "choice": 1, "score": 2}NOUL_DEFAULT = {"no": "no, the statement does not hold", "yes": "yes, the statement holds"}SYSTEM = ("You are a decision model. Read the state and the question, then judge whether the proposed answer " "is correct. Reply Yes or No.")FIRST_SHARED = 20 # Gemma 3n E4B: 35 layers, the last 15 share K/V
# ------------------------------------------------------------------------------------------ inputs@dataclassclass Seg: kind: str # text | image | audio | video data: object = None # str | PIL.Image | np.ndarray 16 kHz | list[PIL] -- or cached tower features (Tensor) audio: object = None # optional soundtrack of a video (np.ndarray or cached Tensor) fps: float = 1.0 # frame rate of `data` for a video
def k_bucket(k: int) -> str: return "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11-30" if k <= 30 else "31+"
def options_of(q: dict) -> tuple[list[str], list[str]]: """(labels, branch texts) in label-index order. noul is always [no, yes] so p[1] is the noul probability.""" t, crit = q["type"], q.get("criteria") if t == "noul": crit = {**NOUL_DEFAULT, **(crit or {})} return ["no", "yes"], [f"no — {crit['no']}", f"yes — {crit['yes']}"] if t == "score": crit = list(crit) return [str(i) for i in range(len(crit))], [f"level {i} of {len(crit) - 1} — {c}" for i, c in enumerate(crit)] if isinstance(crit, dict): return list(crit), [f"{k} — {v}" if v else k for k, v in crit.items()] labels = list(crit if crit is not None else q["options"]) return labels, labels
@dataclassclass FastConfig: media_exit: int | None = None # drop media tokens after this many layers (None = keep) exit_layer: int = 35 # 35 = full depth, 20 = mid-depth head truncate_shared: bool = True # exact KV-share truncation image_pool: int = 2 # 16x16 grid -> (16/pool)^2 tokens per image frame_pool: int = 4 # per video frame n_latents: int = 8 # latent memory tokens per media segment (0 = none) dedup_tau: float = 0.985 # drop a video frame whose pooled feature has cos > tau with the last kept one max_frames: int = 8 sibling_from: int | None = None # from this layer on, option branches of one question see each other (listwise)
# ------------------------------------------------------------------------------------------ Gemma 3n speed patchdef _patch_gaussian_topk(): """The HF MLP builds a torch Normal and calls icdf on every forward of the 10 sparse layers. Cache the constant.""" from transformers.models.gemma3n import modeling_gemma3n as mg if getattr(mg.Gemma3nTextMLP, "_mmjev_patched", False): return cache = {}
def _gaussian_topk(self, inputs): s = float(self.activation_sparsity) if s not in cache: cache[s] = float(torch.distributions.Normal(0, 1).icdf(torch.tensor(s))) mean = inputs.mean(-1, keepdim=True) std = inputs.std(-1, keepdim=True, unbiased=False) return F.relu(inputs - (mean + std * cache[s]))
mg.Gemma3nTextMLP._gaussian_topk = _gaussian_topk mg.Gemma3nTextMLP._mmjev_patched = True
# ------------------------------------------------------------------------------------------ modelclass MMJev(nn.Module): def __init__(self, base, processor, fast: FastConfig | None = None, n_latent_max: int = 16): super().__init__() _patch_gaussian_topk() self.base = base self.proc = processor self.tok = processor.tokenizer self.fast = fast or FastConfig() core = self._core() self.lm = core.language_model self.cfg = self.lm.config self.d = self.cfg.hidden_size self.device = self.lm.embed_tokens.weight.device self.dtype = torch.float16 t = self.tok self.id = {k: t.convert_tokens_to_ids(v) for k, v in dict( boi="<start_of_image>", eoi="<end_of_image>", boa="<start_of_audio>", eoa="<end_of_audio>", sot="<start_of_turn>", eot="<end_of_turn>").items()} self.yes_id = t.encode("Yes", add_special_tokens=False)[0] self.no_id = t.encode("No", add_special_tokens=False)[0] with torch.no_grad(): E = self.lm.embed_tokens.weight w = (E[self.yes_id].float() - E[self.no_id].float())[None] self.heads = nn.ModuleDict({str(k): nn.Linear(self.d, 1).to(self.device, torch.float32) for k in (35, FIRST_SHARED)}) for h in self.heads.values(): h.weight.copy_(w.to(self.device)); h.bias.zero_() # latent memory tokens, initialised near the embedding of a neutral word so they start in-distribution init = self._embed_ids(torch.tensor(self._t(" summary"))).float().mean(0) self.latents = nn.Parameter(init[None].repeat(n_latent_max, 1) + 0.02 * init.std() * torch.randn(n_latent_max, self.d, device=self.device)) self.softcap = getattr(self.cfg, "final_logit_softcapping", None) self.register_buffer("temperature", torch.ones(3, device=self.device)) self.vision_fn = None # optional compiled vision forward (pixel fp16 channels_last -> last_hidden_state)
def _core(self): m = self.base while not (hasattr(m, "language_model") and hasattr(m, "vision_tower")): m = m.model if hasattr(m, "model") else m.base_model return m
def _t(self, s: str) -> list[int]: return self.tok.encode(s, add_special_tokens=False)
def _embed_ids(self, ids: torch.Tensor) -> torch.Tensor: """As Gemma3nModel.forward: text ids from embed_tokens, ids in the vision / audio hard-token ranges (e.g. <end_of_image> = 262144) from embed_vision / embed_audio.""" core = self._core() ev, ea = core.embed_vision, core.embed_audio ids = ids.to(self.device) text = ids < ev.vocab_offset out = self.lm.embed_tokens(torch.where(text, ids, torch.zeros_like(ids))).to(self.dtype) vis = (ids >= ev.vocab_offset) & (ids < ea.vocab_offset) if vis.any(): out[vis] = ev(input_ids=ids[vis][None]).to(self.dtype)[0] aud = ids >= ea.vocab_offset if aud.any(): out[aud] = ea(input_ids=ids[aud][None]).to(self.dtype)[0] return out
# -------------------------------------------------------------------------------------- media encoders @torch.no_grad() def vision_tower_features(self, images) -> torch.Tensor: """list[PIL] -> MobileNet-V5 grid (n, C, 16, 16) at the native 768x768 input.""" vt = self._core().vision_tower dt = next(vt.parameters()).dtype out = [] for s in range(0, len(images), 8): pv = self.proc.image_processor(images[s:s + 8], return_tensors="pt")["pixel_values"] pv = pv.to(self.device, dt).contiguous(memory_format=torch.channels_last) if self.vision_fn is not None: h = self.vision_fn(pv) else: h = vt(pixel_values=pv, do_pooling=False, return_dict=True).last_hidden_state out.append(h.to(self.dtype)) return torch.cat(out, 0)
def embed_vision_grid(self, grid: torch.Tensor, pool: int) -> torch.Tensor: """(n, C, 16, 16) -> (n, (16/pool)^2, d). Pooled before projection so the soft-embedding norm sees averages.""" ev = self._core().embed_vision h = grid.float() target = max(1, 16 // pool) # grids may be cached already pooled (e.g. 8x8 / 4x4) if h.shape[-1] > target: h = F.avg_pool2d(h, h.shape[-1] // target) n, C = h.shape[:2] h = h.reshape(n, C, -1).permute(0, 2, 1) * (C ** 0.5) return ev(inputs_embeds=h.to(next(ev.parameters()).dtype)).to(self.dtype)
@torch.no_grad() def audio_tower_features(self, clips) -> list: """list[np 16 kHz] -> list[(T_i, C)] valid conformer outputs (before embed_audio).""" at = self._core().audio_tower enc = self.proc.feature_extractor([np.asarray(c, np.float32) for c in clips], sampling_rate=16000, return_tensors="pt", padding="longest") feats = enc["input_features"].to(self.device, next(at.parameters()).dtype) mask = enc["input_features_mask"].to(self.device) ao = at(feats, ~mask.bool(), return_dict=True) pad = ao.audio_mel_mask return [ao.last_hidden_state[i][~pad[i]].to(self.dtype) for i in range(len(clips))]
def embed_audio_feats(self, a: torch.Tensor) -> torch.Tensor: ea = self._core().embed_audio return ea(inputs_embeds=a[None].to(next(ea.parameters()).dtype)).to(self.dtype)[0]
@staticmethod def dedup_frames(grid: torch.Tensor, tau: float) -> list[int]: """Keep frame i unless its mean-pooled feature nearly copies the last kept frame (LongVU-style).""" v = F.normalize(grid.float().mean((2, 3)), dim=-1) keep = [0] for i in range(1, len(v)): if float((v[i] * v[keep[-1]]).sum()) < tau: keep.append(i) if keep[-1] != len(v) - 1: keep.append(len(v) - 1) # always keep the last frame: the "now" of the state return keep
def encode_state(self, state: list[Seg], fc: FastConfig | None = None): """-> list of encoded segments, running the frozen towers unless cached features are given.""" fc = fc or self.fast out = [] for seg in state: if seg.kind == "text": out.append(("text", seg.data)) elif seg.kind == "image": g = seg.data if torch.is_tensor(seg.data) else self.vision_tower_features([seg.data])[0] out.append(("image", self.embed_vision_grid(g[None].to(self.device), fc.image_pool)[0])) elif seg.kind == "audio": a = seg.data if torch.is_tensor(seg.data) else self.audio_tower_features([seg.data])[0] out.append(("audio", self.embed_audio_feats(a.to(self.device)))) elif seg.kind == "video": frames = seg.data n = len(frames) idx = np.arange(n) if n > fc.max_frames: idx = np.linspace(0, n - 1, fc.max_frames).round().astype(int) g = frames[torch.as_tensor(idx)] if torch.is_tensor(frames) else \ self.vision_tower_features([frames[i] for i in idx]) g = g.to(self.device) keep = self.dedup_frames(g, fc.dedup_tau) if fc.dedup_tau < 1 else list(range(len(g))) emb = self.embed_vision_grid(g[keep], fc.frame_pool) out.append(("video", emb, [float(idx[k]) / seg.fps for k in keep])) if seg.audio is not None: a = seg.audio if torch.is_tensor(seg.audio) else self.audio_tower_features([seg.audio])[0] out.append(("soundtrack", self.embed_audio_feats(a.to(self.device)))) return out
# -------------------------------------------------------------------------------------- tree plan def plan(self, enc, questions: list[dict], fc: FastConfig | None = None): """Nodes of the tree; a node holds pieces ('ids', list) | ('emb', Tensor, is_media) | ('lat', M).""" M = (fc or self.fast).n_latents pieces = [("ids", [self.tok.bos_token_id, self.id["sot"]] + self._t("user\n" + SYSTEM + "\n\nState:\n"))] for e in enc: kind = e[0] if kind == "text": pieces.append(("ids", self._t(e[1] + "\n"))) elif kind == "image": pieces += [("ids", self._t("Image: ") + [self.id["boi"]]), ("emb", e[1], True)] if M: pieces.append(("lat", M)) pieces.append(("ids", [self.id["eoi"]] + self._t("\n"))) elif kind in ("audio", "soundtrack"): lead = "Audio: " if kind == "audio" else "Video soundtrack: " pieces += [("ids", self._t(lead) + [self.id["boa"]]), ("emb", e[1], True)] if M: pieces.append(("lat", M)) pieces.append(("ids", [self.id["eoa"]] + self._t("\n"))) elif kind == "video": emb, times = e[1], e[2] pieces.append(("ids", self._t(f"Video, {len(times)} key frames:\n"))) for j, t in enumerate(times): pieces += [("ids", self._t(f"{t:.1f}s ") + [self.id["boi"]]), ("emb", emb[j], True), ("ids", [self.id["eoi"]])] if M: pieces.append(("lat", M)) pieces.append(("ids", self._t("\n"))) nodes = [dict(parent=-1, pieces=pieces)] q_opts = [] for q in questions: _, texts = options_of(q) nodes.append(dict(parent=0, pieces=[("ids", self._t( f"\nQuestion ({q['type']}): {q['instructions'].strip()}{self.option_context(q)}\nProposed answer: "))])) qn = len(nodes) - 1 ids = [] for txt in texts: nodes.append(dict(parent=qn, pieces=[("ids", self._t(txt) + [self.id["eot"]] + self._t("\n") + [self.id["sot"]] + self._t("model\n"))])) ids.append(len(nodes) - 1) q_opts.append(ids) return nodes, q_opts
option_context_on = True option_context_max = 8
def option_context(self, q) -> str: """Canonical option context: every branch sees the whole answer space, listed in a canonical order (sorted labels for `choice`, the intrinsic level order for `score`), so the prefix -- and hence every probability -- is still independent of the order the caller passed the options in.""" if not self.option_context_on or q["type"] == "noul": return "" labels, _ = options_of(q) if len(labels) > self.option_context_max: return "" # large label spaces: siblings compare in-attention instead (sibling_from) if q["type"] == "score": crit = list(q["criteria"]) return "\nScale: " + "; ".join(f"level {i} = {str(c)[:80]}" for i, c in enumerate(crit)) return "\nOptions: " + "; ".join(sorted(labels, key=lambda x: x.lower()))
@staticmethod def isolate(plan): """One linear plan per option (root -> question -> that option): the naive K-pass baseline.""" nodes, q_opts = plan out = [] for opts in q_opts: for o in opts: qn = nodes[o]["parent"] out.append(([dict(nodes[0]), dict(nodes[qn], parent=0), dict(nodes[o], parent=1)], [[2]])) return out
def pack(self, plans): """Concatenate the node pieces of every plan into right-padded tensors plus the tree mask.""" B = len(plans) rows = [] for nodes, q_opts in plans: parts, ple, pos, node_of, media = [], [], [], [], [] start, length, end = {}, {}, {} cur = 0 for n, nd in enumerate(nodes): p0 = 0 if nd["parent"] < 0 else start[nd["parent"]] + length[nd["parent"]] start[n], ln = p0, 0 for pc in nd["pieces"]: if pc[0] == "ids": ids = torch.tensor(pc[1], dtype=torch.long) parts.append(("ids", ids)); k = len(ids) ple.append(torch.where(ids < self.cfg.vocab_size_per_layer_input, ids, torch.zeros_like(ids))) media += [False] * k elif pc[0] == "emb": parts.append(("emb", pc[1])); k = len(pc[1]) ple.append(torch.zeros(k, dtype=torch.long)); media += [pc[2]] * k else: k = pc[1] parts.append(("lat", k)); ple.append(torch.zeros(k, dtype=torch.long)); media += [False] * k ln += k length[n] = ln pos.append(torch.arange(p0, p0 + ln)); node_of += [n] * ln cur += ln end[n] = cur - 1 A = torch.zeros(len(nodes), len(nodes), dtype=torch.bool) for i in range(len(nodes)): j = i while j >= 0: A[i, j] = True j = nodes[j]["parent"] qof = torch.full((len(nodes),), -1, dtype=torch.long) # option node -> its question node for opts in q_opts: for o in opts: qof[o] = nodes[o]["parent"] rows.append(dict(parts=parts, ple=torch.cat(ple), pos=torch.cat(pos), node=torch.tensor(node_of), media=torch.tensor(media), A=A, qof=qof, ends=[[end[o] for o in opts] for opts in q_opts])) L = max(len(r["ple"]) for r in rows) ple = torch.zeros(B, L, dtype=torch.long) pos = torch.zeros(B, L, dtype=torch.long) valid = torch.zeros(B, L, dtype=torch.bool) media = torch.zeros(B, L, dtype=torch.bool) mask = torch.zeros(B, L, L, dtype=torch.bool) sib = torch.zeros(B, L, L, dtype=torch.bool) causal = torch.ones(L, L, dtype=torch.bool).tril() lat = self.latents.to(self.dtype) xs = [] for b, r in enumerate(rows): ids_all = [p[1] for p in r["parts"] if p[0] == "ids"] tok = self._embed_ids(torch.cat(ids_all)) seq, off = [], 0 for p in r["parts"]: if p[0] == "ids": seq.append(tok[off:off + len(p[1])]); off += len(p[1]) elif p[0] == "emb": seq.append(p[1].to(self.dtype)) else: seq.append(lat[:p[1]]) seq = torch.cat(seq, 0) n = len(seq) xs.append(F.pad(seq, (0, 0, 0, L - n))) # keeps the graph to the latent parameters ple[b, :n], pos[b, :n], valid[b, :n], media[b, :n] = r["ple"], r["pos"], True, r["media"] pos[b, n:] = r["pos"].max() + 1 nd = r["node"] mask[b, :n, :n] = r["A"][nd[:, None], nd[None, :]] & causal[:n, :n] # sibling bridge (Set-Encoder style): an option-branch token may read the END token of every sibling # branch of the same question -- one summary per option, positions stay tree positions -> equivariant qn = r["qof"][nd] # question of each token's option branch (-1: none) is_end = torch.zeros(n, dtype=torch.bool) is_end[[i for e in r["ends"] for i in e]] = True sib[b, :n, :n] = (qn[:, None] == qn[None, :]) & (qn[:, None] >= 0) & is_end[None, :] mask |= torch.eye(L, dtype=torch.bool)[None] # padded rows see themselves (no all -inf rows) return dict(x=torch.stack(xs), ple=ple, pos=pos, valid=valid, media=media, mask=mask, sib=sib | mask, ends=[r["ends"] for r in rows])
# -------------------------------------------------------------------------------------- decoder loop def _masks(self, mask, pos_q, pos_k): """Full and sliding-window boolean masks [B,1,Q,K] from the tree mask and the tree position ids.""" s = mask & ((pos_q[:, :, None] - pos_k[:, None, :]) < self.cfg.sliding_window) return {"full_attention": mask[:, None], "sliding_attention": s[:, None]}
def host_indices(self, pk, fc: FastConfig, L_pad: int | None = None, K_pad: int | None = None, Lk_pad: int | None = None): """Host-side index tensors: scoring positions in packed coordinates (sidx_full) and after the modality exit (sidx_kept), and the kept-token gather (kidx, kval). Optional padding to fixed buckets for CUDA graphs.""" ends, valid, med = pk["ends"], pk["valid"], pk["media"] B, L = valid.shape K = K_pad or max(sum(len(e) for e in r) for r in ends) sidx = torch.zeros(B, K, dtype=torch.long) for b, r in enumerate(ends): flat = [i for e in r for i in e] sidx[b, :len(flat)] = torch.tensor(flat) out = dict(sidx_full=sidx, sidx_kept=sidx.clone(), kidx=None, kval=None) if fc.media_exit is not None: keep = valid & ~med Lk = Lk_pad or int(keep.sum(1).max()) kidx = torch.zeros(B, Lk, dtype=torch.long) kval = torch.zeros(B, Lk, dtype=torch.bool) remap = torch.zeros(B, L_pad or L, dtype=torch.long) for b in range(B): ii = keep[b].nonzero().squeeze(1) kidx[b, :len(ii)], kval[b, :len(ii)] = ii, True if len(ii) < Lk: # padding slots point at a padding token of the packed sequence kidx[b, len(ii):] = (L_pad or L) - 1 remap[b, ii] = torch.arange(len(ii)) out.update(sidx_kept=remap.gather(1, sidx), kidx=kidx, kval=kval) return out
def core(self, fc: FastConfig, x, ple, pos, mask, sidx_full, sidx_kept, kidx=None, kval=None, sib=None): """Pure-GPU decoder: Gemma3nTextModel.forward re-implemented with the modality exit, the KV-share truncation and the early exit. No host syncs, so it can be captured in a CUDA graph. Returns scores (B, K) float32.""" if self.fp32_residual: # AltUp residual streams reach |h| ~ 700, where fp16 has ~0.5 resolution: keep the streams in fp32 and # let autocast run every matmul in fp16 (vs a per-layer fp32 reference: max |d logit| 2.5 -> ~0.05) with torch.autocast("cuda", dtype=torch.float16): return self._decoder(fc, x.float(), ple.float(), pos, mask, sidx_full, sidx_kept, kidx, kval, sib) return self._decoder(fc, x, ple, pos, mask, sidx_full, sidx_kept, kidx, kval, sib)
fp32_residual = True
def _decoder(self, fc, x, ple, pos, mask, sidx_full, sidx_kept, kidx=None, kval=None, sib=None): lm, cfg, dev = self.lm, self.cfg, self.device B, L = x.shape[:2] K = sidx_full.shape[1] per_layer = lm.project_per_layer_inputs(x, ple) eps = torch.full((), 1e-5, device=dev) target = torch.mean(x ** 2, dim=-1, keepdim=True) ** 0.5 hs = [x] for i in range(1, cfg.altup_num_inputs): p = lm.altup_projections[i - 1](x).to(x.dtype) hs.append(p * target / torch.sqrt(torch.maximum(torch.mean(p ** 2, dim=-1, keepdim=True), eps))) hs = torch.stack(hs, 0)
def rope(p): return {lt: lm.rotary_emb(hs, p, lt) for lt in set(cfg.layer_types)}
def take(t, idx, dim, bdim): """Gather positions idx (B, n) along `dim` of t, whose batch axis is `bdim`.""" shape = list(t.shape); shape[dim] = idx.shape[1] view = [1] * t.dim(); view[dim] = idx.shape[1]; view[bdim] = B return t.gather(dim, idx.reshape(view).expand(shape))
sidx = sidx_full use_sib = fc.sibling_from is not None and sib is not None if not use_sib: sib = mask pe, cur_pos = rope(pos), pos masks, smasks = self._masks(mask, pos, pos), self._masks(sib, pos, pos) qmask = qsib = None shared = {} for i in range(fc.exit_layer): if fc.media_exit is not None and i == fc.media_exit: Lk = kidx.shape[1] hs, per_layer, cur_pos = take(hs, kidx, 2, 1), take(per_layer, kidx, 1, 0), cur_pos.gather(1, kidx) eye = torch.eye(Lk, dtype=torch.bool, device=dev)[None] mask = (take(take(mask, kidx, 1, 0), kidx, 2, 0) & kval[:, None, :]) | eye sib = (take(take(sib, kidx, 1, 0), kidx, 2, 0) & kval[:, None, :]) | eye pe = rope(cur_pos) masks, smasks = self._masks(mask, cur_pos, cur_pos), self._masks(sib, cur_pos, cur_pos) sidx = sidx_kept if i == FIRST_SHARED and fc.truncate_shared: hs, per_layer = take(hs, sidx, 2, 1), take(per_layer, sidx, 1, 0) qpos = cur_pos.gather(1, sidx) pe = rope(qpos) masks = self._masks(take(mask, sidx, 1, 0), qpos, cur_pos) smasks = self._masks(take(sib, sidx, 1, 0), qpos, cur_pos) sidx = torch.arange(K, device=dev)[None].expand(B, K) lt = cfg.layer_types[i] m = smasks if (use_sib and i >= fc.sibling_from) else masks hs = lm.layers[i](hs, pe[lt], per_layer[:, :, i, :], shared_kv_states=shared, attention_mask=m[lt], position_ids=None) hs = take(hs, sidx, 2, 1) target = torch.mean(hs[0] ** 2, dim=-1, keepdim=True) ** 0.5 outs = [hs[0]] for i in range(1, cfg.altup_num_inputs): p = lm.altup_unembed_projections[i - 1](hs[i]).to(x.dtype) outs.append(p * target / torch.sqrt(torch.maximum(torch.mean(p ** 2, dim=-1, keepdim=True), eps))) h = lm.norm(torch.stack(outs).mean(0)) s = self.heads[str(35 if fc.exit_layer >= 35 else FIRST_SHARED)](h.float()).squeeze(-1) if self.softcap: s = torch.tanh(s / self.softcap) * self.softcap return s
def ple_lookup(self, ple_ids): """Per-layer embeddings gathered on the CPU (the 4.7 GB table lives there), copied to the GPU.""" lm, cfg = self.lm, self.cfg w = lm.embed_tokens_per_layer.weight e = F.embedding(ple_ids.to(w.device), w) * lm.embed_tokens_per_layer.embed_scale.to(w.dtype) B, L = ple_ids.shape return e.reshape(B, L, cfg.num_hidden_layers, cfg.hidden_size_per_layer_input)
@staticmethod def split_scores(s, ends): res = [] for b, r in enumerate(ends): out, o = [], 0 for e in r: out.append(s[b, o:o + len(e)]); o += len(e) res.append(out) return res
def run(self, pk, fc: FastConfig | None = None): """Eager path (training and reference). Returns per sample, per question, the option logits.""" fc = fc or self.fast dev = self.device ix = self.host_indices(pk, fc) g = lambda t: None if t is None else t.to(dev, non_blocking=True) s = self.core(fc, pk["x"], g(self.ple_lookup(pk["ple"])).to(self.dtype), g(pk["pos"]), g(pk["mask"]), g(ix["sidx_full"]), g(ix["sidx_kept"]), g(ix["kidx"]), g(ix["kval"]), g(pk.get("sib")) if fc.sibling_from is not None else None) return self.split_scores(s, pk["ends"])
# -------------------------------------------------------------------------------------- CUDA graphs BUCKETS_L = (96, 128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 1536, 2048) BUCKETS_K = (4, 8, 16, 32, 64, 128)
@staticmethod def _bucket(n, buckets): for b in buckets: if n <= b: return b return n
compile_core = False
def _compiled(self, fc): """Inductor-fused decoder (elementwise chains of AltUp / LAuReL / PLE / norms fused), one per FastConfig.""" key = (fc.media_exit, fc.exit_layer, fc.truncate_shared) if not hasattr(self, "_compiled_fns"): self._compiled_fns = {} if key not in self._compiled_fns: import functools self._compiled_fns[key] = torch.compile(functools.partial(self.core, fc), dynamic=False, mode="max-autotune-no-cudagraphs") return self._compiled_fns[key]
@torch.no_grad() def run_graph(self, pk, fc: FastConfig | None = None): """Batch-1 latency path: pad to (L, K, Lk) buckets and replay a captured CUDA graph (one per bucket).""" fc = fc or self.fast assert pk["x"].shape[0] == 1 dev = self.device L0 = pk["x"].shape[1] L = self._bucket(L0, self.BUCKETS_L) K = self._bucket(max(sum(len(e) for e in r) for r in pk["ends"]), self.BUCKETS_K) Lk = None if fc.media_exit is not None: Lk = self._bucket(int((pk["valid"] & ~pk["media"]).sum()), self.BUCKETS_L) Lk = min(Lk, L) key = (L, K, Lk, fc.media_exit, fc.exit_layer, fc.truncate_shared, fc.sibling_from) if not hasattr(self, "_graphs"): self._graphs = {} # pad the packed inputs to the bucket pad = L - L0 x = F.pad(pk["x"], (0, 0, 0, pad)) ple_ids = F.pad(pk["ple"], (0, pad)) pos = torch.cat([pk["pos"], pk["pos"].max() + 1 + torch.arange(pad)[None]], 1) mask = torch.zeros(1, L, L, dtype=torch.bool) mask[:, :L0, :L0] = pk["mask"] mask |= torch.eye(L, dtype=torch.bool)[None] sib = torch.zeros(1, L, L, dtype=torch.bool) sib[:, :L0, :L0] = pk["sib"] sib |= torch.eye(L, dtype=torch.bool)[None] valid = F.pad(pk["valid"], (0, pad)); media = F.pad(pk["media"], (0, pad)) ix = self.host_indices(dict(ends=pk["ends"], valid=valid, media=media), fc, L_pad=L, K_pad=K, Lk_pad=Lk) ple = self.ple_lookup(ple_ids).to(self.dtype) feeds = dict(x=x, ple=ple, pos=pos, mask=mask, sidx_full=ix["sidx_full"], sidx_kept=ix["sidx_kept"]) if Lk is not None: feeds.update(kidx=ix["kidx"], kval=ix["kval"]) if fc.sibling_from is not None: feeds.update(sib=sib) if key not in self._graphs: static = {k: v.to(dev).clone() for k, v in feeds.items()} side = torch.cuda.Stream() side.wait_stream(torch.cuda.current_stream()) fn = self._compiled(fc) if self.compile_core else (lambda **kw: self.core(fc, **kw)) with torch.cuda.stream(side): for _ in range(3): fn(**static) torch.cuda.current_stream().wait_stream(side) graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): out = fn(**static) self._graphs[key] = (graph, static, out) graph, static, out = self._graphs[key] for k, v in feeds.items(): static[k].copy_(v, non_blocking=True) graph.replay() return self.split_scores(out.clone(), pk["ends"])
# -------------------------------------------------------------------------------------- public API def prepare(self, state, questions, fc: FastConfig | None = None): if isinstance(state, str): state = [Seg("text", state)] elif isinstance(state, Seg): state = [state] return self.plan(self.encode_state(state, fc), questions, fc)
@torch.no_grad() def decide(self, state, questions, calibrated: bool = True, fc: FastConfig | None = None, graph: bool = False): """Jev-style call. questions: {name: {type, instructions, criteria}} (or a list). noul -> {"noul": p_yes}; choice -> {"choice", "probabilities"}; score -> {"score" in [0,1], "level", ...}.""" names = list(questions) if isinstance(questions, dict) else list(range(len(questions))) qs = [questions[n] for n in names] self.eval() pk = self.pack([self.prepare(state, qs, fc)]) logits = (self.run_graph(pk, fc) if graph else self.run(pk, fc))[0] out = {} for n, q, lg in zip(names, qs, logits): T = float(self.temperature[QTYPES[q["type"]]]) if calibrated else 1.0 if calibrated and getattr(self, "temps_k", None): T = self.temps_k.get(f"{q['type']}:{k_bucket(len(lg))}", T) p = torch.softmax(lg / T, -1).cpu().numpy() labels, _ = options_of(q) probs = {l: float(v) for l, v in zip(labels, p)} conf = 1.0 - float(-(p * np.log(np.clip(p, 1e-12, 1))).sum() / math.log(max(len(p), 2))) if q["type"] == "noul": out[n] = {"noul": float(p[1]), "confidence": conf} elif q["type"] == "score": ev = float((p * np.arange(len(p))).sum() / max(len(p) - 1, 1)) out[n] = {"score": ev, "level": int(p.argmax()), "probabilities": probs, "confidence": conf} else: out[n] = {"choice": labels[int(p.argmax())], "probabilities": probs, "confidence": conf} return out
# ------------------------------------------------------------------------------------------ lossdef decision_loss(logits: torch.Tensor, target: torch.Tensor, qtype: str, w_rps: float = 1.0): """Strictly proper: log score (soft CE) for every type, + ranked probability score for ordinal questions.""" logp = torch.log_softmax(logits, -1) loss = -(target * logp).sum() if qtype == "score" and len(logits) > 1: p = logp.exp() loss = loss + w_rps * ((p.cumsum(-1) - target.cumsum(-1)) ** 2).sum() / (len(logits) - 1) return loss
# ------------------------------------------------------------------------------------------ loadingdef _cast(mod, dt): for p in mod.parameters(): if p.dtype in (torch.bfloat16, torch.float16, torch.float32): p.data = p.data.to(dt) for b in mod.buffers(): if b.dtype in (torch.bfloat16, torch.float16, torch.float32): b.data = b.data.to(dt)
def load_gemma3n(path: str, vision_dtype=torch.float32, audio_dtype=torch.float32, ple_on_gpu: bool | None = None): """Loaded on the CPU (safetensors are mmapped) and moved to the GPU module by module in fp16 -- except the 4.7 GB per-layer-embedding table, which stays on the CPU (only gathered from; a multi-device device_map would make accelerate copy it to the GPU). Loaded as bf16 first: the audio tower's 1e10 clamp constant overflows fp16. MobileNet-V5 overflows fp16 as shipped; call fp16_safe_vision() to run it in fp16.""" from transformers import AutoProcessor, Gemma3nForConditionalGeneration model = Gemma3nForConditionalGeneration.from_pretrained(path, dtype=torch.bfloat16, device_map="cpu", attn_implementation="sdpa") core = model.model lm = core.language_model ple = lm.embed_tokens_per_layer for _, child in lm.named_children(): if child is not ple: child.to("cuda", torch.float16) for name, b in list(lm.named_buffers(recurse=False)): setattr(lm, name, b.to("cuda", torch.float16 if b.is_floating_point() else b.dtype)) if ple_on_gpu is None: # 24 GB+ cards (L4, A100) keep the 4.7 GB table on the GPU ple_on_gpu = torch.cuda.get_device_properties(0).total_memory > 20 * 2**30 ple.to("cuda" if ple_on_gpu else "cpu", torch.float16) core.embed_vision.to("cuda", torch.float16) core.embed_audio.to("cuda", torch.float16) core.vision_tower.to("cuda"); _cast(core.vision_tower, vision_dtype) core.audio_tower.to("cuda"); _cast(core.audio_tower, audio_dtype) torch.cuda.empty_cache() return model, AutoProcessor.from_pretrained(path)
# ------------------------------------------------------------------------------------------ MatFormer width_FFN_ORIG = {}
def set_ffn_width(lm, width: int | None): """MatFormer elastic width: use the first `width` FFN neurons of every layer (E2B width = 8192). None restores.""" for i, layer in enumerate(lm.layers): mods = [getattr(layer.mlp, n) for n in ("gate_proj", "up_proj", "down_proj")] mods = [getattr(m, "base_layer", m) for m in mods] if i not in _FFN_ORIG: _FFN_ORIG[i] = [m.weight for m in mods] g, u, d = _FFN_ORIG[i] ws = (g, u, d) if width is None else ( nn.Parameter(g.data[:width], requires_grad=False), nn.Parameter(u.data[:width], requires_grad=False), nn.Parameter(d.data[:, :width], requires_grad=False)) for m, wt in zip(mods, ws): m.weight = wt
# ------------------------------------------------------------------------------------------ fp16-safe MobileNet-V5def _rms_norm2d_fp32(x, normalized_shape, weight=None, eps=1e-5): """timm's rms_norm2d squares x in its own dtype: in fp16 |x| > 256 overflows. Statistics in fp32 instead.""" v = x.float().pow(2).mean(dim=1, keepdim=True) y = (x.float() * torch.rsqrt(v + eps)).to(x.dtype) if weight is not None: y = y * weight.reshape(1, -1, 1, 1).to(y.dtype) return y
@torch.no_grad()def fp16_safe_vision(vision_tower, calib_pixels: torch.Tensor, headroom: float = 4096.0): """Run MobileNet-V5 in fp16 without overflow, exactly up to eps: 1. RMSNorm statistics in fp32; 2. every conv whose output feeds straight into an RMSNorm is divided by a power of two s so that its fp32 calibration abs-max stays below `headroom` -- RMSNorm(conv(x) / s) == RMSNorm(conv(x)). Returns the number of rescaled convs.""" import timm.layers.norm_act as na import timm.layers.norm as nm for mod in (na, nm): mod.rms_norm2d = _rms_norm2d_fp32 if hasattr(mod, "fast_rms_norm2d"): mod.fast_rms_norm2d = _rms_norm2d_fp32 tm = vision_tower.timm_model for m in tm.modules(): if hasattr(m, "_fast_norm"): m._fast_norm = False pairs = [] for m in tm.modules(): if hasattr(m, "conv") and hasattr(m, "bn") and "Rms" in type(m.bn).__name__: pairs.append(m.conv) if isinstance(m, nn.Sequential) and hasattr(m, "down_conv") and hasattr(m, "norm"): pairs.append(m.down_conv) _cast(vision_tower, torch.float32) amax = {} hooks = [c.register_forward_hook(lambda mod, i, o: amax.__setitem__(mod, max(amax.get(mod, 0.0), float(o.abs().max())))) for c in pairs] for s in range(0, len(calib_pixels), 4): vision_tower(pixel_values=calib_pixels[s:s + 4].float().cuda(), do_pooling=False, return_dict=True) for h in hooks: h.remove() n = 0 for c in pairs: s = 2.0 ** max(0, math.ceil(math.log2(max(amax.get(c, 0.0), 1e-6) / headroom))) if s > 1: c.weight.div_(s); n += 1 if c.bias is not None: c.bias.div_(s) _cast(vision_tower, torch.float16) vision_tower.to(memory_format=torch.channels_last) return n
# ------------------------------------------------------------------------------------------ adapter I/Oclass LoRALinear(nn.Module): """y = W x + (B A x) * alpha / r; slices A/B when the wrapped FFN projection is MatFormer-sliced."""
def __init__(self, base, r=16, alpha=32, dropout=0.05): super().__init__() self.base_layer = base self.lora_A = nn.Parameter(torch.randn(r, base.in_features, device=base.weight.device) / math.sqrt(base.in_features)) self.lora_B = nn.Parameter(torch.zeros(base.out_features, r, device=base.weight.device)) self.scale, self.drop = alpha / r, nn.Dropout(dropout)
@property def weight(self): return self.base_layer.weight
def forward(self, x): y = self.base_layer(x) out_f, in_f = self.base_layer.weight.shape lx = F.linear(F.linear(self.drop(x), self.lora_A[:, :in_f].to(x.dtype)), self.lora_B[:out_f].to(x.dtype)) return y + lx * self.scale
def add_lora(lm, r=16, alpha=32, mlp_from=10): """Attention q/k/v/o in every layer (KV-shared layers only have q/o) + MLP gate/up/down from `mlp_from`.""" for li, layer in enumerate(lm.layers): for name in ("q_proj", "k_proj", "v_proj", "o_proj"): m = getattr(layer.self_attn, name, None) if isinstance(m, nn.Linear): setattr(layer.self_attn, name, LoRALinear(m, r, alpha)) if li >= mlp_from: for name in ("gate_proj", "up_proj", "down_proj"): m = getattr(layer.mlp, name) if isinstance(m, nn.Linear): setattr(layer.mlp, name, LoRALinear(m, r, alpha))
PRESETS = { "full": (FastConfig(n_latents=8, exit_layer=35, media_exit=None, sibling_from=14), None), "fast": (FastConfig(n_latents=8, exit_layer=20, media_exit=8, sibling_from=14), 8192),}
def _from_adapter(cls, base, processor, adapter_path: str, config_path: str | None = None, preset: str = "fast"): """Build MM-Jev from a Gemma 3n model + the released adapter (LoRA, decision heads, latents, temperatures).""" import json from safetensors.torch import load_file jev = cls(base, processor) add_lora(jev.lm) sd = load_file(adapter_path) params = dict(jev.base.named_parameters()) with torch.no_grad(): for k, v in sd.items(): if k.startswith("lora."): params[k[5:]].copy_(v.to(params[k[5:]].device)) jev.heads.load_state_dict({k[6:]: v for k, v in sd.items() if k.startswith("heads.")}) jev.latents.copy_(sd["latents"].to(jev.latents.device)) fc, width = PRESETS[preset] jev.fast = fc set_ffn_width(jev.lm, width) if config_path: cfg = json.load(open(config_path)) jev.temps_k = cfg.get("temperatures", {}).get(preset, {}) jev.eval() return jev
MMJev.from_adapter = classmethod(_from_adapter)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Benchmarks for MM-Jev (run in the Colab kernel; `jev`, `DATA` in globals).
Accuracy: typed-decisions (Laya notebook scoring), BTZSC AG News / DAIR Emotion / Banking77 (jev-benchmarks pilot-v1protocol), MASSIVE scenario en/ko + intent en, XNLI en, JevBench public (easy / standard / hard), and our multimodalheld-out sets. Latency: batch-1 CUDA-graph path, p50 / p95, end-to-end (towers included for raw media)."""import json, math, timeimport numpy as np, torchfrom mmjev import FastConfig, Seg, options_of, set_ffn_width, QTYPES
LOGFILE = "/content/eval.log"
def say(*a): with open(LOGFILE, "a") as f: print(time.strftime("%H:%M:%S"), *a, file=f)
def ece(conf, corr, bins=10): conf, corr = np.asarray(conf), np.asarray(corr) e, edges = 0.0, np.linspace(0, 1, bins + 1) for lo, hi in zip(edges[:-1], edges[1:]): m = (conf > lo) & (conf <= hi) if m.any(): e += m.mean() * abs(conf[m].mean() - corr[m].mean()) return float(e)
def _T(temps, t, k): from mmjev import k_bucket temps = temps or {} return temps.get(f"{t}:{k_bucket(k)}", temps.get(t, 1.0))
@torch.no_grad()def predict(jev, recs, fc, width, temps=None, bs=8): """-> list (per record) of list (per question) of calibrated probability vectors.""" set_ffn_width(jev.lm, width) jev.eval() out = [] order = sorted(range(len(recs)), key=lambda i: sum(len(options_of(q)[0]) for q in recs[i]["qs"])) res = [None] * len(recs) def _go(idx): batch = [recs[i] for i in idx] try: plans = [jev.plan(jev.encode_state(r["state"], fc), r["qs"], fc) for r in batch] lg = jev.run(jev.pack(plans), fc) except torch.OutOfMemoryError: torch.cuda.empty_cache() if len(idx) == 1: raise h = len(idx) // 2 _go(idx[:h]); _go(idx[h:]); return for i, r, per_q in zip(idx, batch, lg): res[i] = [torch.softmax(l.float() / _T(temps, q["type"], len(l)), -1).cpu().numpy() for q, l in zip(r["qs"], per_q)]
for s in range(0, len(order), bs): _go(order[s:s + bs]) set_ffn_width(jev.lm, None) return res
def basic_metrics(recs, probs): acc, conf, corr, brier, nll = [], [], [], [], [] for r, pq in zip(recs, probs): for q, p, y in zip(r["qs"], pq, r["ys"]): c = float(int(p.argmax()) == y) acc.append(c); conf.append(float(p.max())); corr.append(c) oh = np.zeros_like(p); oh[y] = 1 brier.append(float(((p - oh) ** 2).sum())); nll.append(float(-math.log(max(p[y], 1e-12)))) return dict(n=len(acc), acc=float(np.mean(acc)), brier=float(np.mean(brier)), nll=float(np.mean(nll)), ece=ece(conf, corr))
def typed_metrics(recs, probs): """Exactly the Laya fine-tuning notebook scoring (accuracy, soft acc, Brier, ECE, score MAE in levels).""" accs, soft, brier, maes, confs, corrs = [], [], [], [], [], [] by_type, by_wf = {}, {} for r, pq in zip(recs, probs): for qid, q, p in zip(r["qnames"], r["qs"], pq): g, t = r["gold"][qid], q["type"] if t == "choice": keys = list(q["criteria"]) gp = np.array([g["probabilities"].get(k, 1e-6) for k in keys]); gp /= gp.sum() c = float(keys[int(p.argmax())] == str(g["label"])) soft.append(float((p * gp).sum())); brier.append(float(((p - gp) ** 2).sum())) confs.append(float(p.max())) elif t == "noul": pv = float(p[1]); gv = float(g.get("noul", g.get("probabilities", {}).get("true", 0.5))) c = float(("true" if pv >= 0.5 else "false") == str(g["label"]).lower()) pd, gd = np.array([1 - pv, pv]), np.array([1 - gv, gv]) soft.append(float((pd * gd).sum())); brier.append(float(((pd - gd) ** 2).sum())) confs.append(max(pv, 1 - pv)) else: ev = float((p * np.arange(len(p))).sum()) maes.append(abs(ev - float(g.get("score", 0.0)))) c = float(int(p.argmax()) == int(g.get("label", round(g.get("score", 0))))) confs.append(float(p.max())) accs.append(c); corrs.append(c) by_type.setdefault(t, []).append(c); by_wf.setdefault(r["workflow"], []).append(c) return dict(n=len(accs), acc=float(np.mean(accs)), soft_acc=float(np.mean(soft)), brier=float(np.mean(brier)), ece=ece(confs, corrs, 15), score_mae=float(np.mean(maes)), by_type={k: round(float(np.mean(v)), 3) for k, v in by_type.items()}, by_workflow={k: round(float(np.mean(v)), 3) for k, v in by_wf.items()})
def accuracy_suite(jev, DATA, fc, width, temps=None, tag="", tasks=None): ev = [r for v in list(DATA.values()) for r in v if r["split"] == "eval"] tasks = tasks or sorted(set(r["task"] for r in ev)) out = {} for t in tasks: rs = [r for r in ev if r["task"] == t] t0 = time.time() pr = predict(jev, rs, fc, width, temps) m = typed_metrics(rs, pr) if t == "typed_decisions" else basic_metrics(rs, pr) m["modality"] = rs[0]["modality"] out[t] = m say(f"[{tag}] {t:22s} n={m['n']:5d} acc {m['acc']:.3f} ece {m['ece']:.3f} ({time.time() - t0:.0f}s)") return out
# ------------------------------------------------------------------------------------------ latencydef _time(f, n): ts = [] for _ in range(n): torch.cuda.synchronize(); t0 = time.perf_counter(); f(); torch.cuda.synchronize() ts.append((time.perf_counter() - t0) * 1000) return ts
@torch.no_grad()def latency_suite(jev, DATA, fc, width, n_rep=3, max_items=40): """End-to-end decide() latency, batch 1, CUDA-graph path. Raw media -> towers are included.""" set_ffn_width(jev.lm, width); jev._graphs = {} ev = [r for v in DATA.values() for r in v if r["split"] == "eval"] groups = {} for r in ev: if r.get("raw") is not None: groups.setdefault(f"{r['modality']}:{r['task']}", []).append((r["raw"], r["qs"])) for t in ("typed_decisions", "btzsc_agnews", "btzsc_banking77", "jevbench_hard"): rs = [r for r in ev if r["task"] == t][:max_items] groups[f"text:{t}"] = [(r["state"], r["qs"]) for r in rs] res = {} for g, items in groups.items(): items = items[:max_items] for st, qs in items: # warm-up: capture every bucket graph first jev.decide(st, qs, fc=fc, graph=True) ts = [] for st, qs in items: ts += _time(lambda: jev.decide(st, qs, fc=fc, graph=True), n_rep) nq = float(np.mean([len(qs) for _, qs in items])) res[g] = dict(n=len(items), questions_per_call=nq, p50_ms=float(np.percentile(ts, 50)), p95_ms=float(np.percentile(ts, 95)), per_question_ms=float(np.percentile(ts, 50) / nq)) say(f" {g:32s} p50 {res[g]['p50_ms']:7.1f} ms p95 {res[g]['p95_ms']:7.1f} ms ({nq:.1f} q/call)") set_ffn_width(jev.lm, None) return res
@torch.no_grad()def questions_scaling(jev, fc, width, text=None): """Laya-style: 1, 5, 10, 50 questions on one state in one call.""" set_ffn_width(jev.lm, width) text = text or ("Hi, we were billed twice for March. Please refund the duplicate today or we will cancel our plan.") base_qs = [{"type": "choice", "instructions": "Which department should handle this?", "criteria": {"billing": "invoices, payments, refunds", "technical": "bugs, outages", "other": "everything else"}}, {"type": "score", "instructions": "How urgent is this?", "criteria": ["not urgent", "soon", "blocking"]}, {"type": "noul", "instructions": "Does the user threaten to cancel or leave?"}, {"type": "noul", "instructions": "Does the user explicitly request a refund?"}, {"type": "noul", "instructions": "Is the user angry?"}] out = {} for n in (1, 5, 10, 50): qs = [dict(base_qs[i % 5], instructions=base_qs[i % 5]["instructions"] + (f" (#{i})" if i >= 5 else "")) for i in range(n)] jev.decide(text, qs, fc=fc, graph=True) ts = _time(lambda: jev.decide(text, qs, fc=fc, graph=True), 10) out[n] = float(np.median(ts)) say(f" {n:3d} questions/call: {out[n]:6.1f} ms ({out[n] / n:5.1f} ms/q)") set_ffn_width(jev.lm, None) return out
@torch.no_grad()def tree_vs_naive(jev, DATA, fc, width, n=30): """openjev-style one pass per option vs the packed option tree (same model, eager path).""" set_ffn_width(jev.lm, width) rs = [r for r in DATA["typed"] if r["split"] == "eval"][:n] rows = {} for name, fn in (("tree (1 pass)", lambda p: jev.run(jev.pack([p]), fc)), ("naive (1 pass / option)", lambda p: [jev.run(jev.pack([q]), fc) for q in jev.isolate(p)])): ts = [] for r in rs: p = jev.plan(jev.encode_state(r["state"], fc), r["qs"], fc) fn(p) ts += _time(lambda: fn(p), 2) rows[name] = float(np.median(ts)) say(f" {name:26s} {rows[name]:7.1f} ms per typed-decisions case") set_ffn_width(jev.lm, None) return rows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315"""MM-Jev v3 end-to-end pipeline, run as a detached process on the Colab VM:
nohup python /content/pipeline.py > /content/pipe/stdout.log 2>&1 &
Independent of the local CLI connection. Every stage caches its output under /content/pipe and records completion instate.json; re-running the script resumes (data parts are cached, training resumes from the last checkpoint).Progress: /content/pipe/pipeline.log (one line per event), results: /content/pipe/results.json."""import gc, json, os, random, sys, time, tracebacksys.path.insert(0, "/content")os.environ.setdefault("TORCHINDUCTOR_COMPILE_THREADS", "4")import torch
P = "/content/pipe"; D = f"{P}/data"; A = f"{P}/assets"for d in (P, D, A): os.makedirs(d, exist_ok=True)LOG, STATE, RES = f"{P}/pipeline.log", f"{P}/state.json", f"{P}/results.json"MAX_TRAIN = int(os.environ.get("MMJEV_MAX_TRAIN", 36000))
WORK_REPO = os.environ.get("MMJEV_WORK_REPO") # e.g. fnruha0921/omnijev-work (HF Jobs); None = no hub sync_HUB_LOCK = __import__("threading").Lock()
def hub_upload(local, remote, background=True): """Best effort: a network error must never stop training.""" if not WORK_REPO or not os.path.exists(local): return def _go(): try: from huggingface_hub import HfApi with _HUB_LOCK: HfApi().upload_file(path_or_fileobj=local, path_in_repo=remote, repo_id=WORK_REPO, commit_message=f"sync {remote}") except Exception as e: # noqa: BLE001 log(f"[hub] upload {remote} failed: {repr(e)[:200]}") if background: __import__("threading").Thread(target=_go, daemon=True).start() else: _go()
def hub_restore(): """Pull what a previous (killed) job left behind: checkpoint, final adapter, stage state, results, log.""" if not WORK_REPO: return from huggingface_hub import hf_hub_download for remote, local in (("run/ckpt/last.pt", f"{P}/ckpt/last.pt"), ("run/adapter_final.pt", f"{P}/adapter_final.pt"), ("run/state.json", STATE), ("run/results.json", RES), ("run/pipeline.log", LOG)): if os.path.exists(local): continue try: os.makedirs(os.path.dirname(local), exist_ok=True) path = hf_hub_download(WORK_REPO, remote) __import__("shutil").copy(path, local) print("restored", remote, flush=True) except Exception: pass
def hub_heartbeat(every=300): def _loop(): while True: time.sleep(every) for loc, rem in ((LOG, "run/pipeline.log"), (RES, "run/results.json"), (STATE, "run/state.json")): hub_upload(loc, rem, background=False) __import__("threading").Thread(target=_loop, daemon=True).start()
def log(*a): with open(LOG, "a") as f: print(time.strftime("%m-%d %H:%M:%S"), *a, file=f, flush=True)
def state(): return json.load(open(STATE)) if os.path.exists(STATE) else {}
def mark(k, v=True): s = state(); s[k] = v json.dump(s, open(STATE + ".tmp", "w"), indent=1); os.replace(STATE + ".tmp", STATE)
def results(): return json.load(open(RES)) if os.path.exists(RES) else {}
def put_result(k, v): r = results(); r[k] = v json.dump(r, open(RES + ".tmp", "w"), indent=1, default=float); os.replace(RES + ".tmp", RES)
# ------------------------------------------------------------------------------------------ 1. modeldef load_model(): import mmjev, media from mmjev import MMJev, load_gemma3n, fp16_safe_vision torch.backends.cudnn.benchmark = True t0 = time.time() if not os.path.exists("/content/gemma3n/model-00004-of-00004.safetensors"): from huggingface_hub import snapshot_download snapshot_download("unsloth/gemma-3n-E4B-it", local_dir="/content/gemma3n") log(f"model downloaded in {time.time() - t0:.0f}s") base, proc = load_gemma3n("/content/gemma3n") from datasets import load_dataset cal = [x["image"].convert("RGB") for x in load_dataset("HuggingFaceM4/A-OKVQA", split="validation[:16]")] cal += [media.shapes_image([("circle", "red", 0.3, 0.4, 0.1)]), media.moving_video("square", "blue", "left")[0]] n = fp16_safe_vision(base.model.vision_tower, proc.image_processor(cal, return_tensors="pt")["pixel_values"]) jev = MMJev(base, proc) log(f"model loaded in {time.time() - t0:.0f}s, rescaled convs {n}, GPU {torch.cuda.memory_allocated() / 2**30:.1f}G") return jev
# ------------------------------------------------------------------------------------------ 2. data partsdef part(name, fn): path = f"{D}/{name}.pt" if os.path.exists(path): return torch.load(path, weights_only=False) t0 = time.time() recs = fn() torch.save(recs, path + ".tmp"); os.replace(path + ".tmp", path) log(f"[data] {name}: {len(recs)} records in {time.time() - t0:.0f}s") return recs
FAILED = []
def build_all(jev): DATA = {} ns = {"jev": jev, "DATA": DATA, "RUN_BUILD_MAIN": False, "__name__": "build_data"} exec(open("/content/build_data.py").read(), ns) if os.path.exists(f"{D}/base.pt"): # saved from an interactive kernel DATA.update(torch.load(f"{D}/base.pt", weights_only=False)) else: # rebuild the base parts, each cached def script(path, key): def f(): exec(open(path).read(), ns) return ns["DATA"][key] return f for key, fn in (("text", ns["build_text"]), ("jevbench", ns["build_jevbench"]), ("typed", ns["build_typed_decisions"]), ("btzsc", ns["build_btzsc"]), ("massive_xnli", ns["build_massive_xnli"]), ("image", ns["build_image"]), ("text2", script("/content/build_text2.py", "text2")), ("text3", script("/content/build_text3.py", "text3"))): DATA[key] = part(key, fn) if "audio" not in DATA: # ESC-50 (HF); its synthetic beeps task is excluded DATA["audio"] = part("audio", ns["build_audio"]) import build_mm_hf as M # every other image / audio / video set: HF datasets for name, fn in M.BUILDERS.items(): try: DATA[f"mm_{name}"] = part(f"mm_{name}", lambda fn=fn: fn(jev)) except Exception: log(f"[data] mm {name} FAILED: {traceback.format_exc()[-600:]}"); FAILED.append(name) gc.collect() import build_text4 as B for name, fn in B.BUILDERS.items(): try: DATA[f"t4_{name}"] = part(f"t4_{name}", fn) except Exception: log(f"[data] {name} FAILED: {traceback.format_exc()[-500:]}"); FAILED.append(name) gc.collect() tot = {k: len(v) for k, v in DATA.items()} log(f"[data] parts {tot}") return DATA
SYNTHETIC = {"count_syn", "beeps_count", "vid_direction", "vid_color_change", "vid_flash_count", "vid_av_beep"}
CAPS = {"image": 5000, "audio": 3500, "video": 2500, "text_base": 6000} # the rest of MAX_TRAIN: public text corpora
def train_split(DATA): import train as T T.EXCLUDE_TASKS |= SYNTHETIC rng = random.Random(0) buckets = {"image": [], "audio": [], "video": [], "text_base": [], "text_public": []} for k, v in DATA.items(): for r in v: if r["split"] != "train" or r["task"] in T.EXCLUDE_TASKS: continue if any(len(t) < 2 for t in r["targets"]) or not r["qs"]: continue # degenerate questions (a single option) carry no signal key = r["modality"] if r["modality"] != "text" else ("text_public" if k.startswith("t4_") else "text_base") buckets[key].append(r) recs = [] for key, v in buckets.items(): rng.shuffle(v) if key != "text_public": recs += v[:CAPS[key]] recs += buckets["text_public"][:max(0, MAX_TRAIN - len(recs))] rng.shuffle(recs) n_cal = max(300, len(recs) // 40) return recs[n_cal:], recs[:n_cal]
# ------------------------------------------------------------------------------------------ maindef main(): hub_restore() log("=== pipeline start ===") hub_heartbeat() jev = load_model() DATA = build_all(jev) if FAILED and not os.environ.get("MMJEV_ALLOW_SKIP"): log(f"PIPELINE FAILED: data parts failed {FAILED} -- fix and re-run (cached parts are reused)") return mark("data") import train as T import mmjev_eval as E E.LOGFILE = LOG T.LOG = LOG tr, cal = train_split(DATA) DATA.pop("video", None) # synthetic videos: neither trained on nor evaluated / timed log(f"train {len(tr)} / calib {len(cal)}; modalities " f"{ {m: sum(r['modality'] == m for r in tr) for m in ('text', 'image', 'audio', 'video')} }") if not state().get("trained"): T.train(jev, DATA, bs=int(os.environ.get("MMJEV_BS", 16)), recs=(tr, cal), ckpt_dir=f"{P}/ckpt", save_path=f"{P}/adapter_final.pt", on_ckpt=lambda path, step: hub_upload(path, "run/ckpt/last.pt")) hub_upload(f"{P}/adapter_final.pt", "run/adapter_final.pt", background=False) mark("trained") else: T.add_lora(jev) T.load_trainable(jev, torch.load(f"{P}/adapter_final.pt", weights_only=False)) cfgs = {"full": (T.FULL, None), "fast": (T.FAST, T.FAST_WIDTH)} temps = state().get("temps") or {n: T.fit_temperature_k(jev, cal, fc, w) for n, (fc, w) in cfgs.items()} mark("temps", temps); log(f"temperatures {temps}")
# accuracy: fastest benchmarks first, one log line per task order = ["jevbench_easy", "jevbench_original", "btzsc_agnews", "btzsc_emotiondair", "btzsc_banking77", "jevbench_hard", "typed_decisions", "massive_intent_en", "xnli_en", "massive_scenario_en", "massive_scenario_ko", "aokvqa", "pope", "scienceqa_img", "ai2d", "vqav2_yesno", "vqav2_count", "vqav2_other", "esc50_choice", "esc50_noul", "clotho_aqa", "urbansound8k", "speech_commands", "tempcompass", "mvbench_mini", "ucf101", "kinetics_mini", "boolq", "dbpedia14", "sst5"] snake = [dict(r, split="eval") for r in DATA.get("text2", []) if r["task"] == "snake_syn"] if snake: DATA["snake_eval"] = snake order.append("snake_syn") for n, (fc, w) in cfgs.items(): done = results().get(f"acc_{n}", {}) for t in order: if t in done: continue m = E.accuracy_suite(jev, DATA, fc, w, temps[n], tag=f"v3-{n}", tasks=[t]) done.update(m); put_result(f"acc_{n}", done) mark("accuracy")
# latency (compiled vision tower + CUDA-graph decoder), question scaling, tree vs naive vt = jev._core().vision_tower jev.vision_fn = torch.compile(lambda x: vt(pixel_values=x, do_pooling=False, return_dict=True).last_hidden_state, mode="max-autotune-no-cudagraphs", dynamic=False) for n, (fc, w) in cfgs.items(): if f"latency_{n}" not in results(): jev.temps_k = temps[n] put_result(f"latency_{n}", E.latency_suite(jev, DATA, fc, w)) put_result(f"qscale_{n}", E.questions_scaling(jev, fc, w)) if "tree_vs_naive" not in results(): put_result("tree_vs_naive", E.tree_vs_naive(jev, DATA, T.FAST, T.FAST_WIDTH)) mark("latency")
# demos import demos demos.OUT = A from mmjev import set_ffn_width set_ffn_width(jev.lm, T.FAST_WIDTH); jev._graphs = {}; jev.temps_k = temps["fast"] for seed in (3, 7, 11): r = demos.snake_demo(jev, T.FAST, seed=seed, name=f"snake_seed{seed}") log(f"[demo] snake seed {seed}: {r}") put_result(f"snake_seed{seed}", r) # multimodal cards on held-out raw media (fast config) ev = [r for v in DATA.values() for r in v if r["split"] == "eval" and r.get("raw")] picks = [("image", "aokvqa", 2), ("image", "scienceqa_img", 1), ("audio", "esc50_choice", 2), ("audio", "urbansound8k", 1), ("audio", "speech_commands", 1), ("video", "tempcompass", 2), ("video", "ucf101", 1), ("video", "mvbench_mini", 1)] cards = [] for mod, task, k in picks: for i, r in enumerate([x for x in ev if x["task"] == task][:k]): seg = r["raw"][0] name = f"{task}_{i + 1}" try: if mod == "image": qs = r["qs"] + [{"type": "noul", "instructions": "Is there at least one person in the image?"}, {"type": "choice", "instructions": "Where was this photo most likely taken?", "criteria": {"indoors": "inside a building or vehicle", "outdoors": "outside, open air"}}] res, ms = demos.image_demo(jev, T.FAST, seg.data, qs, name=name, title=f"Image: {task}") elif mod == "audio": qs = r["qs"] + [{"type": "noul", "instructions": "Is this sound made by an animal?"}, {"type": "noul", "instructions": "Is someone speaking in the recording?"}] res, ms = demos.audio_demo(jev, T.FAST, seg.data, qs, name=name, title="Audio: ESC-50 (held out)") else: qs = r["qs"] + [{"type": "noul", "instructions": "Is there a person in the video?"}, {"type": "score", "instructions": "How much motion is there in the video?", "criteria": ["almost static", "some motion", "a lot of motion"]}] res, ms = demos.video_demo(jev, T.FAST, seg.data, qs, audio=seg.audio, fps=seg.fps, name=name, title=f"Video: {task}") from mmjev import options_of gold = options_of(r["qs"][0])[0][r["ys"][0]] pred = res[0].get("choice", res[0].get("level", res[0].get("noul"))) cards.append(dict(name=name, gold=gold, pred=pred, latency_ms=round(ms, 1))) log(f"[demo] {cards[-1]}") except Exception: log(f"[demo] {name} failed: {traceback.format_exc()[-400:]}") put_result("demo_cards", cards) set_ffn_width(jev.lm, None) mark("demos") for f in os.listdir(A): if f.endswith((".mp4", ".png")): hub_upload(f"{A}/{f}", f"run/assets/{f}", background=False) log("=== PIPELINE DONE ===") for loc, rem in ((LOG, "run/pipeline.log"), (RES, "run/results.json"), (STATE, "run/state.json")): hub_upload(loc, rem, background=False)
if __name__ == "__main__": try: main() except BaseException: log("PIPELINE FAILED\n" + traceback.format_exc()[-3000:]) raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328"""Elastic training of MM-Jev (run inside the Colab kernel after build_data.py; `jev`, `DATA` in globals).
One run trains two inference configs that share every weight: full : 35 layers, FFN width 16384, media tokens kept fast : exit after layer 19 (head "20"), FFN width 8192 (MatFormer E2B slice), media tokens dropped after layer 8, 8 latent memory tokens per media segmentLoss per step = proper score(full) + proper score(fast) + lambda * KL(stopgrad p_full || p_fast) (self-distillation,LayerSkip / MatFormer style). LoRA r=16 on attention q/k/v/o only, so FFN slicing stays exact.Trains in a background thread; progress in /content/train.log."""import math, random, threading, time, jsonimport torch, torch.nn.functional as Ffrom torch.utils.checkpoint import checkpointfrom mmjev import FastConfig, decision_loss, set_ffn_width, QTYPES
FULL = FastConfig(n_latents=8, exit_layer=35, media_exit=None, sibling_from=14)FAST = FastConfig(n_latents=8, exit_layer=20, media_exit=8, sibling_from=14)FAST_WIDTH = 8192LOG = "/content/train.log"
def log(*a): with open(LOG, "a") as f: print(time.strftime("%H:%M:%S"), *a, file=f, flush=True)
class LoRALinear(torch.nn.Module): """y = W x + (B A x) * alpha / r ; W frozen fp16, A/B fp32 (B zero-initialised)."""
def __init__(self, base, r=16, alpha=32, dropout=0.05): super().__init__() self.base_layer = base self.lora_A = torch.nn.Parameter(torch.randn(r, base.in_features, device=base.weight.device) / math.sqrt(base.in_features)) self.lora_B = torch.nn.Parameter(torch.zeros(base.out_features, r, device=base.weight.device)) self.scale, self.drop = alpha / r, torch.nn.Dropout(dropout)
@property def weight(self): return self.base_layer.weight
def forward(self, x): y = self.base_layer(x) out_f, in_f = self.base_layer.weight.shape # smaller than the LoRA shapes when the FFN is sliced A = self.lora_A[:, :in_f].to(x.dtype) Bm = self.lora_B[:out_f].to(x.dtype) lx = torch.nn.functional.linear(torch.nn.functional.linear(self.drop(x), A), Bm) return y + lx * self.scale
@torch.no_grad()def reset_trainable(jev): """Fresh start: LoRA B = 0 (A re-drawn), heads = E[Yes] - E[No], latents re-initialised.""" for m in jev.lm.modules(): if isinstance(m, LoRALinear): m.lora_A.normal_().div_(math.sqrt(m.lora_A.shape[1])); m.lora_B.zero_() E = jev.lm.embed_tokens.weight w = (E[jev.yes_id].float() - E[jev.no_id].float())[None] for h in jev.heads.values(): h.weight.copy_(w); h.bias.zero_() init = jev._embed_ids(torch.tensor(jev._t(" summary"))).float().mean(0) jev.latents.copy_(init[None].repeat(jev.latents.shape[0], 1) + 0.02 * init.std() * torch.randn_like(jev.latents))
def add_lora(jev, r=16, alpha=32, mlp_from=10): """Attention q/k/v/o everywhere (layers 20-34 have no k/v: KV-shared) + MLP gate/up/down from layer `mlp_from`.""" for p in jev.base.parameters(): p.requires_grad = False n = 0 for li, layer in enumerate(jev.lm.layers): att = layer.self_attn for name in ("q_proj", "k_proj", "v_proj", "o_proj"): m = getattr(att, name, None) if isinstance(m, torch.nn.Linear): setattr(att, name, LoRALinear(m, r, alpha)); n += 1 if li >= mlp_from: for name in ("gate_proj", "up_proj", "down_proj"): m = getattr(layer.mlp, name) if isinstance(m, torch.nn.Linear): setattr(layer.mlp, name, LoRALinear(m, r, alpha)); n += 1 n_lora = sum(p.numel() for nme, p in jev.base.named_parameters() if "lora_" in nme) log(f"LoRA on {n} projections, {n_lora / 1e6:.1f}M params")
EXCLUDE_TASKS = {"typed_decisions", "snake_syn"} # benchmark train split + demo task: both kept out (zero-shot)
def train_records(DATA, calib_frac=0.05, seed=0, modalities=None, max_records=None): recs = [r for k, v in list(DATA.items()) for r in v if r["split"] == "train" and r["task"] not in EXCLUDE_TASKS and (modalities is None or r["modality"] in modalities)] rng = random.Random(seed) rng.shuffle(recs) if max_records: recs = recs[:max_records] n_cal = int(len(recs) * calib_frac) return recs[n_cal:], recs[:n_cal]
def batch_logits(jev, batch, fc, width): set_ffn_width(jev.lm, width) plans = [jev.plan(jev.encode_state(r["state"], fc), r["qs"], fc) for r in batch] pk = jev.pack(plans) return jev.run(pk, fc)
def step_loss(jev, batch, fc, width, teacher=None, kl_w=0.5): out = batch_logits(jev, batch, fc, width) loss, n, probs = 0.0, 0, [] for r, per_q in zip(batch, out): pq = [] for q, lg, tgt in zip(r["qs"], per_q, r["targets"]): t = torch.tensor(tgt, device=lg.device, dtype=torch.float32) loss = loss + decision_loss(lg, t, q["type"]) + 0.1 * ((torch.softmax(lg, -1) - t) ** 2).sum() pq.append(torch.softmax(lg.detach(), -1)) n += 1 probs.append(pq) if teacher is not None: kl = 0.0 for per_q, tq in zip(out, teacher): for lg, pt in zip(per_q, tq): kl = kl + F.kl_div(torch.log_softmax(lg, -1), pt, reduction="sum") loss = loss + kl_w * kl return loss / max(n, 1), probs
def enable_ckpt(jev): """Gradient checkpointing per decoder layer (the shared-KV dict is refilled identically on recompute).""" for layer in jev.lm.layers: if not hasattr(layer, "_orig_fwd"): layer._orig_fwd = layer.forward
def fwd(*a, _l=layer, **k): if _l.training and torch.is_grad_enabled(): return checkpoint(_l._orig_fwd, *a, use_reentrant=False, **k) return _l._orig_fwd(*a, **k) layer.forward = fwd
TRAIN_MAX_STATE, TRAIN_MAX_OPTS = 2000, 40
def cap_record(r, rng): """Training-time cost cap: truncate long text states; for questions with > TRAIN_MAX_OPTS options keep the gold option plus a random subset (label-subsampling augmentation), renormalising soft targets.""" from mmjev import Seg r = dict(r) r["state"] = [Seg(s.kind, s.data[:TRAIN_MAX_STATE], s.audio, s.fps) if s.kind == "text" else s for s in r["state"]] qs, ts, ys = [], [], [] for q, t, y in zip(r["qs"], r["targets"], r["ys"]): if q["type"] == "choice" and len(t) > TRAIN_MAX_OPTS: keys = list(q["criteria"]) keep = sorted([y] + rng.sample([i for i in range(len(keys)) if i != y], TRAIN_MAX_OPTS - 1)) q = dict(q, criteria={keys[i]: q["criteria"][keys[i]] for i in keep}) tt = [t[i] for i in keep]; sm = sum(tt) or 1.0 t = [x / sm for x in tt]; y = keep.index(y) qs.append(q); ts.append(t); ys.append(y) r.update(qs=qs, targets=ts, ys=ys) return r
def est_len(r): n = 0 for s in r["state"]: n += len(s.data) // 4 if s.kind == "text" else 64 if s.kind == "image" else 150 if s.kind == "video" else 60 for q in r["qs"]: n += 30 + 12 * len(q.get("criteria") or [0, 0]) return n
def train(jev, DATA, epochs=1, bs=4, lr_lora=2e-4, lr_head=1e-3, warmup=50, modalities=None, max_records=None, save_path="/content/mmjev_adapter.pt", lora=True, ckpt_dir=None, ckpt_every=400, recs=None, on_ckpt=None): """Elastic training; with ckpt_dir it checkpoints (adapter + optimizer + scaler + step) and resumes.""" import os if recs is None: tr, cal = train_records(DATA, modalities=modalities, max_records=max_records) else: tr, cal = recs globals()["CALIB"] = cal log(f"train records {len(tr)} calib {len(cal)}") if lora: add_lora(jev) enable_ckpt(jev) params = [ {"params": [p for n, p in jev.base.named_parameters() if "lora_" in n], "lr": lr_lora}, {"params": list(jev.heads.parameters()) + [jev.latents], "lr": lr_head}, ] opt = torch.optim.AdamW(params, weight_decay=0.0) steps = epochs * math.ceil(len(tr) / bs) sched = torch.optim.lr_scheduler.LambdaLR( opt, lambda s: min(1.0, (s + 1) / warmup) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / steps)))) scaler = torch.amp.GradScaler("cuda") start = 0 if ckpt_dir: os.makedirs(ckpt_dir, exist_ok=True) last = f"{ckpt_dir}/last.pt" if os.path.exists(last): ck = torch.load(last, map_location="cpu", weights_only=False) load_trainable(jev, ck) opt.load_state_dict(ck["opt"]); scaler.load_state_dict(ck["scaler"]); sched.load_state_dict(ck["sched"]) start = ck["step"] log(f"RESUMED from step {start}") rng = random.Random(0) tr = [cap_record(r, rng) for r in tr] # length-grouped batches: sort inside chunks of 64 batches, then shuffle batch order (less padding waste) order = list(range(len(tr))); rng.shuffle(order) grouped = [] for c in range(0, len(order), 64 * bs): chunk = sorted(order[c:c + 64 * bs], key=lambda i: est_len(tr[i])) grouped += [chunk[j:j + bs] for j in range(0, len(chunk), bs)] rng.shuffle(grouped) order = [i for b in grouped for i in b] jev.train() t0, ema = time.time(), None step = start for s in range(start * bs, len(order) * epochs, bs): batch = [tr[order[i % len(order)]] for i in range(s, min(s + bs, len(order) * epochs))] try: opt.zero_grad(set_to_none=True) lf, pf = step_loss(jev, batch, FULL, None) scaler.scale(lf).backward() ls, _ = step_loss(jev, batch, FAST, FAST_WIDTH, teacher=pf) scaler.scale(ls).backward() set_ffn_width(jev.lm, None) scaler.unscale_(opt) torch.nn.utils.clip_grad_norm_([p for g in params for p in g["params"]], 1.0) scaler.step(opt); scaler.update(); sched.step() except torch.OutOfMemoryError: set_ffn_width(jev.lm, None) opt.zero_grad(set_to_none=True); torch.cuda.empty_cache() log(f"OOM at step {step}, skipped (tasks {[r['task'] for r in batch]})") step += 1; sched.step() continue step += 1 v = (float(lf), float(ls)) ema = v if ema is None else (0.98 * ema[0] + 0.02 * v[0], 0.98 * ema[1] + 0.02 * v[1]) if step % 50 == 0 or step == start + 1: el = time.time() - t0 done = step - start log(f"step {step}/{steps} loss full {ema[0]:.3f} fast {ema[1]:.3f} | {el / done:.2f}s/step " f"ETA {(steps - step) * el / done / 60:.0f}m | mem {torch.cuda.max_memory_allocated() / 2**30:.1f}G") if ckpt_dir and step % ckpt_every == 0: ck = trainable_state(jev) ck.update(opt=opt.state_dict(), scaler=scaler.state_dict(), sched=sched.state_dict(), step=step) torch.save(ck, f"{ckpt_dir}/last.tmp"); os.replace(f"{ckpt_dir}/last.tmp", f"{ckpt_dir}/last.pt") if on_ckpt: on_ckpt(f"{ckpt_dir}/last.pt", step) jev.eval() set_ffn_width(jev.lm, None) save(jev, save_path) log(f"TRAIN DONE {time.time() - t0:.0f}s")
def trainable_state(jev): return {"lora": {n: p.detach().cpu().clone() for n, p in jev.base.named_parameters() if "lora_" in n}, "heads": {k: v.cpu().clone() for k, v in jev.heads.state_dict().items()}, "latents": jev.latents.detach().cpu().clone()}
@torch.no_grad()def load_trainable(jev, ck): params = dict(jev.base.named_parameters()) for n, v in ck["lora"].items(): params[n].copy_(v.to(params[n].device)) jev.heads.load_state_dict(ck["heads"]) jev.latents.copy_(ck["latents"].to(jev.latents.device))
def save(jev, path): torch.save(trainable_state(jev), path)
def k_bucket(k): return "2" if k <= 2 else "3-5" if k <= 5 else "6-10" if k <= 10 else "11-30" if k <= 30 else "31+"
@torch.no_grad()def fit_temperature_k(jev, recs, fc, width, bs=8): """Temperature per (question type, option-count bucket) -- a 2-way noul and a 72-way choice need different scaling.""" jev.eval() per = {} for s in range(0, len(recs), bs): batch = recs[s:s + bs] out = batch_logits(jev, batch, fc, width) for r, per_q in zip(batch, out): for q, lg, tgt in zip(r["qs"], per_q, r["targets"]): per.setdefault(f"{q['type']}:{k_bucket(len(lg))}", []).append((lg.float().cpu(), torch.tensor(tgt))) set_ffn_width(jev.lm, None) grid = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0] temps = {} for key, items in per.items(): if len(items) < 20: continue temps[key] = min(grid, key=lambda T: sum(float(-(tg * torch.log_softmax(lg / T, -1)).sum()) for lg, tg in items)) return temps
@torch.no_grad()def fit_temperature(jev, recs, fc, width, bs=8): """Per question type temperature by NLL grid search on the calibration records.""" jev.eval() per = {t: [] for t in QTYPES} for s in range(0, len(recs), bs): batch = recs[s:s + bs] out = batch_logits(jev, batch, fc, width) for r, per_q in zip(batch, out): for q, lg, tgt in zip(r["qs"], per_q, r["targets"]): per[q["type"]].append((lg.float().cpu(), torch.tensor(tgt))) set_ffn_width(jev.lm, None) temps = {} for t, items in per.items(): if not items: temps[t] = 1.0; continue best = min((sum(float(-(tg * torch.log_softmax(lg / T, -1)).sum()) for lg, tg in items), T) for T in [0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.15, 1.3, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0]) temps[t] = best[1] return temps
def start(jev, DATA, **kw): th = threading.Thread(target=lambda: _safe(train, jev, DATA, **kw), daemon=True) th.start() return th
def _safe(fn, *a, **k): try: fn(*a, **k) except Exception as e: # noqa: BLE001 import traceback log("TRAIN FAILED", repr(e), traceback.format_exc()[-2000:])README.mdAdded+11
code/build_data.pyAdded+394
code/build_mm_hf.pyAdded+335
code/build_text2.pyAdded+148
code/build_text3.pyAdded+134
code/build_text4.pyAdded+211
code/demos.pyAdded+202
code/media.pyAdded+59
code/mmjev.pyAdded+836
code/mmjev_eval.pyAdded+200
code/pipeline.pyAdded+315
code/train.pyAdded+328