Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Evaluation harness: promote --record writes verdicts into the research JSON; DINOv2 for style

Claude602317527359
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjs
index e9867fca..f805d50a 100644
--- a/scripts/eval/eval.mjs
+++ b/scripts/eval/eval.mjs
@@ -7,9 +7,10 @@ import fs from "node:fs";
import path from "node:path";
import { parseArgs } from "node:util";
import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
-import { compareRuns, compareText, promote, promoteText } from "./lib/compare.mjs";
+import { compareRuns, compareText, promote, promoteText, researchRecords } from "./lib/compare.mjs";
import { scoreRun } from "./lib/metrics.mjs";
import { METRICS_DIR, REPO_DIR, resultsDir } from "./lib/paths.mjs";
+import { RECIPES_FILE } from "./lib/recipes.mjs";
import { writeReport } from "./lib/report.mjs";
import { serveReview, writeReview } from "./lib/review.mjs";
import { DEFAULT_CLOUD_CAP, money, runEval } from "./lib/run.mjs";
@@ -27,7 +28,7 @@ const num = (v, name) => {
class Usage extends Error {}
const COMMON = { url: { type: "string" }, token: { type: "string" }, out: { type: "string" }, json: { type: "boolean" }, help: { type: "boolean", short: "h" } };
-const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "identity-model": { type: "string" }, "accept-noncommercial": { type: "boolean" }, force: { type: "boolean" } };
+const SCORE = { "no-metrics": { type: "boolean" }, metrics: { type: "string" }, device: { type: "string" }, "clip-model": { type: "string" }, "style-model": { type: "string" }, "identity-model": { type: "string" }, "accept-noncommercial": { type: "boolean" }, force: { type: "boolean" } };
const HELP = {
run: `pnpm eval:run --suite <name> --engine demo|open|cloud [options]
@@ -48,13 +49,13 @@ const HELP = {
--comfy-url <url> ComfyUI's address, for memory and its own timings (open engine; default COMFYUI_URL)
--label <text> a note for this run
--no-metrics don't score afterwards · --no-report: don't write the report either`,
- report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--force]",
+ report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--style-model clip|dinov2] [--force]",
review: "pnpm eval:review <runId|latest> [--against variants|references|<otherRunId>] [--port 4173] [--no-serve] [--limit n]",
compare: "pnpm eval:compare <runA[:variant]> <runB[:variant]> [--fail-on clip,aesthetic] [--threshold 1|5%] [--per-case]",
- promote: "pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain]",
+ promote: "pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain] [--record [--research file]] --record writes the verdicts into the research JSON",
history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
- setup: "pnpm eval:setup [--identity] [--download] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",
+ setup: "pnpm eval:setup [--identity] [--download [--dinov2]] [--torch-backend cpu|auto|cu128…] the metrics venv (needs uv)",
};
function usage() {
@@ -114,7 +115,7 @@ const root = (values, env) => resultsDir(env, values.out);
async function score(dir, v, ctx) {
if (v["no-metrics"]) return null;
ctx.note("Scoring the outputs…");
- const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], identityModel: v["identity-model"], acceptNoncommercial: v["accept-noncommercial"], force: v.force, log: ctx.note, env: ctx.env });
+ const r = await scoreRun(dir, { metrics: v.metrics, device: v.device, clipModel: v["clip-model"], styleModel: v["style-model"], identityModel: v["identity-model"], acceptNoncommercial: v["accept-noncommercial"], force: v.force, log: ctx.note, env: ctx.env });
if (!r.ok) ctx.note(`Not scored: ${r.reason}. Timing and cost are in the report; pnpm eval:report ${path.basename(dir)} scores it later.`);
return r;
}
@@ -287,11 +288,26 @@ async function compare(args, ctx) {
}
async function promoteCmd(args, ctx) {
- const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" } }, { positionals: true });
+ const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" }, record: { type: "boolean" }, research: { type: "string" } }, { positionals: true });
if (v.help) return ctx.print(HELP.promote), 0;
const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
const doc = promote(dir, { candidate: v.candidate, alternatives: list(v.against) });
ctx.print(v.json ? JSON.stringify(doc, null, 2) : promoteText(doc));
+ if (!v.record) return 0;
+ // --record: the verdicts go into the research JSON for a person to review (git diff), never a default.
+ if (doc.engine === "demo") throw new Error("A demo run measures the harness, not models: there is nothing to record in the research.");
+ const records = researchRecords(doc);
+ if (!records.length) return ctx.note("No look or motion in this run to record."), 0;
+ const file = path.resolve(v.research ?? path.join(REPO_DIR, RECIPES_FILE));
+ const recordsFile = path.join(dir, "research-records.json");
+ fs.writeFileSync(recordsFile, `${JSON.stringify(records, null, 2)}\n`);
+ const py = ctx.env.FUOBE_EVAL_PYTHON ?? (process.platform === "win32" ? "python" : "python3");
+ const r = spawnSync(py, ["-I", path.join(METRICS_DIR, "fuobe_metrics", "research.py"), recordsFile, file], { encoding: "utf8", env: ctx.env });
+ if (r.error) throw new Error(`--record needs Python 3 (${py} isn't there; set FUOBE_EVAL_PYTHON)`);
+ if (r.status !== 0) throw new Error(`Recording failed: ${(r.stderr || r.stdout).trim().split("\n").at(-1)}`);
+ const res = JSON.parse(r.stdout);
+ ctx.note(`Recorded ${res.recorded} result${res.recorded === 1 ? "" : "s"} in ${path.relative(REPO_DIR, file) || file} (each entry's "eval" list). Review the diff; recipes and defaults change only by hand.`);
+ for (const m of res.missing) ctx.note(` not in the research: ${JSON.stringify(m)}`);
return 0;
}
@@ -333,7 +349,7 @@ async function validate(args, ctx) {
}
async function setup(args, ctx) {
- const { values: v } = parse(args, { identity: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
+ const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
const step = (cmd, a, opts = {}) => {
ctx.note(`$ ${cmd} ${a.join(" ")}`);
const r = spawnSync(cmd, a, { cwd: METRICS_DIR, stdio: "inherit", env: ctx.env, ...opts });
@@ -344,7 +360,7 @@ async function setup(args, ctx) {
if (!fs.existsSync(path.join(METRICS_DIR, py))) step("uv", ["venv", ".venv", "--python", ">=3.11"]);
step("uv", ["pip", "install", "--python", py, "-r", "requirements.txt", "--torch-backend", v["torch-backend"] ?? "cpu"]);
if (v.identity) step("uv", ["pip", "install", "--python", py, "-r", "requirements-identity.txt"]);
- if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : [])]);
+ if (v.download) step(py, ["-m", "fuobe_metrics.download", ...(v.identity ? ["--identity"] : []), ...(v.dinov2 ? ["--dinov2"] : [])]);
ctx.print(`Metrics ready in ${path.join(METRICS_DIR, ".venv")}${v.download ? "" : " (weights download on first use, or run pnpm eval:setup --download)"}.`);
return 0;
}
diff --git a/scripts/eval/lib/compare.mjs b/scripts/eval/lib/compare.mjs
index b7b54a48..868d324e 100644
--- a/scripts/eval/lib/compare.mjs
+++ b/scripts/eval/lib/compare.mjs
@@ -168,6 +168,8 @@ export function promote(dir, { candidate, alternatives, rule = PROMOTE_RULE } =
const reasons = [];
const notes = [];
let verdictText;
+ /** The strengths a winning half-strength variant ran at: what the record suggests. */
+ let suggested = null;
const recipe = ok[0]?.recipe ?? mine[0]?.recipe;
// 1. licence and completeness
const applied = recipe?.applied ?? recipe?.sent?.loras ?? [];
@@ -191,7 +193,10 @@ export function promote(dir, { candidate, alternatives, rule = PROMOTE_RULE } =
if (mc.candidate == null || mc.alternative == null) reasons.push(`no ${main} scores against ${alt} (run pnpm eval:report)`);
else if (mc.candidate < mc.alternative) {
reasons.push(`${alt} scores higher on ${main} (${fmt(main, mc.alternative)} vs ${fmt(main, mc.candidate)})`);
- if (/half/.test(alt)) notes.push("half strength wins: the LoRAs over-cook here — lower their strengths in the research JSON and run again");
+ if (/half/.test(alt)) {
+ notes.push("half strength wins: the LoRAs over-cook here — lower their strengths in the research JSON and run again");
+ suggested = (theirs[0].recipe?.applied ?? theirs[0].recipe?.sent?.loras ?? []).map((l) => ({ file: l.file, strength: l.strength ?? 1 }));
+ }
}
if (row.clip.candidate != null && row.clip.alternative != null && row.clip.candidate < row.clip.alternative - rule.clipGuard) reasons.push(`it follows the prompt worse than ${alt} (CLIP ${fmt("clip", row.clip.candidate)} vs ${fmt("clip", row.clip.alternative)})`);
if (main !== "aesthetic" && row.aesthetic.candidate != null && row.aesthetic.alternative != null && row.aesthetic.candidate < row.aesthetic.alternative - rule.aestheticGuard) reasons.push(`it looks worse than ${alt} (aesthetic ${fmt("aesthetic", row.aesthetic.candidate)} vs ${fmt("aesthetic", row.aesthetic.alternative)})`);
@@ -206,7 +211,7 @@ export function promote(dir, { candidate, alternatives, rule = PROMOTE_RULE } =
else if (forCand + forAlt && forCand / (forCand + forAlt) < rule.minPreference) reasons.push(`people preferred it ${Math.round((100 * forCand) / (forCand + forAlt))}% of the time, the rule wants ${Math.round(rule.minPreference * 100)}%`);
// Over-cooking is its own verdict: the fix is a lower strength, not another recipe.
verdictText = !reasons.length ? "promote" : notes.length ? "lower strengths" : "hold";
- results.push({ caseId, title: mine[0]?.caseTitle ?? caseId, look: recipe?.look ?? null, candidate: cand, verdict: verdictText, reasons, notes, mainMetric: main, against, recipe: recipe ? { loras: applied.map((l) => ({ file: l.file, strength: l.strength ?? 1 })), source: recipe.source } : null });
+ results.push({ caseId, title: mine[0]?.caseTitle ?? caseId, look: recipe?.look ?? null, target: researchTarget(recipe), candidate: cand, verdict: verdictText, reasons, notes, mainMetric: main, against, recipe: recipe ? { loras: applied.map((l) => ({ file: l.file, strength: l.strength ?? 1 })), source: recipe.source } : null, ...(suggested && { suggested }) });
}
const doc = {
runId: L.run.runId,
@@ -223,6 +228,40 @@ export function promote(dir, { candidate, alternatives, rule = PROMOTE_RULE } =
return doc;
}
+/** Which research entry a case measured: a Soul look (presets[id]) or a motion / effect (motionsEffects). */
+function researchTarget(recipe) {
+ if (recipe?.kind === "soul-look" && recipe.look?.id) return { look: recipe.look.id };
+ const motion = recipe?.motion ?? (recipe?.presets?.length === 1 ? recipe.presets[0] : null);
+ return motion ? { motion } : null;
+}
+
+const round = (x) => (typeof x === "number" ? Math.round(x * 10000) / 10000 : x);
+
+/**
+ * The records `promote --record` writes into the research JSON (fuobe_metrics/research.py puts them in
+ * place): one per case that measured a look or a motion. Demo runs have nothing to record.
+ */
+export function researchRecords(doc, { date = new Date().toISOString().slice(0, 10) } = {}) {
+ if (doc.engine === "demo") return [];
+ return doc.results
+ .filter((r) => r.target)
+ .map((r) => ({
+ target: r.target,
+ engine: doc.engine,
+ case: r.caseId,
+ runId: doc.runId,
+ date,
+ candidate: r.candidate,
+ verdict: r.verdict,
+ reasons: r.reasons,
+ ...(r.notes.length && { notes: r.notes }),
+ mainMetric: r.mainMetric,
+ against: r.against.map((a) => Object.fromEntries(Object.entries(a).map(([k, v]) => [k, v && typeof v === "object" ? { candidate: round(v.candidate), alternative: round(v.alternative) } : v]))),
+ loras: r.recipe?.loras ?? [],
+ ...(r.suggested && { suggestedLoras: r.suggested }),
+ }));
+}
+
export function promoteText(doc) {
const count = (v) => doc.results.filter((r) => r.verdict === v).length;
const lines = [`${doc.suite} · ${doc.engine} · candidate “${doc.candidate}” against ${doc.alternatives.join(", ") || "nothing"}`, `${count("promote")} eligible · ${count("lower strengths")} to lower · ${count("hold")} on hold`, ""];
diff --git a/scripts/eval/lib/metrics.mjs b/scripts/eval/lib/metrics.mjs
index fb865097..07e328ec 100644
--- a/scripts/eval/lib/metrics.mjs
+++ b/scripts/eval/lib/metrics.mjs
@@ -19,7 +19,7 @@ export function pythonCommand(env = process.env) {
}
/** Score a run folder; resolves with {ok, file, doc, skipped} and streams the scorer's progress to `log`. */
-export function scoreRun(dir, { metrics, device, clipModel, identityModel, acceptNoncommercial, force, log = () => {}, env = process.env } = {}) {
+export function scoreRun(dir, { metrics, device, clipModel, styleModel, identityModel, acceptNoncommercial, force, log = () => {}, env = process.env } = {}) {
const py = pythonCommand(env);
if (!py) return Promise.resolve({ ok: false, reason: "No Python for the metrics: run pnpm eval:setup (needs uv), or set FUOBE_EVAL_PYTHON" });
const args = [
@@ -30,6 +30,7 @@ export function scoreRun(dir, { metrics, device, clipModel, identityModel, accep
...(metrics ? ["--metrics", metrics] : []),
...(device ? ["--device", device] : []),
...(clipModel ? ["--clip-model", clipModel] : []),
+ ...(styleModel ? ["--style-model", styleModel] : []),
...(identityModel ? ["--identity-model", identityModel] : []),
...(acceptNoncommercial ? ["--accept-noncommercial"] : []),
...(force ? ["--force"] : []),
diff --git a/scripts/eval/lib/recipes.mjs b/scripts/eval/lib/recipes.mjs
index 9519d151..f2a08a91 100644
--- a/scripts/eval/lib/recipes.mjs
+++ b/scripts/eval/lib/recipes.mjs
@@ -114,6 +114,7 @@ export function recipeFor(kind, kase) {
if (!m) throw new Error(`No research entry for the motion or effect “${kase.motion}” (${RECIPES_FILE} → motionsEffects)`);
return {
kind: m.kind,
+ motion: kase.motion,
source: `${RECIPES_FILE} → motionsEffects (${m.presets.join(", ")})`,
presets: m.presets,
status: m.status,
diff --git a/scripts/eval/lib/schema.mjs b/scripts/eval/lib/schema.mjs
index da0d105f..1c501a1c 100644
--- a/scripts/eval/lib/schema.mjs
+++ b/scripts/eval/lib/schema.mjs
@@ -1,6 +1,6 @@
// The case-file format (scripts/eval/cases/*.json): one suite per Fuobe Original, its targets per
// engine, the recipe variants to compare, and the cases (prompt sets with pinned seeds, inputs,
-// references, training runs, shot lists). `pnpm eval:validate` and tests/eval-cases.test.ts check
+// references, training runs, shot lists). `pnpm eval:validate` and tests/eval-harness.test.ts check
// every file against it; `schemaJson()` writes cases/case.schema.json for editors.
import { z } from "zod";
diff --git a/scripts/eval/metrics/fuobe_metrics/download.py b/scripts/eval/metrics/fuobe_metrics/download.py
index 7ff3df6c..e8fe20ed 100644
--- a/scripts/eval/metrics/fuobe_metrics/download.py
+++ b/scripts/eval/metrics/fuobe_metrics/download.py
@@ -1,4 +1,4 @@
-"""Fetch the metric weights at their pinned revisions: python -m fuobe_metrics.download [--identity] [--no-aesthetic].
+"""Fetch the metric weights at their pinned revisions: python -m fuobe_metrics.download [--identity] [--dinov2] [--no-aesthetic].
They go to FUOBE_EVAL_CACHE (default ~/.cache/fuobe-eval); scoring downloads them on first use otherwise."""
from __future__ import annotations
@@ -14,10 +14,13 @@ def main(argv=None) -> int:
ap = argparse.ArgumentParser(prog="fuobe_metrics.download")
ap.add_argument("--identity", action="store_true", help="also AuraFace (Apache-2.0) for identity and the lip-sync face box")
ap.add_argument("--no-aesthetic", action="store_true", help="skip CLIP ViT-L/14 and the aesthetic head (about 1.7 GB)")
+ ap.add_argument("--dinov2", action="store_true", help="also DINOv2 ViT-S/14 (Apache-2.0, 88 MB) for --style-model dinov2")
args = ap.parse_args(argv)
wanted = [("clip-b32", MODELS["clip-b32"]["file"])]
if not args.no_aesthetic:
wanted += [("clip-l14", MODELS["clip-l14"]["file"]), ("aesthetic-v2", MODELS["aesthetic-v2"]["file"])]
+ if args.dinov2:
+ wanted += [("dinov2-small", MODELS["dinov2-small"]["file"])]
if args.identity:
wanted += [("auraface", f) for f in MODELS["auraface"]["files"]]
for key, f in wanted:
diff --git a/scripts/eval/metrics/fuobe_metrics/models.py b/scripts/eval/metrics/fuobe_metrics/models.py
index bcbb878a..e4663f6a 100644
--- a/scripts/eval/metrics/fuobe_metrics/models.py
+++ b/scripts/eval/metrics/fuobe_metrics/models.py
@@ -78,6 +78,37 @@ class Clip:
return self.torch.nn.functional.normalize(e, dim=-1).float().cpu().numpy()
+class Dino:
+ """DINOv2 ViT-S/14 image embeddings through timm (Apache-2.0), at 224 px for the CPU: a style and content
+ descriptor that, unlike CLIP, owes nothing to captions (--style-model dinov2)."""
+
+ def __init__(self, device: str = "cpu"):
+ try:
+ import timm # noqa: PLC0415
+ except ImportError as e:
+ raise Missing("timm isn't installed: run pnpm eval:setup") from e
+ torch = _torch()
+ m = MODELS["dinov2-small"]
+ weights = _download("dinov2-small", m["file"])
+ self.model = timm.create_model(m["arch"], pretrained=True, pretrained_cfg_overlay={"file": weights}, num_classes=0, img_size=224)
+ self.model.eval().to(device)
+ cfg = {**timm.data.resolve_data_config({}, model=self.model), "input_size": (3, 224, 224)}
+ self.preprocess = timm.data.create_transform(**cfg)
+ self.device = device
+ self.torch = torch
+
+ def images(self, pictures) -> np.ndarray:
+ if not pictures:
+ return np.zeros((0, 1))
+ with self.torch.no_grad():
+ out = []
+ for i in range(0, len(pictures), 16):
+ batch = self.torch.stack([self.preprocess(p.convert("RGB")) for p in pictures[i : i + 16]]).to(self.device)
+ e = self.model(batch)
+ out.append(self.torch.nn.functional.normalize(e, dim=-1).float().cpu().numpy())
+ return np.concatenate(out)
+
+
class Aesthetic:
"""The LAION improved aesthetic predictor (v2, sac+logos+ava1 linear MSE) on CLIP ViT-L/14 embeddings: about 1–10."""
diff --git a/scripts/eval/metrics/fuobe_metrics/registry.py b/scripts/eval/metrics/fuobe_metrics/registry.py
index 7c730abc..76c3217c 100644
--- a/scripts/eval/metrics/fuobe_metrics/registry.py
+++ b/scripts/eval/metrics/fuobe_metrics/registry.py
@@ -66,9 +66,13 @@ MODELS = {
"licence": "non-commercial research only (insightface model packs)",
"commercial": False,
},
+ # Style similarity on image features alone (--style-model dinov2): DINOv2 ViT-S/14 as timm packs it.
"dinov2-small": {
- "repo": "facebook/dinov2-small",
- "licence": "Apache-2.0",
+ "arch": "vit_small_patch14_dinov2.lvd142m",
+ "repo": "timm/vit_small_patch14_dinov2.lvd142m",
+ "file": "model.safetensors",
+ "revision": "4610ca143709d58a633b6397a74412c2c3842454",
+ "licence": "Apache-2.0 (facebookresearch/dinov2)",
"commercial": True,
},
}
diff --git a/scripts/eval/metrics/fuobe_metrics/research.py b/scripts/eval/metrics/fuobe_metrics/research.py
new file mode 100644
index 00000000..870a6f7a
--- /dev/null
+++ b/scripts/eval/metrics/fuobe_metrics/research.py
@@ -0,0 +1,76 @@
+"""Record evaluation results back into the research JSON (pnpm eval:promote <run> --record).
+
+Each record lands in the `eval` list of the entry it measured: a Soul look's `presets[]` entry (by id)
+or the `motionsEffects[]` entry that lists the motion or effect. A newer record for the same engine and
+case replaces the older one. Strengths and defaults are never changed here: the record says what the
+run found (and the lower strengths it suggests); a person changes the recipe in a reviewed commit.
+
+Standard library only, so any Python 3 runs it. The file is written the way the research tools write
+it (indent 1, UTF-8 kept, a final newline), so the diff shows only the records.
+
+ python3 -I research.py <records.json> <research.json>
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+CONVENTION = (
+ "eval: results from the evaluation harness (scripts/eval, pnpm eval:promote <run> --record), one per "
+ "engine and case: run id, date, candidate variant, verdict (promote / lower strengths / hold) and why, "
+ "the look's main metric against each alternative, the LoRAs it ran and suggested lower strengths. "
+ "A record never changes a recipe or a default; a person does, in a reviewed commit."
+)
+
+
+def _find(doc: dict, target: dict) -> dict | None:
+ if target.get("look"):
+ return next((p for p in doc.get("presets", []) if p.get("id") == target["look"]), None)
+ if target.get("motion"):
+ want = str(target["motion"]).lower()
+ return next(
+ (m for m in doc.get("motionsEffects", []) if any(str(p).lower() == want for p in m.get("presets", []))),
+ None,
+ )
+ return None
+
+
+def apply_records(doc: dict, records: list[dict]) -> dict:
+ """Put each record into its entry; returns {"recorded": n, "missing": [targets not found]}."""
+ recorded = 0
+ missing = []
+ for rec in records:
+ target = rec.get("target") or {}
+ entry = _find(doc, target)
+ if entry is None:
+ missing.append(target)
+ continue
+ body = {k: v for k, v in rec.items() if k != "target"}
+ if target.get("motion"):
+ body = {"preset": target["motion"], **body}
+ kept = [r for r in entry.get("eval", []) if not (r.get("engine") == body.get("engine") and r.get("case") == body.get("case"))]
+ entry["eval"] = kept + [body]
+ recorded += 1
+ if recorded:
+ doc.setdefault("conventions", {})["eval"] = CONVENTION
+ return {"recorded": recorded, "missing": missing}
+
+
+def main(argv: list[str]) -> int:
+ if len(argv) != 2:
+ print(__doc__.strip().splitlines()[-1].strip(), file=sys.stderr)
+ return 2
+ records = json.loads(Path(argv[0]).read_text(encoding="utf-8"))
+ path = Path(argv[1])
+ doc = json.loads(path.read_text(encoding="utf-8"))
+ result = apply_records(doc, records)
+ if result["recorded"]:
+ path.write_text(json.dumps(doc, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps(result, ensure_ascii=False))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/eval/metrics/fuobe_metrics/score.py b/scripts/eval/metrics/fuobe_metrics/score.py
index d9deb909..43f178eb 100644
--- a/scripts/eval/metrics/fuobe_metrics/score.py
+++ b/scripts/eval/metrics/fuobe_metrics/score.py
@@ -19,7 +19,7 @@ import numpy as np
from . import maths
from .media import audio_track, have_ffmpeg, images_of, kind_of, video_frames
-from .models import MODELS, Aesthetic, Clip, Faces, Missing, device_of
+from .models import MODELS, Aesthetic, Clip, Dino, Faces, Missing, device_of
from .registry import FAMILIES
VERSION = 1
@@ -74,6 +74,7 @@ class Scorer:
self._clip_l14 = None
self._aesthetic = None
self._faces = None
+ self._dino = None
self.used: dict[str, dict] = {}
self.skipped: dict[str, str] = {}
@@ -92,6 +93,16 @@ class Scorer:
self.used["aesthetic"] = {"head": MODELS["aesthetic-v2"], "clip": MODELS["clip-l14"]}
return self._aesthetic
+ def style_model(self):
+ """The image embedder style similarity uses: CLIP (default, already loaded for prompt adherence) or DINOv2."""
+ if getattr(self.args, "style_model", "clip") != "dinov2":
+ self.used["style"] = {**MODELS[self.args.clip_model], "key": self.args.clip_model}
+ return self.clip()
+ if self._dino is None:
+ self._dino = Dino(self.device)
+ self.used["style"] = {**MODELS["dinov2-small"], "key": "dinov2-small"}
+ return self._dino
+
def faces(self):
if self._faces is None:
name = self.args.identity_model
@@ -135,8 +146,9 @@ class Scorer:
pics = [p for o in outs for p in images_of(o, frames=4)]
if not pics:
return {"_note": "no picture to score"}
- ref_emb = self.clip().images(refs)
- out_emb = maths.l2norm(self.clip().images(pics).mean(axis=0))
+ model = self.style_model()
+ ref_emb = model.images(refs)
+ out_emb = maths.l2norm(model.images(pics).mean(axis=0))
s = maths.reference_similarity(out_emb, ref_emb)
return {"style": round(s["centroid"], 4), "styleNearest": round(s["nearest"], 4), "_refs": s["n"]}
@@ -259,6 +271,7 @@ def main(argv=None) -> int:
ap.add_argument("--metrics", help="families to compute (default: each job's own list)")
ap.add_argument("--device", default="cpu", help="cpu (default), cuda, mps or auto")
ap.add_argument("--clip-model", default="clip-b32", choices=["clip-b32", "clip-l14"])
+ ap.add_argument("--style-model", default="clip", choices=["clip", "dinov2"], help="image embeddings for style similarity")
ap.add_argument("--identity-model", default="auraface", choices=["auraface", "buffalo_l"])
ap.add_argument("--accept-noncommercial", action="store_true", help="allow buffalo_l (non-commercial research licence)")
ap.add_argument("--frames", type=int, default=24, help="frames sampled per clip for temporal metrics")
@@ -280,7 +293,7 @@ def main(argv=None) -> int:
out_file = run_dir / "metrics.json"
previous = json.loads(out_file.read_text(encoding="utf8")) if out_file.exists() and not args.force else {}
- config = {"v": VERSION, "clip": args.clip_model, "identity": args.identity_model, "frames": args.frames, "fps": args.fps}
+ config = {"v": VERSION, "clip": args.clip_model, "style": args.style_model, "identity": args.identity_model, "frames": args.frames, "fps": args.fps}
scorer = Scorer(args)
jobs = read_jobs(run_dir)
results: dict[str, dict] = {}
diff --git a/scripts/eval/metrics/tests/test_media_and_models.py b/scripts/eval/metrics/tests/test_media_and_models.py
index 70c50e60..0544dacb 100644
--- a/scripts/eval/metrics/tests/test_media_and_models.py
+++ b/scripts/eval/metrics/tests/test_media_and_models.py
@@ -129,3 +129,20 @@ def test_faces_on_drawn_faces_do_not_crash():
def test_fixtures_are_where_the_tests_expect():
assert (FIXTURES / "palette.png").exists()
assert pathlib.Path(media.__file__).name == "media.py"
+
+
+def test_dinov2_style_embeddings_rank_the_matching_reference_first():
+ pytest.importorskip("torch")
+ pytest.importorskip("timm")
+ if not _weights_cached("timm/vit_small_patch14_dinov2.lvd142m"):
+ pytest.skip("DINOv2 weights aren't cached (pnpm eval:setup --download --dinov2)")
+ from fuobe_metrics import maths
+ from fuobe_metrics.models import Dino
+
+ d = Dino()
+ refs = d.images([media.load_image(FIXTURES / "references" / "warm-1.png")])
+ pics = d.images([media.load_image(FIXTURES / "references" / "warm-2.png"), media.load_image(FIXTURES / "palette.png")])
+ assert refs.shape == (1, 384) and abs(np.linalg.norm(refs[0]) - 1) < 1e-4
+ warm = maths.reference_similarity(pics[0], refs)["centroid"]
+ stripes = maths.reference_similarity(pics[1], refs)["centroid"]
+ assert warm > stripes
diff --git a/scripts/eval/metrics/tests/test_research.py b/scripts/eval/metrics/tests/test_research.py
new file mode 100644
index 00000000..655218bb
--- /dev/null
+++ b/scripts/eval/metrics/tests/test_research.py
@@ -0,0 +1,52 @@
+"""promote --record: results go into the research entry they measured, replacing the same engine and case."""
+
+import json
+
+from fuobe_metrics import research
+
+
+def doc():
+ return {
+ "conventions": {"lora": "…"},
+ "presets": [{"id": "look-1", "name": "General", "loras": [{"file": "a.safetensors", "strength": 1.0}]}],
+ "motionsEffects": [{"kind": "motion", "presets": ["Overhead", "Crane Up"], "loras": []}],
+ }
+
+
+def record(engine="open", case="soul/v1-general", verdict="hold", **target):
+ return {"target": target or {"look": "look-1"}, "engine": engine, "case": case, "runId": "r1", "verdict": verdict}
+
+
+def test_records_land_in_their_entry_and_replace_the_same_engine_and_case():
+ d = doc()
+ out = research.apply_records(d, [record(), record(engine="cloud"), record(motion="crane up", case="dop/motion-crane-up")])
+ assert out == {"recorded": 3, "missing": []}
+ assert [r["engine"] for r in d["presets"][0]["eval"]] == ["open", "cloud"]
+ assert "target" not in d["presets"][0]["eval"][0]
+ assert d["motionsEffects"][0]["eval"][0]["preset"] == "crane up"
+ assert "eval" in d["conventions"]
+ # A newer open run of the same case replaces the older record; the recipe itself is untouched.
+ research.apply_records(d, [record(verdict="promote")])
+ assert [(r["engine"], r["verdict"]) for r in d["presets"][0]["eval"]] == [("cloud", "hold"), ("open", "promote")]
+ assert d["presets"][0]["loras"][0]["strength"] == 1.0
+
+
+def test_unknown_targets_are_reported_not_invented():
+ d = doc()
+ out = research.apply_records(d, [record(look="nope"), record(motion="Dolly Zoom")])
+ assert out["recorded"] == 0 and len(out["missing"]) == 2
+ assert "eval" not in d["conventions"]
+
+
+def test_the_file_keeps_its_format(tmp_path):
+ d = doc()
+ d["presets"][0]["name"] = "Café → film"
+ f = tmp_path / "research.json"
+ f.write_text(json.dumps(d, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
+ recs = tmp_path / "records.json"
+ recs.write_text(json.dumps([record()]), encoding="utf-8")
+ assert research.main([str(recs), str(f)]) == 0
+ text = f.read_text(encoding="utf-8")
+ assert "Café → film" in text and "\\u" not in text
+ assert text.endswith("}\n") and text.startswith('{\n "conventions"')
+ assert json.loads(text)["presets"][0]["loras"][0]["strength"] == 1.0
diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.ts
index 6b319646..3b0d0f44 100644
--- a/tests/eval-harness.test.ts
+++ b/tests/eval-harness.test.ts
@@ -1,3 +1,4 @@
+import { spawnSync } from "node:child_process";
import fs from "node:fs";
import http from "node:http";
import type { AddressInfo } from "node:net";
@@ -372,6 +373,40 @@ describe("report, blind review, compare and promote", () => {
expect(compare.promote(demo).results[0].reasons[0]).toBe("demo media, not model output");
});
+ it("promote --record writes each verdict into the research entry it measured, and nothing else", async () => {
+ const python = spawnSync("python3", ["--version"]).status === 0 ? "python3" : null;
+ if (!python) return; // no Python 3 here: the pytest covers the writer where there is one
+ const research = path.join(process.cwd(), "docs/research/fuobe-originals-recipes-5.json");
+ const copy = path.join(dir, "research-copy.json");
+ fs.copyFileSync(research, copy);
+ const before = fs.readFileSync(copy, "utf8");
+ const look = "464ea177-8d40-4940-8d9d-b438bab269c7";
+ // fake-open-2 has half strength beating the recipe: give its rows the look they measured.
+ const runDir = path.join(results, "fake-open-2");
+ const rows = store.latestJobs(runDir).map((r) => ({ ...r, recipe: { ...r.recipe, look: { id: look, slug: "v1-general" }, ...(r.variant === "half-strength" && { applied: [{ file: "a.safetensors", strength: 0.35 }] }) } }));
+ fs.writeFileSync(path.join(runDir, "jobs.jsonl"), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ const run = async (args: string[]) => {
+ const err = sink();
+ const code = await evalCli.main(["promote", ...args, "--record", "--research", copy], { stdout: sink().stream, stderr: err.stream, env: { ...process.env, FUOBE_EVAL_RESULTS: results, FUOBE_EVAL_PYTHON: python } });
+ return { code, stderr: err.text() };
+ };
+ const r = await run(["fake-open-2"]);
+ expect(r.code, r.stderr).toBe(0);
+ expect(r.stderr).toMatch(/Recorded 1 result/);
+ await run(["fake-open-2"]); // again: the record is replaced, not added
+ const after = JSON.parse(fs.readFileSync(copy, "utf8"));
+ const entry = after.presets.find((p: { id: string }) => p.id === look);
+ expect(entry.eval).toHaveLength(1);
+ expect(entry.eval[0]).toMatchObject({ engine: "open", case: "soul/look-a", runId: "fake-open-2", verdict: "lower strengths", mainMetric: "style", suggestedLoras: [{ file: "a.safetensors", strength: 0.35 }] });
+ // Only the record and its convention line are new: recipes, strengths and the file's format stay.
+ delete entry.eval;
+ delete after.conventions.eval;
+ expect(after).toEqual(JSON.parse(before));
+ expect(fs.readFileSync(copy, "utf8")).not.toMatch(/\\u[0-9a-f]{4}/);
+ // Demo runs have nothing to record.
+ expect((await run(["fake-demo-1"])).stderr).toMatch(/demo run measures the harness/);
+ });
+
it("compare prints wins and losses and fails when a chosen metric regresses beyond the threshold", async () => {
fakeRun("fake-open-3", "open", { ...scored("recipe", 0.8, 28.5), ...scored("prompt-only", 0.7, 31) });
const ok = await cli(["compare", "fake-open-1", "fake-open-3", "--fail-on", "style"]);