feat(heads): production per-concept heads — train + score backend (#114 A)
The eval (#1130) proved the frozen-embedding + trained-head spine; this lands its production form (the first of three slices that make heads the suggestion source, replacing Camie + centroid). - tag_head: one logistic-regression head per general/character concept with enough labelled positives. Weights (pgvector), honest CV-derived suggest threshold + earned-auto-apply point, and per-concept quality metrics. - head_training_run: persisted batch lifecycle (mirrors tag_eval_run) so the admin card shows live + historical status across navigation. - services/ml/heads.py: TRAIN (sync, ml worker, reuses tag_eval's proven data loaders + metric math so production heads match measured eval numbers) and SCORE (async, API worker — numpy via pgvector, no scikit-learn): score one image's embedding against all heads → the rail's suggestions, cached on (count, max trained_at) so a retrain invalidates without per-request loads. - tasks.ml.train_heads (ml queue, commits per head so a kill leaves progress) + recover_stalled_head_training_runs sweep + retention(20) + 5-min beat (rule 89). - api/heads.py: POST /api/heads/train (one run at a time, 409 guard) + GET /api/heads (count, graduated, last-trained, running, per-concept table, recent runs). - ml_settings: head_min_positives + head_auto_apply_precision, tunable via /api/ml/settings. Scoring isn't wired into the rail yet (slice C) and the admin UI is slice B — this slice makes training + scoring exist and CI-verifiable. 'precision' column stored as precision_cv (SQL reserved word). Migration 0058. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ttrj5P7upUTueSfoJcxEqa
This commit is contained in:
@@ -26,10 +26,12 @@ from .series_suggestion import SeriesSuggestion
|
||||
from .source import Source
|
||||
from .subscribestar_failed_media import SubscribeStarFailedMedia
|
||||
from .subscribestar_seen_media import SubscribeStarSeenMedia
|
||||
from .head_training_run import HeadTrainingRun
|
||||
from .tag import Tag, TagKind, image_tag
|
||||
from .tag_alias import TagAlias
|
||||
from .tag_allowlist import TagAllowlist
|
||||
from .tag_eval_run import TagEvalRun
|
||||
from .tag_head import TagHead
|
||||
from .tag_positive_confirmation import TagPositiveConfirmation
|
||||
from .tag_reference_embedding import TagReferenceEmbedding
|
||||
from .tag_suggestion_rejection import TagSuggestionRejection
|
||||
@@ -65,9 +67,11 @@ __all__ = [
|
||||
"ImportSettings",
|
||||
"LibraryAuditRun",
|
||||
"MLSettings",
|
||||
"HeadTrainingRun",
|
||||
"TagAlias",
|
||||
"TagAllowlist",
|
||||
"TagEvalRun",
|
||||
"TagHead",
|
||||
"TagPositiveConfirmation",
|
||||
"TagReferenceEmbedding",
|
||||
"TagSuggestionRejection",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""HeadTrainingRun — persisted lifecycle of a head-training batch (#114).
|
||||
|
||||
Mirrors TagEvalRun so the run SURVIVES navigation and the admin card can show
|
||||
live + historical status instead of holding it in transient frontend state.
|
||||
Training is idempotent (it upserts tag_head rows), so a SIGKILL'd run is harmless
|
||||
— a maintenance recovery sweep flips a stalled `running` row to `error`, and the
|
||||
next run re-trains. State machine: running → ready / error.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import DateTime, Integer, String, Text, func
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base
|
||||
|
||||
|
||||
class HeadTrainingRun(Base):
|
||||
__tablename__ = "head_training_run"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
# Training parameters: {min_positives, neg_ratio, precision_target, ...}.
|
||||
params: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, default="running", index=True
|
||||
)
|
||||
# running | ready | error
|
||||
started_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
# How many concepts got a (re)trained head vs were skipped (too few labels).
|
||||
n_trained: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
n_skipped: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# Last time the task made progress — the recovery sweep tells a live run from
|
||||
# a SIGKILL'd one by this (mirrors TagEvalRun).
|
||||
last_progress_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
@@ -55,6 +55,17 @@ class MLSettings(Base):
|
||||
video_min_tag_frames: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=3
|
||||
)
|
||||
# Tagging-v2 head training (#114). The head is the suggestion source that
|
||||
# LEARNS from the operator's tags (replacing Camie + centroid). A concept
|
||||
# needs >= head_min_positives labelled images before a head is trained;
|
||||
# head_auto_apply_precision is the precision bar a head must clear (at some
|
||||
# operating point) to "graduate" into earned auto-apply. Operator-tunable.
|
||||
head_min_positives: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, default=8
|
||||
)
|
||||
head_auto_apply_precision: Mapped[float] = mapped_column(
|
||||
Float, nullable=False, default=0.97
|
||||
)
|
||||
tagger_model_version: Mapped[str] = mapped_column(
|
||||
String(128), nullable=False, default="camie-tagger-v2"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""TagHead — a small per-concept classifier trained on the operator's tags.
|
||||
|
||||
Milestone #114, tagging-v2: the production form of the head the eval (#1130)
|
||||
proved. One row per concept (general or character) that has enough labelled
|
||||
positives. The head is a logistic-regression boundary over the FROZEN SigLIP
|
||||
embedding (L2-normalized), trained on the operator's positives + negatives
|
||||
(rejections + sampled unlabeled). It REPLACES the Camie prediction + per-tag
|
||||
centroid as the suggestion source — and unlike them it LEARNS: every accept /
|
||||
reject re-trains it sharper.
|
||||
|
||||
Scoring (suggestion path, API worker, NO numpy): p = sigmoid(weights · x̂ + bias)
|
||||
where x̂ is the L2-normalized image embedding. Surface as a suggestion when
|
||||
p >= suggest_threshold; auto-apply only once auto_apply_threshold is set (the
|
||||
head "graduated" — a precision-targeted operating point was achievable). The
|
||||
thresholds come from CROSS-VALIDATED out-of-fold scores so they're honest, not
|
||||
in-sample-optimistic; the deployable weights are fit on all data.
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pgvector.sqlalchemy import Vector
|
||||
from sqlalchemy import (
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base
|
||||
|
||||
# Matches image_record.siglip_embedding's dimensionality — the head operates in
|
||||
# the same space. A model-version change re-embeds AND retrains (embedding_version
|
||||
# guards staleness).
|
||||
HEAD_DIM = 1152
|
||||
|
||||
|
||||
class TagHead(Base):
|
||||
__tablename__ = "tag_head"
|
||||
|
||||
# One head per concept tag; cascade so deleting a tag retires its head.
|
||||
tag_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("tag.id", ondelete="CASCADE"), primary_key=True
|
||||
)
|
||||
# The embedding the head was trained against (image_record's
|
||||
# embedder_model_version). A mismatch with the current embedder means the
|
||||
# head is stale and must be retrained, not scored.
|
||||
embedding_version: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# Logistic-regression coefficients over the L2-normalized embedding, stored
|
||||
# as a pgvector for compactness + a future in-DB dot-product path. NOT a
|
||||
# similarity target, just a serialized weight vector.
|
||||
weights: Mapped[list[float]] = mapped_column(Vector(HEAD_DIM), nullable=False)
|
||||
bias: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
# Probability cutoff for SURFACING as a suggestion (F1-best on CV scores).
|
||||
suggest_threshold: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
# Probability cutoff for EARNED auto-apply: the operating point that holds
|
||||
# precision >= the configured target while maximizing recall. NULL = the head
|
||||
# hasn't graduated (can't auto-apply without a human yet).
|
||||
auto_apply_threshold: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
# Training-set sizes + cross-validated quality, surfaced in the admin card so
|
||||
# the operator can see which concepts are strong / need more tags.
|
||||
n_pos: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
n_neg: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
ap: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
# 'precision' is a SQL reserved word → store as precision_cv (the
|
||||
# cross-validated precision at the suggest operating point).
|
||||
precision_cv: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
recall: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
trained_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
# Extra detail (auto-apply operating point, F1, etc.) — non-load-bearing.
|
||||
metrics: Mapped[dict[str, Any] | None] = mapped_column(JSONB, nullable=True)
|
||||
Reference in New Issue
Block a user