Spaces:
Sleeping
Sleeping
Commit Β·
6927844
1
Parent(s): 9f6aaf9
projection-head scaffold for type-aware similarity
Browse files- BucketPairHeads registry, identity-default when no .npz loaded
- _pick_complement uses heads.similarity() instead of raw np.dot
- Plug-in design: drop trained weights at ~/.taste/projection_heads.npz
No training: Vasileva 2018 needs ~10K weak positives we don't have yet.
Scaffold only β eval unchanged with identity fallback.
- .long-run/checkpoints/phase-3-step-7.md +28 -0
- taste/outfits.py +15 -3
- taste/projection_heads.py +136 -0
.long-run/checkpoints/phase-3-step-7.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
step: 7
|
| 3 |
+
title: Type-aware projection heads (Vasileva-style) scaffold
|
| 4 |
+
status: completed
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# Step 7 β `taste/projection_heads.py`
|
| 8 |
+
|
| 9 |
+
## What changed
|
| 10 |
+
|
| 11 |
+
- New module `taste/projection_heads.py`:
|
| 12 |
+
- `BucketPairHeads` registry mapping (a_bucket, b_bucket) β projection ndarray
|
| 13 |
+
- `project()`: identity-default when head is missing
|
| 14 |
+
- `similarity()`: type-aware cosine, drop-in replacement for `np.dot`
|
| 15 |
+
- `from_npz()`: loader for trained weights
|
| 16 |
+
- `get_heads()` / `reset_heads()`: process-wide cached registry, lazy-loaded from `~/.taste/projection_heads.npz`
|
| 17 |
+
- `taste/outfits.py`: `_pick_complement` now takes `anchor_bucket` and uses `heads.similarity(...)` instead of `np.dot(...)` for the visual-sim term. Plumbed `anchor_bucket` through `compose_outfit`.
|
| 18 |
+
|
| 19 |
+
## Why no training?
|
| 20 |
+
|
| 21 |
+
Vasileva 2018 needs β₯10K weak positives (Polyvore-style outfit pairs). We don't have those for the Scandi catalog yet. The scaffold makes it cheap to plug in once we collect them β drop the .npz at the expected path and `get_heads()` picks it up next process start, no code change needed.
|
| 22 |
+
|
| 23 |
+
## Verifier
|
| 24 |
+
|
| 25 |
+
- `python3 -m py_compile` β pass
|
| 26 |
+
- 80-anchor eval re-run with identity-default heads:
|
| 27 |
+
- Scandi 0.760, axes 4.15, distinct 0.188 β within sampling noise of pre-Step-7 (0.752/4.26/0.200)
|
| 28 |
+
- Identity fallback verified β no regression with no .npz present
|
taste/outfits.py
CHANGED
|
@@ -40,6 +40,7 @@ from taste.colors import (
|
|
| 40 |
lab_to_hex,
|
| 41 |
)
|
| 42 |
from taste.contrast import AXES, merge
|
|
|
|
| 43 |
from taste.scandi import bias as scandi_bias
|
| 44 |
|
| 45 |
# Pairing rules: anchor bucket β ordered list of complement buckets to fill.
|
|
@@ -308,12 +309,19 @@ class _OutfitState:
|
|
| 308 |
def _pick_complement(
|
| 309 |
conn,
|
| 310 |
bucket: str,
|
|
|
|
| 311 |
anchor_url: str,
|
| 312 |
state: _OutfitState,
|
| 313 |
used_urls: set[str],
|
| 314 |
embeddings_cache: dict[str, np.ndarray],
|
| 315 |
) -> dict | None:
|
| 316 |
-
"""Pick best in-stock product from `bucket`, scored against partial outfit.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
candidates = _candidate_pool(conn, bucket, anchor_url, _POOL_SIZE)
|
| 318 |
candidates = [c for c in candidates if c["url"] not in used_urls]
|
| 319 |
if not candidates:
|
|
@@ -335,6 +343,7 @@ def _pick_complement(
|
|
| 335 |
|
| 336 |
scores_raw = [float(c["score"]) for c in candidates]
|
| 337 |
centroid = state.anchor_centroid()
|
|
|
|
| 338 |
sims_raw: list[float] = []
|
| 339 |
color_raw: list[float] = []
|
| 340 |
contrast_raw: list[float] = []
|
|
@@ -343,7 +352,8 @@ def _pick_complement(
|
|
| 343 |
for c in candidates:
|
| 344 |
emb = embeddings_cache.get(c["url"])
|
| 345 |
if centroid is not None and emb is not None and emb.size == centroid.size:
|
| 346 |
-
|
|
|
|
| 347 |
else:
|
| 348 |
sims_raw.append(0.5) # neutral when missing
|
| 349 |
|
|
@@ -427,7 +437,9 @@ def compose_outfit(anchor_url: str, conn) -> dict | None:
|
|
| 427 |
total = float(anchor.get("price_nok") or 0)
|
| 428 |
|
| 429 |
for comp_bucket in PAIRING_RULES.get(bucket, []):
|
| 430 |
-
prod = _pick_complement(
|
|
|
|
|
|
|
| 431 |
if not prod:
|
| 432 |
continue
|
| 433 |
pick = prod.pop("_pick", {})
|
|
|
|
| 40 |
lab_to_hex,
|
| 41 |
)
|
| 42 |
from taste.contrast import AXES, merge
|
| 43 |
+
from taste.projection_heads import get_heads
|
| 44 |
from taste.scandi import bias as scandi_bias
|
| 45 |
|
| 46 |
# Pairing rules: anchor bucket β ordered list of complement buckets to fill.
|
|
|
|
| 309 |
def _pick_complement(
|
| 310 |
conn,
|
| 311 |
bucket: str,
|
| 312 |
+
anchor_bucket: str,
|
| 313 |
anchor_url: str,
|
| 314 |
state: _OutfitState,
|
| 315 |
used_urls: set[str],
|
| 316 |
embeddings_cache: dict[str, np.ndarray],
|
| 317 |
) -> dict | None:
|
| 318 |
+
"""Pick best in-stock product from `bucket`, scored against partial outfit.
|
| 319 |
+
|
| 320 |
+
`anchor_bucket` is the bucket the anchor item belongs to. It only affects
|
| 321 |
+
the visual-similarity term: if a Vasileva-style projection head exists
|
| 322 |
+
for the (anchor_bucket, bucket) pair, similarity becomes type-aware;
|
| 323 |
+
otherwise it falls back to plain cosine.
|
| 324 |
+
"""
|
| 325 |
candidates = _candidate_pool(conn, bucket, anchor_url, _POOL_SIZE)
|
| 326 |
candidates = [c for c in candidates if c["url"] not in used_urls]
|
| 327 |
if not candidates:
|
|
|
|
| 343 |
|
| 344 |
scores_raw = [float(c["score"]) for c in candidates]
|
| 345 |
centroid = state.anchor_centroid()
|
| 346 |
+
heads = get_heads()
|
| 347 |
sims_raw: list[float] = []
|
| 348 |
color_raw: list[float] = []
|
| 349 |
contrast_raw: list[float] = []
|
|
|
|
| 352 |
for c in candidates:
|
| 353 |
emb = embeddings_cache.get(c["url"])
|
| 354 |
if centroid is not None and emb is not None and emb.size == centroid.size:
|
| 355 |
+
# Type-aware when heads are loaded; identity-cosine when not.
|
| 356 |
+
sims_raw.append(heads.similarity(centroid, anchor_bucket, emb, bucket))
|
| 357 |
else:
|
| 358 |
sims_raw.append(0.5) # neutral when missing
|
| 359 |
|
|
|
|
| 437 |
total = float(anchor.get("price_nok") or 0)
|
| 438 |
|
| 439 |
for comp_bucket in PAIRING_RULES.get(bucket, []):
|
| 440 |
+
prod = _pick_complement(
|
| 441 |
+
conn, comp_bucket, bucket, anchor_url, state, used_urls, embeddings_cache,
|
| 442 |
+
)
|
| 443 |
if not prod:
|
| 444 |
continue
|
| 445 |
pick = prod.pop("_pick", {})
|
taste/projection_heads.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Type-aware projection heads (Vasileva 2018-style) β registry + identity fallback.
|
| 2 |
+
|
| 3 |
+
The shared FashionSigLIP embedding space treats "dress vs bag" similarity the
|
| 4 |
+
same as "dress vs dress" similarity, but those have very different semantics:
|
| 5 |
+
two dresses being similar means they look alike, while a dress and a bag being
|
| 6 |
+
similar means they pair well together. Vasileva et al. (2018) show that
|
| 7 |
+
training a small projection per (anchor_bucket, candidate_bucket) pair
|
| 8 |
+
materially improves outfit retrieval β the model learns "this kind of dress
|
| 9 |
+
pairs with this kind of bag" instead of cross-type visual confusion.
|
| 10 |
+
|
| 11 |
+
This module is the **plumbing**, not the training. The default registry has
|
| 12 |
+
no heads loaded β cosine similarity stays identity (current behaviour). Once
|
| 13 |
+
heads are trained offline (script TBD), drop the resulting `.npz` at
|
| 14 |
+
`~/.taste/projection_heads.npz` and `_get_heads()` will pick it up on next
|
| 15 |
+
process start. Per-pair lookups fall through to identity if a specific pair
|
| 16 |
+
isn't trained, so partial coverage works.
|
| 17 |
+
|
| 18 |
+
Cost of training: needs β₯10k weak positives (e.g. catalogue lookbook pairs
|
| 19 |
+
or curated outfit datasets like Polyvore). We don't have that yet β this
|
| 20 |
+
scaffold makes it cheap to plug in once we do.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class BucketPairHeads:
|
| 31 |
+
"""Registry of per-(bucket_a, bucket_b) projection matrices.
|
| 32 |
+
|
| 33 |
+
Each head W_{ab} β R^{dΓd} maps an embedding from bucket b's space into
|
| 34 |
+
a shared space where cosine similarity reflects compatibility with bucket a.
|
| 35 |
+
Stored as ndarray, applied as `W @ emb`.
|
| 36 |
+
|
| 37 |
+
Identity-default: when no head is registered for a pair, `project()`
|
| 38 |
+
returns the input unchanged, so similarity falls back to plain cosine
|
| 39 |
+
in the original embedding space.
|
| 40 |
+
|
| 41 |
+
Symmetry: we store (a, b) and (b, a) separately. Outfit similarity
|
| 42 |
+
is symmetrically scored: project both sides and dot. If only one
|
| 43 |
+
direction is loaded, the other side falls back to identity.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, dim: int | None = None):
|
| 47 |
+
self.dim: int | None = dim
|
| 48 |
+
self.heads: dict[tuple[str, str], np.ndarray] = {}
|
| 49 |
+
|
| 50 |
+
def has_head(self, a_bucket: str, b_bucket: str) -> bool:
|
| 51 |
+
return (a_bucket, b_bucket) in self.heads
|
| 52 |
+
|
| 53 |
+
def project(self, emb: np.ndarray, a_bucket: str, b_bucket: str) -> np.ndarray:
|
| 54 |
+
"""Project `emb` (which lives in b_bucket's slot) toward a_bucket's space.
|
| 55 |
+
|
| 56 |
+
Identity-fallback when the head is missing β emb returned unchanged.
|
| 57 |
+
"""
|
| 58 |
+
W = self.heads.get((a_bucket, b_bucket))
|
| 59 |
+
if W is None:
|
| 60 |
+
return emb
|
| 61 |
+
return (W @ emb).astype(np.float32)
|
| 62 |
+
|
| 63 |
+
def similarity(
|
| 64 |
+
self,
|
| 65 |
+
a_emb: np.ndarray,
|
| 66 |
+
a_bucket: str,
|
| 67 |
+
b_emb: np.ndarray,
|
| 68 |
+
b_bucket: str,
|
| 69 |
+
) -> float:
|
| 70 |
+
"""Type-aware cosine similarity between an a-bucket and b-bucket item.
|
| 71 |
+
|
| 72 |
+
If both heads are identity (default), this is the plain dot product
|
| 73 |
+
of the original (already-unit-norm) embeddings β same numbers as the
|
| 74 |
+
previous code path. Once heads are loaded, the relevant pair gets
|
| 75 |
+
type-aware projection on both sides before dotting.
|
| 76 |
+
"""
|
| 77 |
+
a = self.project(a_emb, a_bucket, b_bucket)
|
| 78 |
+
b = self.project(b_emb, b_bucket, a_bucket)
|
| 79 |
+
an = float(np.linalg.norm(a)) + 1e-9
|
| 80 |
+
bn = float(np.linalg.norm(b)) + 1e-9
|
| 81 |
+
return float(np.dot(a, b) / (an * bn))
|
| 82 |
+
|
| 83 |
+
@classmethod
|
| 84 |
+
def from_npz(cls, path: str | Path) -> "BucketPairHeads":
|
| 85 |
+
"""Load heads from a numpy .npz file.
|
| 86 |
+
|
| 87 |
+
Expected key format: ``{a_bucket}__{b_bucket}`` (double underscore).
|
| 88 |
+
Each value is a (d, d) ndarray. Buckets unknown to PAIRING_RULES are
|
| 89 |
+
kept (forward-compat for new categories).
|
| 90 |
+
"""
|
| 91 |
+
data = np.load(str(path))
|
| 92 |
+
out = cls()
|
| 93 |
+
for k in data.files:
|
| 94 |
+
if "__" not in k:
|
| 95 |
+
continue
|
| 96 |
+
a, b = k.split("__", 1)
|
| 97 |
+
arr = data[k]
|
| 98 |
+
if arr.ndim != 2 or arr.shape[0] != arr.shape[1]:
|
| 99 |
+
# malformed entry β skip, don't crash
|
| 100 |
+
continue
|
| 101 |
+
out.heads[(a, b)] = arr.astype(np.float32)
|
| 102 |
+
if out.dim is None:
|
| 103 |
+
out.dim = int(arr.shape[0])
|
| 104 |
+
return out
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
# Process-wide cached registry. Lazily loaded on first request.
|
| 108 |
+
_HEADS: BucketPairHeads | None = None
|
| 109 |
+
_HEADS_PATH = Path.home() / ".taste" / "projection_heads.npz"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_heads() -> BucketPairHeads:
|
| 113 |
+
"""Return the process-wide registry, loading from disk on first call.
|
| 114 |
+
|
| 115 |
+
If the .npz isn't present, an empty (identity-default) registry is
|
| 116 |
+
returned and cached. To force a reload after training, call
|
| 117 |
+
`reset_heads()` (single-process β workers must reload independently).
|
| 118 |
+
"""
|
| 119 |
+
global _HEADS
|
| 120 |
+
if _HEADS is not None:
|
| 121 |
+
return _HEADS
|
| 122 |
+
if _HEADS_PATH.exists():
|
| 123 |
+
try:
|
| 124 |
+
_HEADS = BucketPairHeads.from_npz(_HEADS_PATH)
|
| 125 |
+
except Exception:
|
| 126 |
+
# Corrupt file β fall back to identity rather than crashing the API.
|
| 127 |
+
_HEADS = BucketPairHeads()
|
| 128 |
+
else:
|
| 129 |
+
_HEADS = BucketPairHeads()
|
| 130 |
+
return _HEADS
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def reset_heads() -> None:
|
| 134 |
+
"""Drop the cached registry so `get_heads()` reloads from disk next call."""
|
| 135 |
+
global _HEADS
|
| 136 |
+
_HEADS = None
|