Jeveration-GGUF / scripts /nyu_eval.py
Meshwa's picture
Model card, CPU inference code (llama.cpp helper + Python), set-up scripts, examples
6a8ca2a verified
Raw History Blame Contribute Delete
6.11 kB
"""Evaluate the GGUF backbone's dense predictions on the NYUv2 test split (tanganke/nyuv2 'val' = the standard 654 images,
288 x 384, depth in meters, 13 classes in jeveration.config.NYU13 order, -1 = ignore).
python scripts/nyu_eval.py --n 20 # 20 images evenly spread over the downloaded shard(s)
python scripts/nyu_eval.py --n 20 --tasks depth # depth only (~50 s / image on a 4-thread CPU)
Writes per-image rows to <out>/results.jsonl (resumable: images already there are skipped) and prints the running mean.
"""
import argparse
import glob
import json
import time
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import torch
import torch.nn.functional as F
from dense_gguf import DenseSide, dense_hidden, depth_metrics, load_vision_tower
from jev_gguf import WORK, Backbone, default_gguf
from jeveration import config
from jeveration.dense import resize_for_vision, to_predictions
from jeveration.prompts import SourcePromptTokenizer, vision_tokens
def seg_confusion(pred, gt, k=13):
m = gt >= 0
return np.bincount(k * gt[m].astype(int) + pred[m].astype(int), minlength=k * k).reshape(k, k)
def normal_metrics(pred, gt):
m = np.linalg.norm(gt, axis=-1) > 0.5
cos = np.clip((pred[m] * gt[m]).sum(-1), -1, 1)
ang = np.degrees(np.arccos(cos))
return {"mean_deg": float(ang.mean()), "median_deg": float(np.median(ang)), "within_11.25": float((ang < 11.25).mean()),
"within_22.5": float((ang < 22.5).mean()), "within_30": float((ang < 30).mean())}
def rows(files, n):
"""n samples evenly spread over the parquet files -> (global index, image uint8 [H, W, 3], depth, seg, normal)"""
tables = [pq.read_table(f) for f in files]
total = sum(t.num_rows for t in tables)
want = sorted(set(np.linspace(0, total - 1, min(n, total)).round().astype(int)))
offs = np.cumsum([0] + [t.num_rows for t in tables])
for g in want:
ti = int(np.searchsorted(offs, g, side="right") - 1)
r = tables[ti].slice(g - offs[ti], 1).to_pylist()[0]
img = (np.array(r["image"], np.float32).transpose(1, 2, 0) * 255).round().clip(0, 255).astype(np.uint8)
yield (g, img, np.array(r["depth"], np.float32)[0], np.array(r["segmentation"], np.int64),
np.array(r["normal"], np.float32).transpose(1, 2, 0))
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--data", default=str(WORK / "nyuv2" / "val-*.parquet"))
ap.add_argument("--n", type=int, default=20)
ap.add_argument("--tasks", default="depth,seg,normal")
ap.add_argument("--gguf", default=default_gguf("Q4_K_M"))
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--out", default=str(WORK / "nyu_eval"))
a = ap.parse_args()
tasks = [t for t in a.tasks.split(",") if t]
torch.set_num_threads(a.threads)
out = Path(a.out) / Path(a.gguf).stem
out.mkdir(parents=True, exist_ok=True)
res_path = out / "results.jsonl"
done = {json.loads(l)["index"]: json.loads(l) for l in open(res_path)} if res_path.exists() else {}
backbone = Backbone(a.gguf, a.threads, n_ubatch=512)
side = DenseSide(backbone.n_embd).eval()
side.load(WORK / "jeveration-weights" / "jeveration.pt")
visual = load_vision_tower(WORK / "qwen3.5-4b")
from transformers import AutoTokenizer
sptok = SourcePromptTokenizer(AutoTokenizer.from_pretrained(str(WORK / "qwen3.5-4b")))
results, conf = list(done.values()), np.zeros((13, 13), np.int64)
for r in results:
if "seg_conf" in r:
conf += np.array(r["seg_conf"])
for g, img, d_gt, s_gt, n_gt in rows(sorted(glob.glob(a.data)), a.n):
if g in done:
continue
t0 = time.time()
with torch.no_grad():
vis, _ = vision_tokens(visual, resize_for_vision(torch.from_numpy(img.copy())[None]))
row = {"index": int(g)}
for t in tasks:
hq = dense_hidden(backbone, side, sptok, vis.float(), t)
raw = F.interpolate(side.readout(t, hq).float(), size=img.shape[:2], mode="bilinear", align_corners=False)
p = to_predictions(t, raw)[0].numpy()
if t == "depth":
row["depth"] = depth_metrics(p, d_gt, crop=False)
elif t == "seg":
c = seg_confusion(p, s_gt)
row["seg_conf"] = c.tolist()
row["seg_pixacc"] = float(np.trace(c) / max(c.sum(), 1))
conf += c
else:
row["normal"] = normal_metrics(p, n_gt)
row["sec"] = round(time.time() - t0, 1)
results.append(row)
with open(res_path, "a") as f:
f.write(json.dumps(row) + "\n")
msg = [f"[{len(results)}/{a.n}] #{g} {row['sec']}s"]
if "depth" in row:
msg.append("depth " + " ".join(f"{k} {np.mean([r['depth'][k] for r in results if 'depth' in r]):.3f}"
for k in ("AbsRel", "RMSE", "d1")))
if "seg_conf" in row:
iou = np.diag(conf) / np.maximum(conf.sum(0) + conf.sum(1) - np.diag(conf), 1)
present = conf.sum(1) > 0
msg.append(f"seg mIoU {iou[present].mean():.3f} pixacc {np.trace(conf) / conf.sum():.3f}")
if "normal" in row:
msg.append("normal " + " ".join(f"{k} {np.mean([r['normal'][k] for r in results if 'normal' in r]):.3f}"
for k in ("mean_deg", "within_11.25", "within_30")))
print(" | ".join(msg), flush=True)
if conf.sum():
iou = np.diag(conf) / np.maximum(conf.sum(0) + conf.sum(1) - np.diag(conf), 1)
print("per-class IoU: " + ", ".join(f"{c} {v:.2f}" for c, v, ok in zip(config.NYU13, iou, conf.sum(1) > 0) if ok))
if any("depth" in r for r in results):
print("FINAL depth (mean over images): " + " ".join(
f"{k} {np.mean([r['depth'][k] for r in results if 'depth' in r]):.3f}" for k in results[0]["depth"]))
if __name__ == "__main__":
main()