Photo curation pipeline (2/3): Clef decision-model judge, local on M1 (mlx-community/clef-flash-4bit) #6

Open
opened 2026-10-14 11:03:32 +00:00 by xrisk · 1 comment
Owner

Goal

Add a model-judge stage to the clock-photo curation pipeline that scores photos with Cloudflare's Clef decision model, running locally on the M1 Pro (16 GB) — not via any hosted API. This is stage 2 of 3. Companion issues: #5 (stage 1, cheap local pre-filters) and stage 3 (LAION aesthetic predictor baseline, filed separately). Work on this issue independently; do not implement the other stages.

Why

Generic aesthetic scores cannot judge "good living-room TV wallpaper" (no text/watermarks, works cover-cropped to 16:9, well exposed for a bright room, calm composition). Clef is a decision model: you send the image plus a schema of typed questions whose instructions/criteria are natural language, and it returns calibrated probabilities for every option in a single non-autoregressive forward pass — no text generation, no parsing. It is the open-weight (Apache-2.0) counterpart of TypeSafe's Jev, but multimodal (Jev is text-only, and closed-source).

Model + how to run it (verified — follow exactly)

  • Model: mlx-community/clef-flash-4bit on HuggingFace — Cloudflare's clef-flash (9B, Qwen3.5-9B base + vision encoder + custom joint schema head), MLX 4-bit. 6.2 GB download, ~7 GB peak RAM → fits the M1 Pro 16 GB. License: Apache-2.0.
  • Install: pip install "mlx-vlm>=0.7.4,<0.8" huggingface_hub (no torch needed), then hf download mlx-community/clef-flash-4bit --local-dir clef-flash-4bit.
  • You must use the bundled clef_mlx.py loader shipped in that repo. Clef is not a chat model: mlx_vlm.generate, mlx_lm.generate, LM Studio, and Ollama load the backbone but produce meaningless text — the custom decision head (two-stage attention routing over the schema) only runs via clef_mlx.py, as model.systemone({...}) / model.predict({...}), via its CLI (python clef_mlx.py predict --image photo.jpg --state ... --questions '{...}'), or as a localhost server (clef_mlx.py serve --port 8000, Jev-compatible POST /v1/systemone).
  • Latency: ~0.3 s/decision on an M5 Max; expect a few seconds per photo on a base M1 Pro — fine for batch curation at ingest time. One record per call (no batching) → loop in the script.
  • Quality: 4-bit is ~1 point below bf16 on Cloudflare's Decision Index; top-answer agreement >96% vs bf16.
  • References: https://huggingface.co/mlx-community/clef-flash-4bit · https://huggingface.co/Cloudflare/clef-flash · https://blog.cloudflare.com/clef-decision-models/

Suggested question schema (refine as you see fit)

{
  "state": ["A photo from the clock-photo library, being considered as a living-room TV wallpaper (full-screen clock background).", { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,..." } }],
  "questions": {
    "sharp":       { "type": "noul", "instructions": "Is the photo sharp and in focus at full-TV scale, without motion blur?" },
    "well_exposed": { "type": "noul", "instructions": "Is the photo well exposed for a bright living room — not too dark, not blown out?" },
    "no_text":     { "type": "noul", "instructions": "Is the image free of visible text, watermarks, logos, timestamps, and frame borders?" },
    "calm":        { "type": "noul", "instructions": "Is the composition calm and uncluttered, with a clear subject that still works when cover-cropped to 16:9?" },
    "wallpaper":   { "type": "choice", "instructions": "Should this photo be used as a TV wallpaper?",
                     "criteria": { "keep": "Sharp, well exposed, calm composition, no text/watermarks, works at 16:9",
                                   "reject": "Blurry, poorly exposed, cluttered, contains text/watermarks, or awkward to crop" } }
  }
}

The natural-language semantics live in instructions/criteria. Responses are typed answers with per-option probabilities + confidence — threshold on wallpaper=keep with a confidence floor, or rank by a score question instead.

What to build

A maintainer-run script under scripts/ (style of discover-clock-photos.py) that:

  1. Takes the photos that passed stage 1 (decide the CLI interface: set id / directory / manifest filter),
  2. Loads the model once via clef_mlx.py, loops one record per call, and catches per-photo errors without aborting the batch,
  3. Writes per-photo answers (probabilities, confidence, final verdict) to a JSON sidecar atomically (temp file + mv),
  4. Documents setup (venv, pip install, hf download) in the script docstring and/or docs/, plus expected runtime on the M1 Pro.

Run it after the pre-filters and before --clock-photo-probe, so Vision segmentation is never spent on rejects.

Repo context (read first)

  • AGENTS.md — product constraints + source-control workflow: worktree under .worktrees/ on a feat/… branch; commit freely; make test before proposing a merge; never merge/push to main without explicit operator confirmation; push only when asked.
  • .wiki/_index.md + .wiki/wiki/references/task-routing.md — canonical routing; "Clock photos" section (manifest, probe, atomic-write rule, push path). (Wiki says manifest is at Resources/photos/manifest.json; actual path is Sources/TVDashboard/Resources/photos/manifest.json.)
  • Manifest: Sources/TVDashboard/Resources/photos/manifest.json (file/caption/credit/date/author/license/source/downloadUrl/clockY/depth); loader Sources/TVDashboard/Clock/ClockPhotoLibrary.swift.
  • Ingest flow: discover-clock-photos.py → fetch-clock-photos.sh → --clock-photo-probe → gen-photo-credits.py.
  • Kiosk constraints: TV view is read-only; curation is an operator-time maintainer tool (no TV-facing UI); the app must stay offline-resilient — the model runs at ingest time, never at display time.
  • Update .wiki/ (committed on your feature branch) for durable decisions (where the judge runs, sidecar location, schema).

Decisions already made (do not re-litigate)

  • Judge = Clef, local on the M1 Pro, via the MLX 4-bit port.
  • Hosted paths are explicitly NOT planned for now: no Cloudflare Workers AI API, no OpenRouter, no TypeSafe Jev (closed source, text-only). If you conclude a hosted path is unavoidable, stop and explain why in this issue instead of building it.
  • Stages 1 (#5) and 3 are separate issues — do not fold them in.

Acceptance criteria

  • Setup + run are documented; the script scores the existing pool end-to-end on the M1 Pro with no manual steps beyond the documented install.
  • Sidecar is atomic and schema-documented; per-photo failures never abort the batch.
  • Verdicts are sane on a hand-checked sample (attach the sample + results to the issue/PR notes).
  • make test passes.

Open questions for the planning agent

  • Python env convention for ML deps (this repo has no ML venv yet — check how discover-clock-photos.py declares deps; keep the MLX env separate from any PyTorch env stage 3 might want).
  • Sidecar location/schema; manifest field vs sidecar (mind the tolerant-decode gotcha).
  • Confidence-threshold policy; how re-runs invalidate stale entries (e.g. keyed by file content hash).
  • Model cache location (HF cache vs repo-local clef-flash-4bit/ — likely gitignored; check .gitignore).
# Goal Add a **model-judge stage** to the clock-photo curation pipeline that scores photos with Cloudflare's **Clef** decision model, running **locally on the M1 Pro (16 GB)** — not via any hosted API. This is **stage 2 of 3**. Companion issues: **#5** (stage 1, cheap local pre-filters) and stage 3 (LAION aesthetic predictor baseline, filed separately). Work on this issue independently; do not implement the other stages. # Why Generic aesthetic scores cannot judge "good living-room TV wallpaper" (no text/watermarks, works cover-cropped to 16:9, well exposed for a bright room, calm composition). Clef is a *decision model*: you send the image plus a schema of typed questions whose `instructions`/`criteria` are natural language, and it returns calibrated probabilities for every option in a single non-autoregressive forward pass — no text generation, no parsing. It is the open-weight (Apache-2.0) counterpart of TypeSafe's Jev, but multimodal (Jev is text-only, and closed-source). # Model + how to run it (verified — follow exactly) - **Model:** `mlx-community/clef-flash-4bit` on HuggingFace — Cloudflare's `clef-flash` (9B, Qwen3.5-9B base + vision encoder + custom joint schema head), MLX 4-bit. **6.2 GB download, ~7 GB peak RAM → fits the M1 Pro 16 GB.** License: Apache-2.0. - **Install:** `pip install "mlx-vlm>=0.7.4,<0.8" huggingface_hub` (no torch needed), then `hf download mlx-community/clef-flash-4bit --local-dir clef-flash-4bit`. - **You must use the bundled `clef_mlx.py` loader shipped in that repo.** Clef is **not a chat model**: `mlx_vlm.generate`, `mlx_lm.generate`, LM Studio, and Ollama load the backbone but produce meaningless text — the custom decision head (two-stage attention routing over the schema) only runs via `clef_mlx.py`, as `model.systemone({...})` / `model.predict({...})`, via its CLI (`python clef_mlx.py predict --image photo.jpg --state ... --questions '{...}'`), or as a localhost server (`clef_mlx.py serve --port 8000`, Jev-compatible `POST /v1/systemone`). - **Latency:** ~0.3 s/decision on an M5 Max; expect a few seconds per photo on a base M1 Pro — fine for batch curation at ingest time. One record per call (no batching) → loop in the script. - **Quality:** 4-bit is ~1 point below bf16 on Cloudflare's Decision Index; top-answer agreement >96% vs bf16. - References: https://huggingface.co/mlx-community/clef-flash-4bit · https://huggingface.co/Cloudflare/clef-flash · https://blog.cloudflare.com/clef-decision-models/ # Suggested question schema (refine as you see fit) ```json { "state": ["A photo from the clock-photo library, being considered as a living-room TV wallpaper (full-screen clock background).", { "type": "image_url", "image_url": { "url": "data:image/jpeg;base64,..." } }], "questions": { "sharp": { "type": "noul", "instructions": "Is the photo sharp and in focus at full-TV scale, without motion blur?" }, "well_exposed": { "type": "noul", "instructions": "Is the photo well exposed for a bright living room — not too dark, not blown out?" }, "no_text": { "type": "noul", "instructions": "Is the image free of visible text, watermarks, logos, timestamps, and frame borders?" }, "calm": { "type": "noul", "instructions": "Is the composition calm and uncluttered, with a clear subject that still works when cover-cropped to 16:9?" }, "wallpaper": { "type": "choice", "instructions": "Should this photo be used as a TV wallpaper?", "criteria": { "keep": "Sharp, well exposed, calm composition, no text/watermarks, works at 16:9", "reject": "Blurry, poorly exposed, cluttered, contains text/watermarks, or awkward to crop" } } } } ``` The natural-language semantics live in `instructions`/`criteria`. Responses are typed answers with per-option probabilities + confidence — threshold on `wallpaper=keep` with a confidence floor, or rank by a `score` question instead. # What to build A maintainer-run script under `scripts/` (style of `discover-clock-photos.py`) that: 1. Takes the photos that passed stage 1 (decide the CLI interface: set id / directory / manifest filter), 2. Loads the model once via `clef_mlx.py`, loops one record per call, and catches per-photo errors without aborting the batch, 3. Writes per-photo answers (probabilities, confidence, final verdict) to a JSON sidecar **atomically** (temp file + `mv`), 4. Documents setup (venv, `pip install`, `hf download`) in the script docstring and/or `docs/`, plus expected runtime on the M1 Pro. Run it **after** the pre-filters and **before** `--clock-photo-probe`, so Vision segmentation is never spent on rejects. # Repo context (read first) - `AGENTS.md` — product constraints + source-control workflow: worktree under `.worktrees/` on a `feat/…` branch; commit freely; `make test` before proposing a merge; **never merge/push to `main` without explicit operator confirmation**; push only when asked. - `.wiki/_index.md` + `.wiki/wiki/references/task-routing.md` — canonical routing; "Clock photos" section (manifest, probe, atomic-write rule, push path). (Wiki says manifest is at `Resources/photos/manifest.json`; actual path is `Sources/TVDashboard/Resources/photos/manifest.json`.) - Manifest: `Sources/TVDashboard/Resources/photos/manifest.json` (`file`/`caption`/`credit`/`date`/`author`/`license`/`source`/`downloadUrl`/`clockY`/`depth`); loader `Sources/TVDashboard/Clock/ClockPhotoLibrary.swift`. - Ingest flow: `discover-clock-photos.py` → `fetch-clock-photos.sh` → `--clock-photo-probe` → `gen-photo-credits.py`. - Kiosk constraints: TV view is read-only; curation is an operator-time maintainer tool (no TV-facing UI); the app must stay offline-resilient — the model runs at ingest time, never at display time. - Update `.wiki/` (committed on your feature branch) for durable decisions (where the judge runs, sidecar location, schema). # Decisions already made (do not re-litigate) - Judge = **Clef, local on the M1 Pro**, via the MLX 4-bit port. - **Hosted paths are explicitly NOT planned for now**: no Cloudflare Workers AI API, no OpenRouter, no TypeSafe Jev (closed source, text-only). If you conclude a hosted path is unavoidable, stop and explain why in this issue instead of building it. - Stages 1 (#5) and 3 are separate issues — do not fold them in. # Acceptance criteria - Setup + run are documented; the script scores the existing pool end-to-end on the M1 Pro with no manual steps beyond the documented install. - Sidecar is atomic and schema-documented; per-photo failures never abort the batch. - Verdicts are sane on a hand-checked sample (attach the sample + results to the issue/PR notes). - `make test` passes. # Open questions for the planning agent - Python env convention for ML deps (this repo has no ML venv yet — check how `discover-clock-photos.py` declares deps; keep the MLX env separate from any PyTorch env stage 3 might want). - Sidecar location/schema; manifest field vs sidecar (mind the tolerant-decode gotcha). - Confidence-threshold policy; how re-runs invalidate stale entries (e.g. keyed by file content hash). - Model cache location (HF cache vs repo-local `clef-flash-4bit/` — likely gitignored; check `.gitignore`).
Author
Owner

Planning update — awaiting operator approval

Planning/read-only inspection is complete. No implementation, tests, inference, or calibration have begun. All recommendations below remain unapproved. This update changes no issue scope or approval status.

Proposed scope

Add a maintainer-only Clef judge under scripts/, with model-free fixture tests and concise setup/schema documentation. Load the pinned bundled clef_mlx.py once in an isolated MLX environment, call predict serially on local images, retain option probabilities, handle per-photo errors, and atomically checkpoint a sidecar. No hosted judging, app UI, manifest edits, photo deletion/quarantine, or runtime filtering. Remain independent of companion stages #5 and #7 through fixtures and a documented input contract; explicit standalone selection should support development without merged branches.

Recommend separate stage-owned, gitignored outputs under worktree-local .photo-curation/, outside bundled resources: versioned set/file/SHA256 identity, schema/config/model provenance, and pass/reject/review/error semantics. Only fresh passes advance. Commit schemas/tests/docs, not generated pool results.

Material findings and risks

  • bake-clock-placement.py invokes a whole-set probe; ClockPhotoLibrary.swift::probe analyzes every available photo. Neither consumes curation sidecars/allowlists. Merely running this judge before baking does not spare Vision work.
  • fetch-clock-photos.sh normalizes downloaded images to sRGB JPEG, longest edge ≤1280, and can invalidate built resource copies. The worktree contains 13 seeds versus 649 manifest entries: 636 files are missing.
  • The MLX model card and bundled loader confirm local multimodal inference and Apache-2.0 metadata/LICENSE. Inspected revision: b5adbe2c3a95200d4bf04a0727c8ec457157d5e1. predict returns full option probabilities; systemone boolean answers omit explicit option maps, and choice confidence is the winning probability, not independent reliability.
  • Published memory/latency figures are M5 Max text-input measurements, not M1 photo measurements. Wallpaper quality/calibration and M1 image memory/throughput remain unknown. Use explicit local PIL images and reject silent truncation.

Validation still needed: fixture coverage for upstream selection, stale hashes/provenance, threshold boundaries, malformed outputs, per-photo failures, atomic checkpoint/resume; subsequently an approved M1 pilot, hand-checked representative sample and full-pool calibration, then scheduled make test. GUI-capable tests can activate windows and write shared caches; never relaunch/replace a running dashboard.

Questions for the operator

  1. Shared contract: Approve the sidecar/provenance/fresh-pass contract above, with explicit standalone mode? Default: yes. Gates interoperable independent stages.
  2. Integration ownership: Should #5 own an opt-in probe/bake allowlist while #6/#7 stay sidecar producers? Default: yes, if integration is elected. Deferral is possible, but “rejects never segmented” remains incomplete; keep source photos/manifest unchanged.
  3. #6 visual policy: Allow legitimate scene signage, intentional night photos and historical monochrome, penalizing overlays/watermarks/unreadable exposure, and evaluate the actual center-top 16:9 crop? Default: yes. Gates question/preprocessing design.
  4. #6 verdict policy: Use provisional P(keep)≥0.8 pass / ≤0.2 reject / otherwise review, without separate boolean vetoes? Default: yes, subject to hand-checked calibration. Gates provisional verdict behavior, not a claim of calibrated accuracy.
  5. Resources/approval: Authorize implementation plus model-free validation first, with separately scheduled permission for isolated-env installation, photo/model provisioning, serialized pilots/full-pool calibration and GUI-capable tests? Default: staged approval. Gates safe acceptance evidence without disrupting the dashboard.

Awaiting operator answers and explicit implementation approval.

## Planning update — awaiting operator approval Planning/read-only inspection is complete. **No implementation, tests, inference, or calibration have begun. All recommendations below remain unapproved.** This update changes no issue scope or approval status. ### Proposed scope Add a maintainer-only Clef judge under `scripts/`, with model-free fixture tests and concise setup/schema documentation. Load the pinned bundled `clef_mlx.py` once in an isolated MLX environment, call `predict` serially on local images, retain option probabilities, handle per-photo errors, and atomically checkpoint a sidecar. No hosted judging, app UI, manifest edits, photo deletion/quarantine, or runtime filtering. Remain independent of companion stages #5 and #7 through fixtures and a documented input contract; explicit standalone selection should support development without merged branches. Recommend separate stage-owned, gitignored outputs under worktree-local `.photo-curation/`, outside bundled resources: versioned set/file/SHA256 identity, schema/config/model provenance, and pass/reject/review/error semantics. Only fresh passes advance. Commit schemas/tests/docs, not generated pool results. ### Material findings and risks - `bake-clock-placement.py` invokes a whole-set probe; `ClockPhotoLibrary.swift::probe` analyzes every available photo. Neither consumes curation sidecars/allowlists. Merely running this judge before baking does **not** spare Vision work. - `fetch-clock-photos.sh` normalizes downloaded images to sRGB JPEG, longest edge ≤1280, and can invalidate built resource copies. The worktree contains 13 seeds versus 649 manifest entries: 636 files are missing. - The MLX [model card](https://huggingface.co/mlx-community/clef-flash-4bit) and bundled loader confirm local multimodal inference and Apache-2.0 metadata/LICENSE. Inspected revision: `b5adbe2c3a95200d4bf04a0727c8ec457157d5e1`. `predict` returns full option probabilities; `systemone` boolean answers omit explicit option maps, and choice confidence is the winning probability, not independent reliability. - Published memory/latency figures are M5 Max **text-input** measurements, not M1 photo measurements. Wallpaper quality/calibration and M1 image memory/throughput remain unknown. Use explicit local PIL images and reject silent truncation. Validation still needed: fixture coverage for upstream selection, stale hashes/provenance, threshold boundaries, malformed outputs, per-photo failures, atomic checkpoint/resume; subsequently an approved M1 pilot, hand-checked representative sample and full-pool calibration, then scheduled `make test`. GUI-capable tests can activate windows and write shared caches; never relaunch/replace a running dashboard. ### Questions for the operator 1. **Shared contract:** Approve the sidecar/provenance/fresh-pass contract above, with explicit standalone mode? **Default: yes.** Gates interoperable independent stages. 2. **Integration ownership:** Should #5 own an **opt-in probe/bake allowlist** while #6/#7 stay sidecar producers? **Default: yes, if integration is elected.** Deferral is possible, but “rejects never segmented” remains incomplete; keep source photos/manifest unchanged. 3. **#6 visual policy:** Allow legitimate scene signage, intentional night photos and historical monochrome, penalizing overlays/watermarks/unreadable exposure, and evaluate the actual center-top 16:9 crop? **Default: yes.** Gates question/preprocessing design. 4. **#6 verdict policy:** Use provisional P(keep)≥0.8 pass / ≤0.2 reject / otherwise review, without separate boolean vetoes? **Default: yes, subject to hand-checked calibration.** Gates provisional verdict behavior, not a claim of calibrated accuracy. 5. **Resources/approval:** Authorize implementation plus model-free validation first, with separately scheduled permission for isolated-env installation, photo/model provisioning, **serialized** pilots/full-pool calibration and GUI-capable tests? **Default: staged approval.** Gates safe acceptance evidence without disrupting the dashboard. **Awaiting operator answers and explicit implementation approval.**
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
xrisk/tvd#6
No description provided.