Spaces:
Running on Zero

READ-demo / readcore /tools /multisensor_nonbox.py
fnc1901's picture
READ demo: app, study-code subset, demo data (part 6)
32769b9 verified
Raw History Blame Contribute Delete
52.9 kB
#!/usr/bin/env python
"""E2: non-box free space, source x format (docs/pilot_artifacts/2026-10-30/NONBOX_RASTER_SPEC.md, approved 30 Oct).
Arms (each continues its parent for the same 1,000 updates on one stream):
J j1 detector as tokens, no raster
T j2t detector as text, no raster
R j1 + raster tokens the shared view V as 210 cell tokens (raster branch aligned first: phase `align`)
RG j1 + grid text V written out as text (strict match to R)
RL j1 + unknown-obstacle list text (reviewer baseline)
R_T, RG_T the R / RG pair on the j2t base (exploratory, one seed)
J_A j1, text-anchored J after aligning its object-token projector and branches (LLM and LoRA frozen) to
make the reader reproduce T's text from the tokens (phase `align`): the method arm
R_NA j1 + raster tokens R without the alignment stage (ablation)
RI j1 + raster image V as one bird's-eye image through the frozen vision encoder, one visual token per cell
(validity addendum §7: added 1 Nov, after dev results; RG's recipe, no alignment)
LI1 j1 + LiDAR range images the keyframe sweep drawn in the six camera views (1 Oct pilot renderer, pre-rendered:
tools/build_lidar_image_cache.py); a supporting baseline, not a format arm (addendum §9)
The raster block sits after the question, with the same header for every raster arm; only its body differs
(placeholders, grid text, list, image). LI1's LiDAR range images sit in the same place, under their own header.
Free-space questions are kept verbatim: their <t seconds> stamp is the joint prompt's own frame anchor
(templates_v2.stamp).
Phases: stream (CPU) | align (R, R_T: raster branch; J_A: object tokens) | train | evaluate.
"""
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime, timezone
import hashlib
import json
import math
import os
from pathlib import Path
import random
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT), str(ROOT / "src"), str(ROOT / "tools")]
import numpy as np # noqa: E402
import torch # noqa: E402
from mmcrfm_utonia.data import nonbox_raster as nr # noqa: E402
from mmcrfm_utonia.data import readout_ladder as ladder # noqa: E402
from mmcrfm_utonia.data.camera_views import ( # noqa: E402
CAMERA_CHANNELS, CAMERA_LABELS, LIDAR_IMAGE_MARKER, RASTER_IMAGE_MARKER)
from mmcrfm_utonia.eval import freespace_score as fs_score # noqa: E402
from mmcrfm_utonia.raster_branch import RASTER_TOKEN, RasterBranch, RasterInjector # noqa: E402
from tools import multisensor_readout_ladder as tool # noqa: E402
from tools.multisensor_selective import guard_radar_prefix # noqa: E402
SEED = 20261031
ARMS = dict(J=("j1", None), T=("j2t", None), R=("j1", "tokens"), RG=("j1", "grid"), RL=("j1", "list"),
R_T=("j2t", "tokens"), RG_T=("j2t", "grid"), J_A=("j1", None), R_NA=("j1", "tokens"), RI=("j1", "image"),
LI1=("j1", "lidar_cam"))
ALIGNED = {"R": "raster", "R_T": "raster", "J_A": "detector"} # arms whose training starts after `align`
FS_SHARE = 0.5 # of the 8,000 training draws; the rest is replay of the joint stream
FS_DARK_BLUR_P = 0.25 # free-space training items with the dark/blurred camera
STEPS, BATCH, WARMUP = 1000, 8, 30
LORA_LR, SENSOR_LR, RASTER_LR = 1e-5, 2e-5, 2e-4
SAVE_EVERY = 250
ALIGN_STEPS, ALIGN_BATCH, ALIGN_WARMUP = 2000, 16, 50
ALIGN_INSTRUCTION = "Write out the occupancy grid ahead."
DETECTOR_ALIGN_BATCH, DETECTOR_ALIGN_OBJECTS = 8, 8 # object-token prompts are ~3k tokens; 8 objects' lines per target
MAX_NEW_TOKENS = 48
FS_FILES = dict(train="train/geom_stage_freespace_v2.json", dev="train/geom_stage_freespace_v2_heldout_phrasing.json",
val="test/geom_stage_freespace_v2_test_heldout_phrasing.json",
miss_dev="train/geom_stage_freespace_v1_heldout_phrasing.json",
miss_val="test/geom_stage_freespace_v1_test_heldout_phrasing.json")
SPLIT_OF = dict(train="train", dev="val", val="val") # free-space split -> split-file role; --split val needs the
# val config (tools/prepare_nonbox_val_inputs.py)
CONDITIONS = ("clean", "camera_dark_blur", "camera_removed", "donor:camera_dark_blur", "miss:camera_dark_blur",
"retention:clean")
RETENTION_SETS = ("r1b_eval", "addr_eval", "sel_eval", "s4_eval", "m1_eval", "m2_eval", "m3_eval")
RETENTION_LIMIT = None # every record of the seven development sets (3,960): the method contrast J_A - J
CURVE_CONDITIONS = ("camera_dark_blur",) # checkpoints 250 / 500 / 750: prose_free only
BOX_Z = (0.2, 2.0)
def now():
return datetime.now(timezone.utc).isoformat()
def sha256_text(text):
return hashlib.sha256(text.encode()).hexdigest()
# ---------------------------------------------------------------------------------------------------- records
def fs_records(fs_root, name, scenes):
"""Free-space records of ``scenes`` as E2 records (one per scene, frame and family)."""
out = {}
for r in json.loads((Path(fs_root) / FS_FILES[name]).read_text()):
if r["scene_token"] not in scenes:
continue
fs = r["fs"]
rid = f"{r['scene_token']}/{fs['frame_index']:02d}/{r['family']}"
if rid in out:
raise ValueError(f"duplicate free-space record {rid}")
out[rid] = dict(id=rid, scene_token=r["scene_token"], keyframe=int(fs["frame_index"]), rung="fs",
family=r["family"], region=fs.get("region"), value=fs["value"],
stratum=fs.get("stratum"), question=r["question"], answer=r["answer"])
return [out[k] for k in sorted(out)]
def split_scenes(args, role):
return set(json.loads(Path(args.split_file).read_text())[role])
def region_box(region):
side, lo, hi = region.split("_")
y = dict(path=(-1.25, 1.25), left=(1.25, 4.75), right=(-4.75, -1.25))[side]
return float(lo), float(hi), y[0], y[1]
def row_boxes(rows, layout):
"""(x, y, z, length, width, height, yaw) of every supplied object row."""
g, c = layout.geometry_start, layout.xyz_start
out = []
for r in rows:
length, width, height, s, co = (float(v) for v in r[g:g + 5])
x, y, z = (float(v) for v in r[c:c + 3])
out.append((x, y, z, length, width, height, math.atan2(s, co)))
return out
def box_hits_region(box, region):
from shapely.geometry import Polygon, box as rect
x, y, z, length, width, height, yaw = box
if z + height / 2 < BOX_Z[0] or z - height / 2 > BOX_Z[1]:
return False
corners = [(x + dx * math.cos(yaw) - dy * math.sin(yaw), y + dx * math.sin(yaw) + dy * math.cos(yaw))
for dx, dy in ((length / 2, width / 2), (length / 2, -width / 2), (-length / 2, -width / 2),
(-length / 2, width / 2))]
x_lo, x_hi, y_lo, y_hi = region_box(region)
return Polygon(corners).intersects(rect(x_lo, y_lo, x_hi, y_hi))
# ----------------------------------------------------------------------------------------------------- source
class Rasters:
def __init__(self, root):
self.root, self.cache = Path(root), {}
def __call__(self, scene, frame):
if scene not in self.cache:
if len(self.cache) >= 256:
self.cache.pop(next(iter(self.cache)))
self.cache[scene] = np.load(self.root / f"{scene}.npz")["raster"]
return self.cache[scene][frame].astype(np.float32)
def frames(self, scene):
return int(np.load(self.root / f"{scene}.npz", mmap_mode="r")["raster"].shape[0])
LI1_HEADER = ("LiDAR range images: the LiDAR returns drawn in each camera view, coloured by horizontal distance from "
"the ego vehicle (dark red near, blue at 50 m or more); black = no return.")
class LidarImages:
"""Arm LI1's pre-rendered range images (tools/build_lidar_image_cache.py): (6, 288, 512, 3) uint8 per frame, in
CAMERA_CHANNELS order, and the sample's files per frame (frames.json)."""
def __init__(self, root):
self.root = Path(root)
self.files = json.loads((self.root / "frames.json").read_text())
def __call__(self, scene, frame):
if not 0 <= frame < len(self.files[scene]):
raise IndexError(f"{scene} has no LiDAR image frame {frame}")
images = np.load(self.root / scene / f"{frame:02d}.npz")["images"]
if images.shape != (len(CAMERA_CHANNELS), 288, 512, 3) or images.dtype != np.uint8:
raise ValueError(f"{scene}/{frame}: LiDAR images {images.shape} {images.dtype}")
return images
def camera_files(self, scene, frame):
return [Path(self.files[scene][frame][ch]).name for ch in CAMERA_CHANNELS]
class RasterSource(tool.SceneSource):
"""``SceneSource`` whose items carry the raster block of the arm (none, tokens, grid, list, image or LiDAR range
images)."""
def __init__(self, args, split, raster_mode, raster_root, lidar_image_root=None, **kw):
super().__init__(args, split, **kw)
if raster_mode not in (None, "tokens", "grid", "list", "image", "lidar_cam"):
raise ValueError(f"unknown raster mode {raster_mode!r}")
if raster_mode == "lidar_cam" and lidar_image_root is None:
raise ValueError("LI1 needs --lidar-image-root")
self.raster_mode, self.rasters = raster_mode, Rasters(raster_root)
self.lidar_images = LidarImages(lidar_image_root) if raster_mode == "lidar_cam" else None
def raster_block(self, scene, frame, rows, degradation=None, target=None, raster_from=None):
"""(text block, cell features (tokens) / PIL image (image) / PIL images (lidar_cam) / None) of the raster or
LiDAR images the item shows."""
rscene, rframe = raster_from or (scene, frame)
if self.raster_mode == "lidar_cam": # LiDAR, not camera views: no camera condition reaches them
from PIL import Image
lines = [f"{CAMERA_LABELS[ch]}: {LIDAR_IMAGE_MARKER}" for ch in CAMERA_CHANNELS]
return LI1_HEADER + "\n" + "\n".join(lines), [Image.fromarray(a) for a in self.lidar_images(rscene, rframe)]
n, h, seen = nr.view(self.rasters(rscene, rframe))
if self.raster_mode == "tokens":
return nr.VIEW_HEADER + "\n" + RASTER_TOKEN * nr.N_VIEW, torch.from_numpy(nr.cell_features(n, h, seen))
if self.raster_mode == "grid":
return nr.VIEW_HEADER + "\n" + nr.grid_text(n, h, seen), None
if self.raster_mode == "image": # LiDAR, not a camera view: no camera condition reaches it
from PIL import Image
return (nr.VIEW_HEADER + "\n" + nr.IMAGE_LEGEND + "\n" + RASTER_IMAGE_MARKER,
Image.fromarray(nr.view_image(n, h, seen)))
if degradation is not None and degradation[0] == "lidar_box_dropout": # the boxes the item will show
keep = ladder.surviving_objects(len(rows), target, tool.BOX_DROP_FRACTION,
torch.Generator().manual_seed(int(degradation[1])))
rows = rows[keep]
boxes = [(x, y, length, width, yaw) for x, y, _, length, width, _, yaw in row_boxes(rows, self.layout)]
covered = nr.covered_by_boxes(boxes)
return nr.LIST_HEADER + "\n" + nr.unknown_obstacles_text(n, h, covered), None
def _item(self, raw, frame, rows, question, answer, ids=None, target=None, degradation=None, raster_from=None):
if self.raster_mode is None:
if raster_from is not None:
raise ValueError("a raster donor needs a raster arm")
return super()._item(raw, frame, rows, question, answer, ids, target, degradation)
block, extra = self.raster_block(raw["scene_token"], frame, rows, degradation, target, raster_from)
item = super()._item(raw, frame, rows, f"{question}\n\n{block}", answer, ids, target, degradation)
if self.raster_mode == "tokens":
item["raster_cells"] = extra
elif self.raster_mode == "image":
item["raster_image"] = extra
elif self.raster_mode == "lidar_cam":
own = self.lidar_images.camera_files(raw["scene_token"], frame)
shown = [Path(p).name for p in item.get("image_paths") or []]
if raster_from is None and shown and shown != own: # the same nuScenes sample as the camera images
raise ValueError(f"{raw['scene_token']}/{frame}: LiDAR images and camera images differ in sample")
item["lidar_images"] = extra
return item
def fs_item(self, record, degradation=None, raster_from=None, drop_region_boxes=False):
"""Item of a free-space record: every detected object of the keyframe, nearest first, labelled obj1, obj2, ...
in the shuffled order of the multi-object rungs (sel/addr; the detector text then names each object). None
when the keyframe supplies no object, which the joint input cannot represent."""
scene, frame = record["scene_token"], record["keyframe"]
raw = self.raw(scene)
features, _ = ladder.scene_rows(raw)
objects = self.objects(scene, frame)
rows = features[[o["row"] for o in objects]]
ids = ladder.object_ids(scene, frame, len(objects), tool.SEED, salt="fs")
dropped = 0
if drop_region_boxes:
keep = [i for i, b in enumerate(row_boxes(rows, self.layout)) if not box_hits_region(b, record["region"])]
dropped = len(rows) - len(keep)
rows, ids = rows[keep], [ids[i] for i in keep]
if len(rows) == 0:
return None, dropped
return self._item(raw, frame, rows, record["question"], record["answer"], ids, None, degradation,
raster_from), dropped
class RasterCollator:
"""The ladder collator, staging the batch's raster cells for the injector right before the forward."""
def __init__(self, base, injector=None):
self.base, self.injector = base, injector
def _stage(self, samples):
if self.injector is None:
if any("raster_cells" in s for s in samples):
raise ValueError("raster cells without a raster branch")
return
self.injector.stage(torch.stack([s["raster_cells"] for s in samples]))
def __call__(self, samples):
self._stage(samples)
return self.base(samples)
def encode_prompts(self, samples):
self._stage(samples)
return self.base.encode_prompts(samples)
# ------------------------------------------------------------------------------------------------------ model
def load_arm(options, checkpoint, arm, train, raster_branch=None):
"""Model, processor, collator, args and (raster arms) the branch and injector; ``raster_branch`` overrides the
checkpoint's branch file (the aligned branch at the start of training)."""
parent, mode = ARMS[arm]
model, processor, collator, args, _ = tool.load(options, checkpoint, train=train, radar=True)
spec = getattr(model, "ladder_spec", {})
text_parent = bool(spec.get("measured_text")) and not spec.get("sensor_tokens", True)
if not spec.get("camera") or text_parent != (parent == "j2t"):
raise ValueError(f"{checkpoint} does not continue {parent} (spec {spec})")
branch = injector = None
if mode == "tokens":
branch = RasterBranch(int(tool.active_projector(model).config.llm_dim), seed=options.seed).to(model.device)
state_path = Path(raster_branch or Path(checkpoint) / "ladder_raster_branch.pt")
if state_path.is_file():
branch.load_state_dict(torch.load(state_path, map_location="cpu")["state_dict"])
elif not train:
raise FileNotFoundError(f"{state_path}: an R checkpoint needs its raster branch")
placeholder = processor.tokenizer.convert_tokens_to_ids(RASTER_TOKEN)
injector = RasterInjector(model, branch, placeholder)
model.nonbox_raster_branch = branch
return model, processor, RasterCollator(collator, injector), args, injector
def save_arm(model, processor, destination, state):
tool.save(model, processor, destination, state)
branch = getattr(model, "nonbox_raster_branch", None)
if branch is not None:
torch.save(dict(state_dict={k: v.detach().cpu() for k, v in branch.state_dict().items()}),
destination / "ladder_raster_branch.pt")
def source_for(options, model, args, arm, split_role, motion_labels=None):
spec = model.ladder_spec
return RasterSource(args, split_role, ARMS[arm][1], options.raster_root, options.lidar_image_root, radar=True,
motion_labels=motion_labels, camera=True, measured_text=spec.get("measured_text", False),
sensor_tokens=spec.get("sensor_tokens", True))
# ----------------------------------------------------------------------------------------------------- stream
def stream_phase(options):
"""One training stream for every arm: 8,000 draws, FS_SHARE free-space v2 records of the 630 training scenes
(natural family mix, without replacement), the rest replay of the joint stream (tool.joint_schedule, j1's
quotas and degradations); free-space items get the dark/blurred camera with probability FS_DARK_BLUR_P."""
import infer
args = infer.resolve_inference_settings(options.config, {}, False)
train_scenes = split_scenes(args, "train")
fs = fs_records(options.fs_root, "train", train_scenes)
need = STEPS * BATCH
n_fs = int(round(FS_SHARE * need))
rng = random.Random(f"{SEED}:stream")
fs_part = rng.sample(fs, n_fs)
sets, _ = tool.load_sets(options.run_root)
replay_steps = (need - n_fs) // BATCH
order, degradations = tool.joint_schedule("j1", sets, replay_steps, BATCH, SEED)
entries = [dict(kind="joint", id=r["id"], rung=r["rung"], degradation=d) for r, d in zip(order, degradations)]
for i, r in enumerate(fs_part):
g = random.Random(f"{SEED}:fs-degrade:{i}")
d = ["camera_dark_blur", g.randrange(2 ** 31)] if g.random() < FS_DARK_BLUR_P else None
entries.append(dict(kind="fs", record=r, degradation=d))
rng.shuffle(entries)
if len(entries) != need:
raise ValueError(f"stream has {len(entries)} entries, expected {need}")
payload = dict(spec="docs/pilot_artifacts/2026-10-30/NONBOX_RASTER_SPEC.md", seed=SEED, steps=STEPS, batch=BATCH,
fs_share=FS_SHARE, fs_dark_blur_p=FS_DARK_BLUR_P, fs_file=FS_FILES["train"],
fs_file_sha256=hashlib.sha256((Path(options.fs_root) / FS_FILES["train"]).read_bytes()).hexdigest(),
counts=dict(Counter(e["kind"] if e["kind"] == "joint" else e["record"]["family"] for e in entries)),
entries=entries)
text = json.dumps(payload, sort_keys=True)
options.stream.parent.mkdir(parents=True, exist_ok=True)
options.stream.write_text(text)
print(json.dumps(dict(stream=str(options.stream), sha256=sha256_text(text), counts=payload["counts"])))
def load_stream(path, expected=None):
text = Path(path).read_text()
digest = sha256_text(text)
if expected and digest != expected:
raise ValueError(f"stream {path} has sha256 {digest}, expected {expected}")
return json.loads(text), digest
def stream_item(source, entry, joint_by_id):
if entry["kind"] == "fs":
d = tuple(entry["degradation"]) if entry["degradation"] else None
item, _ = source.fs_item(entry["record"], degradation=d)
return item
d = tuple(entry["degradation"]) if entry["degradation"] else None
item, _ = source.item(joint_by_id[entry["id"]], degradation=d)
return item
# ------------------------------------------------------------------------------------------------ training
def optimizer_groups(model):
tool.enable_prefix_training(model, lora=True)
named = [(n, p) for n, p in model.named_parameters() if p.requires_grad]
groups = [dict(params=[p for n, p in named if "pc_prefix" in n], lr=SENSOR_LR, name="pc_prefix"),
dict(params=[p for n, p in named if "pc_prefix" not in n], lr=LORA_LR, name="lora")]
for name in ("class", "radar"):
branch = getattr(model, f"ladder_{name}_branch")
if branch is not None:
branch.requires_grad_(True)
groups.append(dict(params=list(branch.parameters()), lr=SENSOR_LR, name=f"{name}_branch"))
if model.nonbox_raster_branch is not None:
model.nonbox_raster_branch.requires_grad_(True)
groups.append(dict(params=list(model.nonbox_raster_branch.parameters()), lr=RASTER_LR, name="raster_branch"))
if len({id(p) for g in groups for p in g["params"]}) != sum(len(g["params"]) for g in groups):
raise ValueError("a parameter sits in two optimizer groups")
return [g for g in groups if g["params"]]
def train(options):
from transformers import set_seed
from tools.multisensor_reward_training import on_device, sft_loss
tool.require_device("E2 training")
started = time.monotonic()
set_seed(options.seed)
stream, digest = load_stream(options.stream, options.stream_sha256)
sets, _ = tool.load_sets(options.run_root)
joint_by_id = {r["id"]: r for name, records in sets.items() if name.endswith("_train") for r in records}
model, processor, collator, args, injector = load_arm(options, options.warm_checkpoint, options.arm, train=True,
raster_branch=options.raster_branch)
if ALIGNED.get(options.arm) == "raster" and options.raster_branch is None and not options.smoke:
raise ValueError(f"{options.arm} starts from the aligned raster branch (--raster-branch)")
if options.arm == "R_NA" and options.raster_branch is not None:
raise ValueError("R_NA is the arm without the alignment stage")
groups = optimizer_groups(model)
optimizer = torch.optim.AdamW([{k: v for k, v in g.items() if k != "name"} for g in groups], weight_decay=0.0)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda s: min(1.0, (s + 1) / WARMUP))
source = source_for(options, model, args, options.arm, "train", sets["motion_labels"])
steps, batch_size = options.max_steps, (2 if options.smoke else BATCH)
options.chunk = options.chunk or 2
entries = stream["entries"]
result = dict(arm=options.arm, seed=options.seed, warm_checkpoint=str(options.warm_checkpoint),
radar_channels=model.ladder_radar, radar_zeroed=model.ladder_radar_zeroed,
spec=dict(model.ladder_spec),
raster_branch=str(options.raster_branch) if options.raster_branch else None,
stream_sha256=digest, lrs=dict(lora=LORA_LR, sensor=SENSOR_LR, raster=RASTER_LR),
batch_size=batch_size, chunk=options.chunk, warmup_steps=WARMUP, planned_steps=steps, started_at=now(),
groups={g["name"]: sum(p.numel() for p in g["params"]) for g in groups})
print(json.dumps(dict(event="e2_training_ready", **result)), flush=True)
options.output_dir.mkdir(parents=True, exist_ok=True)
tally = Counter()
order = list(range(len(entries)))
random.Random(f"{SEED}:order:{options.seed}").shuffle(order) # seeds see the stream in different orders
step = 0
with (options.output_dir / "metrics.jsonl").open("x") as metrics:
for step in range(1, steps + 1):
batch_entries = [entries[i] for i in order[(step - 1) * batch_size:step * batch_size]]
items = []
for e in batch_entries:
item = stream_item(source, e, joint_by_id)
if item is None:
tally[f"undefined:{e['kind']}"] += 1
continue
tally[e["kind"]] += 1
items.append(item)
optimizer.zero_grad(set_to_none=True)
log = dict(step=step, examples=len(items), loss=0.0)
for start in range(0, len(items), options.chunk):
part = items[start:start + options.chunk]
batch = on_device(collator(part), model.device)
loss = sft_loss(model, batch) * (len(part) / len(items))
if not torch.isfinite(loss):
raise ValueError("nonfinite SFT loss")
loss.backward()
log["loss"] += float(loss.detach())
params = [p for g in groups for p in g["params"]]
log["grad_norm"] = float(torch.nn.utils.clip_grad_norm_(params, 1.0, error_if_nonfinite=True))
optimizer.step()
scheduler.step()
if model.nonbox_raster_branch is not None:
log["raster_scale"] = float(model.nonbox_raster_branch.scale)
if torch.cuda.is_available():
log["max_memory_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)
log["seconds"] = time.monotonic() - started
metrics.write(json.dumps(log) + "\n")
metrics.flush()
if step % 10 == 0 or step == 1:
print(json.dumps(log), flush=True)
if step % SAVE_EVERY == 0 and step != steps:
save_arm(model, processor, options.output_dir / f"checkpoint-{step}", dict(step=step, **result))
if step != steps:
raise RuntimeError(f"stopped at {step} of {steps} updates")
result.update(optimizer_steps=step, seconds=time.monotonic() - started, tally=dict(tally), finished_at=now())
final = options.output_dir / f"checkpoint-{step}"
save_arm(model, processor, final, dict(step=step, **result))
(options.output_dir / "final").symlink_to(final.name, target_is_directory=True)
tool.write_json(options.output_dir / "result.json", result)
return result
# ----------------------------------------------------------------------------------------------- alignment
def align_example(processor, n, h, seen):
"""(prompt text, target text) of one alignment example: raster tokens in, the grid text out."""
from mmcrfm_utonia.data.collator import MULTISENSOR_SYSTEM_PROMPT
messages = [dict(role="system", content=[dict(type="text", text=MULTISENSOR_SYSTEM_PROMPT)]),
dict(role="user", content=[dict(type="text", text=f"{nr.VIEW_HEADER}\n{RASTER_TOKEN * nr.N_VIEW}\n"
f"{ALIGN_INSTRUCTION}")])]
prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
return prompt, nr.grid_text(n, h, seen)
def align_batch(processor, frames, rasters):
tok = processor.tokenizer
ids, labels, cells = [], [], []
for scene, frame in frames:
n, h, seen = nr.view(rasters(scene, frame))
prompt, target = align_example(processor, n, h, seen)
p = tok(prompt, add_special_tokens=False).input_ids
t = tok(target + tok.eos_token, add_special_tokens=False).input_ids if tok.eos_token else \
tok(target, add_special_tokens=False).input_ids
ids.append(p + t)
labels.append([-100] * len(p) + t)
cells.append(torch.from_numpy(nr.cell_features(n, h, seen)))
width = max(map(len, ids))
pad = tok.pad_token_id
input_ids = torch.tensor([x + [pad] * (width - len(x)) for x in ids])
attention = torch.tensor([[1] * len(x) + [0] * (width - len(x)) for x in ids])
label_t = torch.tensor([x + [-100] * (width - len(x)) for x in labels])
return dict(input_ids=input_ids, attention_mask=attention, labels=label_t), torch.stack(cells)
def align(options):
"""Raster alignment (spec §4): only the raster branch trains, the parent frozen and no camera, to reproduce the
frame's grid text from its raster tokens. Every frame of the training scenes; no question or answer label."""
import infer
from transformers import set_seed
tool.require_device("raster alignment")
started = time.monotonic()
set_seed(options.seed)
if ALIGNED.get(options.arm) == "detector":
return align_detector(options)
if ALIGNED.get(options.arm) != "raster":
raise ValueError(f"{options.arm} has no alignment stage")
model, processor, _, args, injector = load_arm(options, options.warm_checkpoint, options.arm, train=True)
model.requires_grad_(False)
branch = model.nonbox_raster_branch
branch.requires_grad_(True)
rasters = Rasters(options.raster_root)
scenes = sorted(split_scenes(args, "train"))
frames = [(s, f) for s in scenes for f in range(rasters.frames(s))]
random.Random(f"{SEED}:align:{options.seed}").shuffle(frames)
steps, batch_size = options.max_steps, (2 if options.smoke else ALIGN_BATCH)
options.chunk = options.chunk or 4
optimizer = torch.optim.AdamW(branch.parameters(), lr=RASTER_LR, weight_decay=0.0)
scheduler = torch.optim.lr_scheduler.LambdaLR(
optimizer, lambda s: min(1.0, (s + 1) / ALIGN_WARMUP) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / steps))))
options.output_dir.mkdir(parents=True, exist_ok=True)
# Memory (GPU smoke, 31 Oct): full-vocabulary logits of 16 sequences without checkpointing ran out of 96 GB.
# The reader is frozen, so: no dropout (deterministic), activation checkpointing, chunks of --chunk sequences, and
# the loss on completion logits only (sft_loss: per-sequence mean log-likelihood of the grid text).
from tools.multisensor_reward_training import on_device, sft_loss
for module in model.modules():
if isinstance(module, torch.nn.Dropout):
module.p = 0.0
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model.config.use_cache = False
model.train()
with (options.output_dir / "metrics.jsonl").open("x") as metrics:
for step in range(1, steps + 1):
start = ((step - 1) * batch_size) % len(frames)
batch_frames = (frames + frames)[start:start + batch_size]
batch, cells = align_batch(processor, batch_frames, rasters)
optimizer.zero_grad(set_to_none=True)
total = 0.0
for lo in range(0, batch_size, options.chunk):
part = {k: v[lo:lo + options.chunk] for k, v in batch.items()}
injector.stage(cells[lo:lo + options.chunk])
loss = sft_loss(model, on_device(part, model.device)) * (len(part["input_ids"]) / batch_size)
if not torch.isfinite(loss):
raise ValueError("nonfinite alignment loss")
loss.backward()
total += float(loss.detach())
grad = float(torch.nn.utils.clip_grad_norm_(branch.parameters(), 1.0, error_if_nonfinite=True))
optimizer.step()
scheduler.step()
log = dict(step=step, loss=total, grad_norm=grad, scale=float(branch.scale),
seconds=time.monotonic() - started)
if torch.cuda.is_available():
log["max_memory_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)
metrics.write(json.dumps(log) + "\n")
metrics.flush()
if step % 25 == 0 or step == 1:
print(json.dumps(log), flush=True)
torch.save(dict(state_dict={k: v.detach().cpu() for k, v in branch.state_dict().items()}),
options.output_dir / "ladder_raster_branch.pt")
recon = align_reconstruction(model, processor, injector, args, options,
**(dict(n_frames=2, max_new_tokens=40) if options.smoke else
dict(n_frames=options.recon_frames or 16)))
result = dict(arm=options.arm, seed=options.seed, parent=str(options.warm_checkpoint), steps=steps,
batch=batch_size, lr=RASTER_LR, warmup=ALIGN_WARMUP, frames=len(frames),
seconds=time.monotonic() - started, dev_reconstruction=recon, finished_at=now())
tool.write_json(options.output_dir / "result.json", result)
print(json.dumps(dict(event="aligned", **{k: v for k, v in result.items() if k != "dev_reconstruction"}),
indent=None), flush=True)
@torch.inference_mode()
def align_reconstruction(model, processor, injector, args, options, n_frames=16, max_new_tokens=900):
"""Descriptive: greedy grid text from the aligned raster tokens on dev frames, cell symbols compared."""
import infer
model.eval()
rasters = Rasters(options.raster_root)
scenes = sorted(split_scenes(args, "val"))
rng = random.Random(f"{SEED}:recon")
frames = [(s, rng.randrange(rasters.frames(s))) for s in rng.sample(scenes, min(n_frames, len(scenes)))]
tok = processor.tokenizer
right = total = parsed = 0
for scene, frame in frames:
n, h, seen = nr.view(rasters(scene, frame))
prompt, target = align_example(processor, n, h, seen)
ids = tok(prompt, add_special_tokens=False, return_tensors="pt").input_ids.to(model.device)
injector.stage(torch.from_numpy(nr.cell_features(n, h, seen))[None])
with infer.generation_autocast(model):
out = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids), max_new_tokens=max_new_tokens,
do_sample=False, use_cache=True, suppress_tokens=[tok.convert_tokens_to_ids(RASTER_TOKEN)],
pad_token_id=tok.pad_token_id, eos_token_id=tok.eos_token_id)
text = tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True)
want = [line.split(": ", 1)[1].split() for line in target.splitlines()[1:]]
got = {line.split(": ", 1)[0]: line.split(": ", 1)[1].split() for line in text.splitlines() if ": " in line}
for line, cells in zip(target.splitlines()[1:], want):
row = got.get(line.split(": ", 1)[0], [])
parsed += bool(row)
right += sum(a == b for a, b in zip(cells, row))
total += len(cells)
return dict(frames=len(frames), cell_accuracy=right / max(1, total), rows_parsed=parsed / max(1, len(frames) * nr.VIEW_ROWS))
def detector_align_example(source, scene, frame, rng):
"""(item, target lines, ids of the queried objects) of one detector-alignment example: every detected object of the
keyframe as tokens (labelled like the multi-object rungs), no camera; the target is T's text for up to
DETECTOR_ALIGN_OBJECTS of them, in the order the instruction names them. None for a keyframe without objects."""
from mmcrfm_utonia.data.geometry_qa.templates_v2 import stamp
raw = source.raw(scene)
features, _ = ladder.scene_rows(raw)
objects = source.objects(scene, frame)
if not objects:
return None
rows = features[[o["row"] for o in objects]]
ids = ladder.object_ids(scene, frame, len(objects), tool.SEED, salt="align")
seen = ladder.frame_objects(rows, torch.full((len(rows),), frame), frame, source.layout, tool.K)
pick = rng.sample(range(len(seen)), min(DETECTOR_ALIGN_OBJECTS, len(seen)))
chosen = [seen[i] for i in pick]
labels = [ids[o["row"]] for o in chosen]
question = (f"At {stamp(frame)}, write out the measured detector and radar fields of "
+ ", ".join(f"obj{i}" for i in labels) + ".")
target = ladder.measured_fields_text(chosen, labels)
return source._item(raw, frame, rows, question, target, ids), target, labels
def align_detector(options):
"""Text-anchored alignment of the detector tokens (arm J_A, spec §4): the object-token projector and the class and
radar branches train, the reader and its LoRA frozen and no camera, to make the reader reproduce T's text for
the objects the instruction names. Keyframes of the training scenes; no question or answer label. Saves a full
ladder checkpoint, which J_A's training continues."""
from transformers import set_seed
from tools.multisensor_reward_training import on_device, sft_loss
tool.require_device("detector alignment")
started = time.monotonic()
set_seed(options.seed)
model, processor, collator, args, _ = load_arm(options, options.warm_checkpoint, options.arm, train=True)
tool.enable_prefix_training(model, lora=False) # the projector trains; reader and LoRA frozen
params = [p for p in model.parameters() if p.requires_grad]
for name in ("class", "radar"):
branch = getattr(model, f"ladder_{name}_branch")
branch.requires_grad_(True)
params += list(branch.parameters())
source = RasterSource(args, "train", None, options.raster_root, radar=True, camera=False)
rng = random.Random(f"{SEED}:detector-align:{options.seed}")
frames = [(s, f) for s in sorted(split_scenes(args, "train")) for f in source.frames(s)]
rng.shuffle(frames)
steps, batch_size = options.max_steps, (2 if options.smoke else DETECTOR_ALIGN_BATCH)
options.chunk = options.chunk or 4
optimizer = torch.optim.AdamW(params, lr=RASTER_LR, weight_decay=0.0)
scheduler = torch.optim.lr_scheduler.LambdaLR(
optimizer, lambda s: min(1.0, (s + 1) / ALIGN_WARMUP) * 0.5 * (1 + math.cos(math.pi * min(1.0, s / steps))))
options.output_dir.mkdir(parents=True, exist_ok=True)
model.train()
cursor = 0
with (options.output_dir / "metrics.jsonl").open("x") as metrics:
for step in range(1, steps + 1):
items = []
while len(items) < batch_size:
example = detector_align_example(source, *frames[cursor % len(frames)], rng)
cursor += 1
if example is not None:
items.append(example[0])
optimizer.zero_grad(set_to_none=True)
total = 0.0
for start in range(0, len(items), options.chunk):
part = items[start:start + options.chunk]
loss = sft_loss(model, on_device(collator(part), model.device)) * (len(part) / len(items))
if not torch.isfinite(loss):
raise ValueError("nonfinite alignment loss")
loss.backward()
total += float(loss.detach())
grad = float(torch.nn.utils.clip_grad_norm_(params, 1.0, error_if_nonfinite=True))
optimizer.step()
scheduler.step()
log = dict(step=step, loss=total, grad_norm=grad, seconds=time.monotonic() - started)
if torch.cuda.is_available():
log["max_memory_gb"] = round(torch.cuda.max_memory_allocated() / 1e9, 2)
metrics.write(json.dumps(log) + "\n")
metrics.flush()
if step % 25 == 0 or step == 1:
print(json.dumps(log), flush=True)
state = dict(arm=options.arm, seed=options.seed, warm_checkpoint=str(options.warm_checkpoint),
radar_channels=model.ladder_radar, radar_zeroed=model.ladder_radar_zeroed, spec=dict(model.ladder_spec),
alignment="text-anchored detector tokens", steps=steps, batch=batch_size, lr=RASTER_LR,
warmup=ALIGN_WARMUP, objects_per_target=DETECTOR_ALIGN_OBJECTS)
tool.save(model, processor, options.output_dir / "checkpoint", state)
recon = detector_reconstruction(model, processor, collator, args, options,
n_frames=2 if options.smoke else (options.recon_frames or 64))
result = dict(state, frames=len(frames), seconds=time.monotonic() - started, dev_reconstruction=recon,
finished_at=now())
tool.write_json(options.output_dir / "result.json", result)
print(json.dumps(dict(event="aligned", arm=options.arm, dev_reconstruction=recon)), flush=True)
_FIELD = {"range": r"box centre ([0-9]+(?:\.[0-9]+)?) m,", "velocity": r"velocity ([+-]?[0-9]+(?:\.[0-9]+)?) m/s"}
def parse_fields(text):
"""{object id: {field: value}} from lines of T's text."""
import re
out = {}
for line in text.splitlines():
m = re.match(r"\s*obj(\d+):", line)
if not m:
continue
values = {}
for field, pattern in _FIELD.items():
hit = re.search(pattern, line)
if hit:
values[field] = float(hit.group(1))
cls = re.search(r"detected class ([a-z ]+?),", line)
if cls:
values["class"] = cls.group(1)
out[int(m.group(1))] = values
return out
@torch.inference_mode()
def detector_reconstruction(model, processor, collator, args, options, n_frames=64):
"""Descriptive: on development keyframes, the share of named objects whose class, range (within 2 m) and radar
velocity (within 1 m/s) the aligned reader writes out correctly from the tokens alone."""
model.eval()
source = RasterSource(args, "val", None, options.raster_root, radar=True, camera=False)
rng = random.Random(f"{SEED}:detector-recon")
scenes = sorted(split_scenes(args, "val"))
built = []
for scene in rng.sample(scenes, min(n_frames, len(scenes))):
example = detector_align_example(source, scene, rng.choice(source.frames(scene)), rng)
if example is not None:
built.append(example)
texts = answers(model, processor, collator, [b[0] for b in built], 4, max_new_tokens=600)
hits = Counter()
for (_, target, labels), text in zip(built, texts):
want, got = parse_fields(target), parse_fields(text)
for i in labels:
w, g = want.get(i, {}), got.get(i, {})
hits["objects"] += 1
hits["class"] += w.get("class") is not None and w.get("class") == g.get("class")
hits["range"] += "range" in w and "range" in g and abs(w["range"] - g["range"]) <= 2.0
if "velocity" in w:
hits["velocity_n"] += 1
hits["velocity"] += "velocity" in g and abs(w["velocity"] - g["velocity"]) <= 1.0
n = max(1, hits["objects"])
return dict(frames=len(built), objects=hits["objects"], class_=hits["class"] / n, range_2m=hits["range"] / n,
velocity_1mps=hits["velocity"] / max(1, hits["velocity_n"]))
# ----------------------------------------------------------------------------------------------- evaluation
def donor_for(record, scenes, rasters):
rng = random.Random(f"{SEED}:donor:{record['id']}")
scene = rng.choice(sorted(s for s in scenes if s != record["scene_token"]))
return scene, rng.randrange(rasters.frames(scene))
def eval_population(options, args, split, population):
"""[(condition, record, kind)] of an evaluation: free-space v2 records of the split under each condition, the
detector-miss variant (v1 regions occupied where a detected box overlaps: those boxes are dropped)."""
scenes = split_scenes(args, SPLIT_OF[split])
records = fs_records(options.fs_root, split, scenes)
if population == "primary":
records = [r for r in records if r["family"] == "prose_free"]
if options.limit:
records = records[:options.limit]
return records, scenes
@torch.inference_mode()
def answers(model, processor, collator, items, batch_size, max_new_tokens=MAX_NEW_TOKENS):
import infer
tok = processor.tokenizer
raster_id = tok.convert_tokens_to_ids(RASTER_TOKEN)
out = []
for start in range(0, len(items), batch_size):
batch, _ = collator.encode_prompts(items[start:start + batch_size])
batch = {k: v.to(model.device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}
with infer.generation_autocast(model):
generated = model.generate(**batch, max_new_tokens=max_new_tokens, do_sample=False, use_cache=True,
suppress_tokens=[raster_id], pad_token_id=tok.pad_token_id,
eos_token_id=tok.eos_token_id)
out += [t.strip() for t in tok.batch_decode(generated[:, batch["input_ids"].shape[1]:],
skip_special_tokens=True)]
return out
def evaluate(options):
tool.require_device("E2 evaluation")
model, processor, collator, args, _ = load_arm(options, options.checkpoint, options.arm, train=False)
model.eval()
# Raw RADAR is on here (radar_to_llm), bucketed per frame to the LiDAR cap: 20 GiB buffers at batch 16, where
# arm T's evaluations ran out of memory (vast.ai, 31 Oct). The guarded prefix is bit-identical (guard_radar_prefix).
print(f"RADAR prefix guard on {guard_radar_prefix(model)} projector(s)", flush=True)
source = source_for(options, model, args, options.arm, SPLIT_OF[options.split])
records, scenes = eval_population(options, args, options.split, options.population)
val_scenes = {r["scene_token"] for r in json.loads((Path(options.fs_root) / FS_FILES["val"]).read_text())}
if scenes & split_scenes(args, "train") or (options.split == "val") != bool(scenes & val_scenes) \
or (options.split == "val" and not val_scenes <= scenes):
raise ValueError(f"--split {options.split}: the config's val role does not hold that split's scenes "
"(nuScenes-val needs the config from tools/prepare_nonbox_val_inputs.py)")
conditions = options.conditions or (CURVE_CONDITIONS if options.population == "primary" else CONDITIONS)
raster_arm = ARMS[options.arm][1] is not None
options.output_dir.mkdir(parents=True, exist_ok=True)
summary = dict(arm=options.arm, checkpoint=str(options.checkpoint), split=options.split,
population=options.population, started_at=now(), conditions={})
for condition in conditions:
if condition == "retention:clean":
if options.split == "dev":
summary["conditions"][condition] = retention(options, model, processor, collator, source)
continue
donor = condition.startswith("donor:")
miss = condition.startswith("miss:")
if donor and not raster_arm:
continue
camera = condition.split(":")[-1]
pool = records
if miss:
v1 = fs_records(options.fs_root, f"miss_{options.split}", scenes)
pool = [r for r in v1 if r["family"] == "prose_free" and r["value"] == "occupied"]
if options.limit:
pool = pool[:options.limit]
t0 = time.monotonic()
built, skipped = [], Counter()
for r in pool:
d = None if camera == "clean" else (camera, int(sha256_text(f"{SEED}:{r['id']}:{camera}")[:8], 16))
raster_from = donor_for(r, scenes, source.rasters) if donor else None
item, dropped = source.fs_item(r, degradation=d, raster_from=raster_from, drop_region_boxes=miss)
if miss and dropped == 0:
skipped["no_detected_box_in_region"] += 1
continue
if item is None:
skipped["no_object_rows"] += 1
continue
built.append((r, item, raster_from, dropped))
texts = answers(model, processor, collator, [b[1] for b in built], options.batch_size)
rows = []
for (r, _, raster_from, dropped), text in zip(built, texts):
ok = fs_score.correct(r["family"], r["answer"], text)
rows.append(dict(id=r["id"], scene=r["scene_token"], family=r["family"], stratum=r["stratum"],
region=r["region"], value=r["value"], condition=condition, prediction=text,
correct=ok, raster_from=raster_from, dropped_boxes=dropped))
path = options.output_dir / f"{condition.replace(':', '__')}.jsonl"
path.write_text("".join(json.dumps(x) + "\n" for x in rows))
free = [x for x in rows if x["family"] == "prose_free" and x["correct"] is not None]
by = {v: [x["correct"] for x in free if x["value"] == v] for v in ("occupied", "free")}
summary["conditions"][condition] = dict(
n=len(rows), skipped=dict(skipped), seconds=round(time.monotonic() - t0, 1),
prose_free_balanced=(float(np.mean([np.mean(v) for v in by.values() if v])) if free else None),
recall={v: (float(np.mean(x)) if x else None) for v, x in by.items()})
print(json.dumps(dict(condition=condition, **summary["conditions"][condition])), flush=True)
summary["finished_at"] = now()
tool.write_json(options.output_dir / "summary.json", summary)
def retention(options, model, processor, collator, source):
"""The seven joint development sets, clean, the first RETENTION_LIMIT records each (with this arm's raster
block); correctness as in the joint analysis (tools.multisensor_ladder_reward.answer_right)."""
from tools.multisensor_ladder_reward import answer_right
sets, _ = tool.load_sets(options.run_root)
source.motion_labels = sets["motion_labels"]
limit = options.limit or RETENTION_LIMIT
rows, per_set = [], {}
for name in RETENTION_SETS:
built = []
for record in sets[name][:limit]:
meta = {}
if record["rung"] in tool.MOTION_RUNGS:
item, expected, meta = source.motion_item(record)
else:
item, expected = source.item(record)
if item is not None:
built.append((record, item, expected, meta))
texts = answers(model, processor, collator, [b[1] for b in built], options.batch_size)
part = [dict(set=name, id=r["id"], scene=r["scene_token"], family=r["family"],
attribute=r.get("attribute", "range"), supported=m.get("answerable"), expected=e, prediction=t,
correct=bool(answer_right(t, e, r.get("attribute", "range"))))
for (r, _, e, m), t in zip(built, texts)]
per_set[name] = dict(n=len(part), accuracy=float(np.mean([x["correct"] for x in part])) if part else None)
rows += part
(options.output_dir / "retention__clean.jsonl").write_text("".join(json.dumps(x) + "\n" for x in rows))
macro = [v["accuracy"] for v in per_set.values() if v["accuracy"] is not None]
out = dict(per_set=per_set, macro=float(np.mean(macro)) if macro else None)
print(json.dumps(dict(condition="retention:clean", **out)), flush=True)
return out
# ------------------------------------------------------------------------------------------------------- cli
def parse_args(argv=None):
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("phase", choices=("stream", "align", "train", "evaluate"))
p.add_argument("--config", type=Path, required=True)
p.add_argument("--run-root", type=Path, required=True, help="the joint experiment's runs/ (ladder_data, plan)")
p.add_argument("--fs-root", type=Path, required=True, help="B4DL dataset dir holding train/ and test/")
p.add_argument("--raster-root", type=Path, required=True)
p.add_argument("--lidar-image-root", type=Path, help="arm LI1's pre-rendered range images")
p.add_argument("--stream", type=Path)
p.add_argument("--stream-sha256")
p.add_argument("--arm", choices=sorted(ARMS))
p.add_argument("--seed", type=int, default=SEED)
p.add_argument("--warm-checkpoint", type=Path, help="the parent (align, train)")
p.add_argument("--raster-branch", type=Path, help="aligned ladder_raster_branch.pt (train, R arms)")
p.add_argument("--checkpoint", type=Path, help="evaluate")
p.add_argument("--split", choices=("dev", "val"), default="dev")
p.add_argument("--population", choices=("primary", "full"), default="full")
p.add_argument("--conditions", nargs="*")
p.add_argument("--limit", type=int, default=None, help="smoke: records per condition")
p.add_argument("--max-steps", type=int)
p.add_argument("--chunk", type=int, default=None,
help="examples per forward pass (the objective is unchanged): default 2 for train (the text arm "
"reached 97 GB at 4 on a 96 GB card), 4 for align")
p.add_argument("--recon-frames", type=int, default=None,
help="align: development frames of the descriptive reconstruction (default 16 raster / 64 detector)")
p.add_argument("--batch-size", type=int, default=16)
p.add_argument("--smoke", action="store_true",
help="plumbing only: batch 2, R may train without an aligned branch, 2 reconstruction frames")
p.add_argument("--output-dir", type=Path)
o = p.parse_args(argv)
if o.max_steps is None:
o.max_steps = ALIGN_STEPS if o.phase == "align" else STEPS
return o
def main(argv=None):
options = parse_args(argv)
dict(stream=stream_phase, align=align, train=train, evaluate=evaluate)[options.phase](options)
if __name__ == "__main__":
main()