"""Grounding DINO audit of rendered scenes (stage 3, MMDetection 3.x environment). Runs the detector on every rendered scene and compares its detections with the intended classes. In lean mode (the default) a scene is flagged when the detector finds an unrequested class or a duplicate of an intended class above the score threshold (raised to 0.50); missing classes are not flagged. Writes clean and dirty manifests per shard. usage: python strangebench/audit/audit_diffusion_scenes.py --scene-specs --raw-root --config --checkpoint --out-dir /_audit [--num-shards N --shard-id I] """ from __future__ import annotations import argparse import json from collections import Counter, defaultdict from pathlib import Path from typing import Dict, List, Optional, Set, Tuple import torch IMG_EXTENSIONS = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} TEXT_CONDITIONED_TYPES = {"GroundingDINO", "GLIP"} def is_text_conditioned(model) -> bool: cfg = getattr(model, "cfg", None) if cfg is None: return False return cfg.get("model", {}).get("type", "") in TEXT_CONDITIONED_TYPES def build_text_prompt(class_names: List[str]) -> str: return " . ".join(class_names) + " ." def detections_above_threshold( pred_instances, score_thr: float, class_names: List[str] ) -> List[Dict]: scores = pred_instances.scores.cpu().numpy() labels = pred_instances.labels.cpu().numpy() bboxes = pred_instances.bboxes.cpu().numpy() keep = scores >= score_thr out = [] for s, l, b in zip(scores[keep], labels[keep], bboxes[keep]): out.append({ "class": class_names[int(l)], "label": int(l), "score": float(s), "bbox": [float(x) for x in b], }) return out def classify_scene( intended_counts: Counter, detected_counts: Counter, ignore: Set[str], ) -> Tuple[str, Set[str], Set[str], Dict[str, int]]: """Return (image_status, missing, extras, duplicates). - missing : intended classes that the detector did not find - extras : detected classes outside intended set, excluding ignore - duplicates: intended class -> excess count (detected - intended) for classes where detector found MORE instances than the LLM placed. E.g. {'zebra': 5} means LLM said 1 zebra, detector found 6. image_status in {clean, missing_intended, extras_present, duplicate_intended_class, both}. """ intended_set = set(intended_counts) detected_set = set(detected_counts) missing = intended_set - detected_set extras = (detected_set - intended_set) - ignore duplicates: Dict[str, int] = {} for c, n_intended in intended_counts.items(): n_detected = detected_counts.get(c, 0) if n_detected > n_intended: duplicates[c] = n_detected - n_intended flags = [] if missing: flags.append("missing_intended") if extras: flags.append("extras_present") if duplicates: flags.append("duplicate_intended_class") if not flags: status = "clean" elif len(flags) == 1: status = flags[0] else: status = "both" return status, missing, extras, duplicates def _bbox_iou_xyxy(a: List[float], b: List[float]) -> float: ax1, ay1, ax2, ay2 = a bx1, by1, bx2, by2 = b ix1, iy1 = max(ax1, bx1), max(ay1, by1) ix2, iy2 = min(ax2, bx2), min(ay2, by2) iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1) inter = iw * ih if inter <= 0: return 0.0 aw, ah = max(0.0, ax2 - ax1), max(0.0, ay2 - ay1) bw, bh = max(0.0, bx2 - bx1), max(0.0, by2 - by1) union = aw * ah + bw * bh - inter return inter / union if union > 0 else 0.0 def _xywh_to_xyxy(b: List[float]) -> List[float]: return [b[0], b[1], b[0] + b[2], b[1] + b[3]] def verify_annotations( anns_for_image: List[Dict], detections: List[Dict], coco_id_to_name: Dict[int, str], iou_thr: float, ) -> List[Dict]: """For each ann, find best-IoU detector prediction and flag mismatches. Returns a list of per-ann verdicts with keys: ann_id, ann_class, ann_bbox_xyxy, best_iou, best_det_class, ok, fail_reason """ verdicts: List[Dict] = [] for ann in anns_for_image: ann_class = coco_id_to_name.get(int(ann["category_id"]), "?") ann_xyxy = _xywh_to_xyxy([float(x) for x in ann["bbox"]]) best_iou, best_det_class, best_det_score = 0.0, None, 0.0 for d in detections: iou = _bbox_iou_xyxy(ann_xyxy, d["bbox"]) if iou > best_iou: best_iou, best_det_class, best_det_score = ( iou, d["class"], d["score"]) if best_iou < iou_thr: ok, fail = False, "low_iou" elif best_det_class != ann_class: ok, fail = False, "class_mismatch" else: ok, fail = True, None verdicts.append({ "ann_id": int(ann["id"]), "ann_class": ann_class, "ann_bbox_xyxy": ann_xyxy, "best_iou": float(best_iou), "best_det_class": best_det_class, "best_det_score": float(best_det_score), "ok": ok, "fail_reason": fail, }) return verdicts def verify_layout_fidelity( anns_for_image: List[Dict], scene: Dict, coco_id_to_name: Dict[int, str], iou_thr: float, ) -> List[Dict]: """For each ann, compare its bbox to the LLM layout bbox for the same class. Returns per-ann verdicts with keys: ann_id, ann_class, layout_iou, layout_ok, layout_fail_reason Match is by class name. For the diffusion_tnever pipeline, every scene has unique class labels (partner-selection excludes anchor), so the lookup is unambiguous. """ label_to_box = {lbl: bb for lbl, bb in zip(scene["labels"], scene["layout_boxes"])} verdicts: List[Dict] = [] for ann in anns_for_image: ann_class = coco_id_to_name.get(int(ann["category_id"]), "?") ann_xyxy = _xywh_to_xyxy([float(x) for x in ann["bbox"]]) layout_box = label_to_box.get(ann_class) if layout_box is None: verdicts.append({ "ann_id": int(ann["id"]), "ann_class": ann_class, "layout_iou": None, "layout_ok": False, "layout_fail_reason": "no_layout_box_for_class", }) continue iou = _bbox_iou_xyxy(ann_xyxy, [float(x) for x in layout_box]) ok = iou >= iou_thr verdicts.append({ "ann_id": int(ann["id"]), "ann_class": ann_class, "layout_iou": float(iou), "layout_ok": ok, "layout_fail_reason": None if ok else "low_layout_iou", }) return verdicts def _ann_iou(a: Dict, b: Dict) -> float: """IoU of two COCO annotations: mask IoU when both carry an RLE ``segmentation`` and pycocotools is importable, else bbox IoU.""" sa, sb = a.get("segmentation"), b.get("segmentation") if isinstance(sa, dict) and isinstance(sb, dict): try: from pycocotools import mask as mask_utils return float(mask_utils.iou([sa], [sb], [0])[0][0]) except Exception: pass return _bbox_iou_xyxy(_xywh_to_xyxy([float(x) for x in a["bbox"]]), _xywh_to_xyxy([float(x) for x in b["bbox"]])) def dedup_cross_class( anns_for_image: List[Dict], intended: Set[str], coco_id_to_name: Dict[int, str], iou_thr: float, iou_fn=None, ) -> Tuple[List[Dict], bool]: """Duplicate-label rule (D). Returns (dropped, dup_label_intended). ``dropped`` has one entry per removed annotation: ann_id, ann_class, kept_ann_id, kept_class, iou, dropped_intended ``dup_label_intended`` is True when any dropped annotation's class is in ``intended`` (the scene is then flagged ``dup_label``). Pairs are visited by descending IoU; an annotation dropped once is not matched again. ``iou_fn(a, b)`` defaults to ``_ann_iou`` (mask IoU when possible). """ iou_fn = iou_fn or _ann_iou if iou_thr <= 0 or len(anns_for_image) < 2: return [], False name_of = {int(a["id"]): coco_id_to_name.get(int(a["category_id"]), "?") for a in anns_for_image} pairs = [] for i in range(len(anns_for_image)): for j in range(i + 1, len(anns_for_image)): a, b = anns_for_image[i], anns_for_image[j] if name_of[int(a["id"])] == name_of[int(b["id"])]: continue iou = float(iou_fn(a, b)) if iou > iou_thr: pairs.append((iou, a, b)) pairs.sort(key=lambda t: -t[0]) dropped_ids: Set[int] = set() dropped: List[Dict] = [] for iou, a, b in pairs: ia, ib = int(a["id"]), int(b["id"]) if ia in dropped_ids or ib in dropped_ids: continue ca, cb = name_of[ia], name_of[ib] a_int, b_int = ca in intended, cb in intended if a_int and not b_int: keep, drop = a, b elif b_int and not a_int: keep, drop = b, a else: keep, drop = (a, b) if float(a.get("score", 0.0)) >= float(b.get("score", 0.0)) else (b, a) dropped_ids.add(int(drop["id"])) dropped.append({ "ann_id": int(drop["id"]), "ann_class": name_of[int(drop["id"])], "kept_ann_id": int(keep["id"]), "kept_class": name_of[int(keep["id"])], "iou": round(iou, 4), "dropped_intended": name_of[int(drop["id"])] in intended, }) return dropped, any(d["dropped_intended"] for d in dropped) def load_annotations_index( annotations_root: Path, coco_id_to_name: Dict[int, str], ) -> Tuple[Dict[Tuple[str, str], List[Dict]], Dict[int, str]]: """Index Stage-3 anns by (sub_tier, scene_id) -> list of ann dicts. Returns (index, ann_id_to_subtier). The ann_id_to_subtier map lets the filter script know which sub-tier each flagged ann belongs to. """ index: Dict[Tuple[str, str], List[Dict]] = {} ann_to_sub: Dict[int, str] = {} for sub_dir in sorted(annotations_root.iterdir()): ann_path = sub_dir / "annotations.json" if not ann_path.exists(): continue with open(ann_path) as f: coco = json.load(f) id_to_fn = {img["id"]: img["file_name"] for img in coco.get("images", [])} for ann in coco.get("annotations", []): fn = id_to_fn.get(ann["image_id"]) if fn is None: continue scene_id = fn.rsplit(".", 1)[0] key = (sub_dir.name, scene_id) index.setdefault(key, []).append(ann) ann_to_sub[int(ann["id"])] = sub_dir.name return index, ann_to_sub LEAN_SCORE_THR = 0.50 def apply_mode_defaults(args: argparse.Namespace) -> None: """Resolve the mode-dependent defaults in place (shared by the CLI and the tests).""" if args.audit_mode == "lean": args.also_flag_missing = False if not args.check_layout_fidelity and not args.no_layout_fidelity: args.check_layout_fidelity = True print("[lean mode] auto-enabling --check-layout-fidelity") if args.score_thr < 0.45: print(f"[lean mode] bumping --score-thr {args.score_thr} -> {LEAN_SCORE_THR} " "(higher precision for extras/dups; reduces false drops)") args.score_thr = LEAN_SCORE_THR if args.no_layout_fidelity: args.check_layout_fidelity = False print("[--no-layout-fidelity] layout-fidelity check disabled") def main() -> None: ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--scene-specs", required=True, type=Path, help="Stage 1 scene_specs.json (intended labels per scene)") ap.add_argument("--raw-root", required=True, type=Path, help="Dir containing /raw/.png " "(typically the same as Stage 2/3 OUT_ROOT).") ap.add_argument("--config", required=True, help="MMDet config for the audit detector.") ap.add_argument("--checkpoint", required=True, help="Detector checkpoint path.") ap.add_argument("--out-dir", required=True, type=Path, help="Where to write clean/dirty manifests.") ap.add_argument("--score-thr", type=float, default=0.30, help="Detection score threshold for counting a class " "as 'present'. Lower = stricter audit.") ap.add_argument("--max-dets-per-img", type=int, default=300) ap.add_argument("--ignore-classes", type=str, nargs="*", default=[], help="Class names to IGNORE as extras (still reported in " "the dirty manifest but do NOT flag the scene). " "Example: --ignore-classes 'dining table' chair") ap.add_argument("--also-flag-missing", action="store_true", help="By default, missing intended classes only land the " "scene in the 'missing_intended' bucket. Set this " "to ALSO put missing_intended scenes into the dirty " "manifest (treats them as eval-unfit).") ap.add_argument("--annotations-root", type=Path, default=None, help="Path to containing /annotations.json " "from Stage 3 + merger. When given, also runs per-" "annotation correctness check (flag SAM3 bboxes that " "don't match the detector's prediction in the same " "region/class). Same path as --raw-root in the " "common case.") ap.add_argument("--ann-iou-thr", type=float, default=0.5, help="IoU threshold for matching a SAM3 ann to a detector " "prediction. Below this -> ann flagged as low_iou.") ap.add_argument("--check-layout-fidelity", action="store_true", help='Also compare the annotation boxes with the planned layout boxes of scene_specs.json (per class; needs --annotations-root).') ap.add_argument("--layout-iou-thr", type=float, default=0.3, help='IoU threshold between an annotation box and its planned layout box.') ap.add_argument("--no-layout-fidelity", action="store_true", help='Turn the layout-fidelity check off, also in lean mode.') ap.add_argument("--dedup-iou", type=float, default=0.0, help='Duplicate-label rule: IoU above which two annotations of different classes in one scene are the same object (0 = off; needs --annotations-root).') ap.add_argument("--audit-mode", choices=["lean", "strict"], default="lean", help='lean (default): the detector flags only unrequested classes and duplicates, at the raised score threshold. strict: also missing intended classes and per-annotation box checks.') ap.add_argument("--num-shards", type=int, default=1) ap.add_argument("--shard-id", type=int, default=0) ap.add_argument("--device", type=str, default="cuda:0") args = ap.parse_args() if args.dedup_iou > 0 and args.annotations_root is None: ap.error("--dedup-iou needs --annotations-root (the rule works on the merged annotations)") apply_mode_defaults(args) args.out_dir.mkdir(parents=True, exist_ok=True) with open(args.scene_specs) as f: scenes = json.load(f) print(f"Loaded {len(scenes)} scenes from {args.scene_specs}") shard_scenes = scenes[args.shard_id :: args.num_shards] print(f"Shard {args.shard_id}/{args.num_shards}: {len(shard_scenes)} scenes") if not shard_scenes: print("Nothing to audit, exiting.") return print(f"Loading detector\n cfg: {args.config}\n ckpt: {args.checkpoint}") from mmdet.apis import inference_detector, init_detector model = init_detector(args.config, args.checkpoint, device=args.device) class_names = list(model.dataset_meta["classes"]) text_prompt = None if is_text_conditioned(model): text_prompt = build_text_prompt(class_names) print(f"Text-conditioned model -> {len(class_names)}-class prompt " f"({len(text_prompt)} chars)") ignore_set = set(args.ignore_classes) if ignore_set: print(f"Ignoring as extras: {sorted(ignore_set)}") ann_index: Dict[Tuple[str, str], List[Dict]] = {} coco_id_to_name: Dict[int, str] = {} if args.annotations_root is not None: any_ann = next(args.annotations_root.glob("*/annotations.json"), None) if any_ann is None: print(f"WARNING: --annotations-root={args.annotations_root} " f"has no /annotations.json; per-ann check disabled") else: with open(any_ann) as f: cats = json.load(f).get("categories", []) coco_id_to_name = {int(c["id"]): c["name"] for c in cats} ann_index, _ = load_annotations_index( args.annotations_root, coco_id_to_name) print(f"Per-ann check ENABLED: indexed " f"{sum(len(v) for v in ann_index.values())} anns " f"across {len(ann_index)} (sub_tier, scene_id) pairs") clean: List[Dict] = [] dirty: List[Dict] = [] bad_anns_global: List[Dict] = [] by_subtier_status: Dict[str, Counter] = defaultdict(Counter) extra_class_counter: Counter = Counter() duplicate_class_counter: Counter = Counter() ann_fail_counter: Counter = Counter() dedup_dropped_total = 0 dup_label_scenes = 0 n_missing_png = 0 for idx, scene in enumerate(shard_scenes): sub_tier = scene["sub_tier"] scene_id = scene["scene_id"] intended = set(scene["labels"]) png = args.raw_root / sub_tier / "raw" / f"{scene_id}.png" if not png.exists(): n_missing_png += 1 continue try: with torch.inference_mode(): if text_prompt is not None: result = inference_detector( model, str(png), text_prompt=text_prompt, custom_entities=True) else: result = inference_detector(model, str(png)) except Exception as e: print(f" [det error] {png.name}: {e}") continue dets = detections_above_threshold( result.pred_instances, args.score_thr, class_names) dets = sorted(dets, key=lambda d: -d["score"])[: args.max_dets_per_img] intended_counts = Counter(scene["labels"]) detected_counts = Counter(d["class"] for d in dets) status, missing, extras, duplicates = classify_scene( intended_counts, detected_counts, ignore_set) by_subtier_status[sub_tier][status] += 1 for c in extras: extra_class_counter[c] += 1 for c in duplicates: duplicate_class_counter[c] += 1 ann_verdicts: List[Dict] = [] n_bad_anns = 0 if ann_index: anns = ann_index.get((sub_tier, scene_id), []) if args.audit_mode == "strict": ann_verdicts = verify_annotations( anns, dets, coco_id_to_name, args.ann_iou_thr) else: ann_verdicts = [{ "ann_id": int(a["id"]), "ann_class": coco_id_to_name.get(int(a["category_id"]), "?"), "ann_bbox_xyxy": _xywh_to_xyxy(a["bbox"]), "best_iou": None, "best_det_class": None, "ok": True, "fail_reason": None, } for a in anns] if args.check_layout_fidelity: layout_verdicts = verify_layout_fidelity( anns, scene, coco_id_to_name, args.layout_iou_thr) lay_by_id = {v["ann_id"]: v for v in layout_verdicts} for v in ann_verdicts: lay = lay_by_id.get(v["ann_id"], {}) v["layout_iou"] = lay.get("layout_iou") v["layout_ok"] = lay.get("layout_ok", True) v["layout_fail_reason"] = lay.get("layout_fail_reason") if not v["layout_ok"]: v["ok"] = False if v.get("fail_reason") is None: v["fail_reason"] = v["layout_fail_reason"] n_bad_anns = sum(1 for v in ann_verdicts if not v["ok"]) for v in ann_verdicts: if not v["ok"]: ann_fail_counter[v["fail_reason"]] += 1 bad_anns_global.append({ "ann_id": v["ann_id"], "sub_tier": sub_tier, "scene_id": scene_id, **v, }) dedup_dropped: List[Dict] = [] dup_label_intended = False if ann_index and args.dedup_iou > 0: anns = ann_index.get((sub_tier, scene_id), []) dedup_dropped, dup_label_intended = dedup_cross_class( anns, intended, coco_id_to_name, args.dedup_iou) for d in dedup_dropped: ann_fail_counter["dup_label"] += 1 bad_anns_global.append({ "sub_tier": sub_tier, "scene_id": scene_id, "ok": False, "fail_reason": "dup_label", **d, }) dedup_dropped_total += len(dedup_dropped) dup_label_scenes += int(dup_label_intended) entry = { "scene_id": scene_id, "sub_tier": sub_tier, "status": status, "intended": sorted(intended_counts), "missing": sorted(missing), "extras": sorted(extras), "duplicates": duplicates, "n_bad_anns": n_bad_anns, "ann_verdicts": ann_verdicts, "dedup_dropped": dedup_dropped, "dup_label": dup_label_intended, "detections": dets, "file_name": str(png.relative_to(args.raw_root)), } is_dirty = ( status in ("extras_present", "duplicate_intended_class", "both") or n_bad_anns > 0 or (args.also_flag_missing and status == "missing_intended") or dup_label_intended ) if is_dirty: dirty.append(entry) else: clean.append(entry) if (idx + 1) % 50 == 0: print(f" [{idx+1}/{len(shard_scenes)}] " f"clean={len(clean)} dirty={len(dirty)} " f"bad_anns={sum(e['n_bad_anns'] for e in dirty + clean)} " f"missing_png={n_missing_png}") suffix = f"_shard{args.shard_id:03d}" if args.num_shards > 1 else "" audit_cfg = { "audit_mode": args.audit_mode, "config": args.config, "checkpoint": args.checkpoint, "score_thr": args.score_thr, "ann_iou_thr": args.ann_iou_thr, "layout_iou_thr": args.layout_iou_thr, "ignored_classes": sorted(ignore_set), "also_flag_missing": args.also_flag_missing, "scene_specs": str(args.scene_specs), "raw_root": str(args.raw_root), "annotations_root": (str(args.annotations_root) if args.annotations_root else None), "per_ann_check_enabled": bool(ann_index), "layout_fidelity_check_enabled": bool(args.check_layout_fidelity), "dedup_iou": args.dedup_iou, } with open(args.out_dir / f"clean_manifest{suffix}.json", "w") as f: json.dump({ "audit_config": audit_cfg, "scenes": clean, }, f, indent=2) with open(args.out_dir / f"dirty_manifest{suffix}.json", "w") as f: json.dump({ "audit_config": audit_cfg, "extra_class_counts": dict(extra_class_counter.most_common()), "duplicate_class_counts": dict(duplicate_class_counter.most_common()), "ann_fail_counts": dict(ann_fail_counter), "bad_anns": bad_anns_global, "scenes": dirty, }, f, indent=2) n = len(clean) + len(dirty) pct_dirty = 100.0 * len(dirty) / max(n, 1) n_bad_anns_total = len(bad_anns_global) print(f"\n=== Audit summary (shard {args.shard_id}/{args.num_shards}) ===") print(f" audited: {n} ({n_missing_png} missing PNGs skipped)") print(f" clean: {len(clean)} ({100-pct_dirty:.1f}%)") print(f" dirty: {len(dirty)} ({pct_dirty:.1f}%)") if ann_index: print(f" bad anns (ann-level): {n_bad_anns_total}") print(f" detector low_iou: {ann_fail_counter.get('low_iou', 0)}") print(f" detector class_mismatch: {ann_fail_counter.get('class_mismatch', 0)}") if args.check_layout_fidelity: print(f" layout low_layout_iou: {ann_fail_counter.get('low_layout_iou', 0)}") print(f" no_layout_box_for_class: {ann_fail_counter.get('no_layout_box_for_class', 0)}") if args.dedup_iou > 0: print(f" dup_label anns dropped: {dedup_dropped_total} " f"(scenes flagged dup_label: {dup_label_scenes})") print() print(f" per-sub-tier status (clean / missing / extras / dup_class / both):") for sub in sorted(by_subtier_status): c = by_subtier_status[sub] print(f" {sub:<22s} " f"clean={c['clean']:3d} miss={c['missing_intended']:3d} " f"extras={c['extras_present']:3d} " f"dup_class={c['duplicate_intended_class']:3d} " f"both={c['both']:3d}") if extra_class_counter: print(f"\n top extra-class leaks (across all sub-tiers):") for cls, ct in extra_class_counter.most_common(15): print(f" {cls:<25s} {ct}") if duplicate_class_counter: print(f"\n top duplicate-class hits (intended class with detected_count > 1):") for cls, ct in duplicate_class_counter.most_common(15): print(f" {cls:<25s} {ct}") print() print(f"Clean manifest: {args.out_dir / f'clean_manifest{suffix}.json'}") print(f"Dirty manifest: {args.out_dir / f'dirty_manifest{suffix}.json'}") if __name__ == "__main__": main()