Ypeng12's picture
Publish verified cache speedup, pixel-equivalence checks, UI results and Chinese evaluation
23cdd96 verified
Raw History Blame Contribute Delete
11.2 kB
"""Render a human-readable report from retained measured evidence."""
import json
from pathlib import Path
BASE=Path(__file__).resolve().parent
s=json.loads((BASE/'summary.json').read_text())
f=json.loads((BASE/'frozen_config.json').read_text())
names={'baseline_default':'Original weights, threshold 75','baseline_calibrated':'Original weights, calibrated threshold 44',
'selected_frozen':'Frozen fusion preset, threshold 30','hash_only':'pHash + dHash only','features_only':'Mutual SIFT only',
'ssim_only':'SSIM only','color_only':'Mean CIELAB only'}
rows=[]
for key,m in s['results'].items():
rows.append(f"| {names[key]} | {m['threshold']:g} | {m['precision']:.1%} | {m['recall']:.1%} | {m['f1']:.1%} | {m['false_positive_rate']:.1%} | {m['raw_score_average_precision']:.3f} | {m['raw_score_roc_auc']:.3f} |")
categories=[]
for name,m in s['by_category'].items():
categories.append(f"| {name} | {m['tp']} | {m['fp']} | {m['fn']} | {m['tn']} | {m['f1']:.1%} |")
ci=s['selected_cluster_bootstrap_95pct']['f1']
text=f"""# Visual Product Matching: measured evaluation
Evaluated through the deployed Hugging Face Gradio API on CPU Basic, September 17, 2026 UTC. Classification measurements use revision `{f['source_revision']}`. All 360 pair requests succeeded. This report retains weak results as well as improvements.
## Main finding
The original threshold of 75 was unsuitable for these natural multi-view photos: it found only **1 of 60** held-out positive pairs. Calibration recovered recall, but did not establish a strong product-identity classifier. The frozen fusion preset achieved **53.3% precision, 66.7% recall, and 59.3% F1** on 180 held-out pairs. It produced **40 true positives, 35 false positives, 20 false negatives, and 85 true negatives**.
Changing only the original threshold to its calibration-selected value achieved **58.8% F1**. The additional weight change provided only **0.4 percentage points** on this test; this small difference is not evidence of a reliable fusion advantage. The color-only baseline achieved **65.4% F1**, exceeding the selected fusion. We did not switch to color-only after seeing the test result.
The app offers **Apply evaluated SOP settings** as an optional, explicitly labeled preset. Its weights are perceptual **0.30**, local features **0.50**, SSIM **0.10**, color **0.10**, threshold **30**, and Lowe ratio **0.75**. Original settings remain available. A similarity score is not a probability.
## Dataset and selection
- **120 product/listing IDs, 240 natural photographs, 12 categories, 360 pairs** from a pinned Stanford Online Products mirror.
- Calibration: 60 product IDs, 180 pairs. Held-out test: 60 different product IDs, 180 pairs. Each split has 60 same-product positives, 60 same-category negatives, and 60 cross-category negatives.
- No product-ID overlap across splits and no exact decoded RGB duplicates among the 240 photographs. Five duplicate-photo selections were repaired by deterministic rules before scoring, with an audit trail.
- Selection used source metadata and a fixed seed, never matcher scores. Category coverage: bicycle, cabinet, chair, coffee maker, fan, kettle, lamp, mug, sofa, stapler, table, toaster.
- Source labels indicate SOP listing/product identity, **not verified cross-merchant SKU equivalence**. These categories are not a luxury-handbag benchmark.
See [dataset procedure and limits](evaluation/DATASET.md), [source provenance](evaluation/dataset_provenance.json), [pair manifest](evaluation/pairs.jsonl), and [duplicate audit](evaluation/selection_audit.json). Source photographs are not republished.
## Calibration, baselines, and held-out results
Five fusion profiles were specified before measurements. Each profile's threshold was selected on calibration pairs over 0–100 in steps of 0.5, maximizing F1, then precision and recall. Ties within a profile prefer the higher threshold; profile ties prefer the original profile. Each single-component baseline had its threshold selected independently on the same calibration set. The selected configuration was frozen at **{f['frozen_utc']}**, before test API calls began. No test-driven retuning occurred.
| Configuration | Threshold | Precision | Recall | F1 | False-positive rate | Raw-score AP | Raw-score AUROC |
|---|---:|---:|---:|---:|---:|---:|---:|
{chr(10).join(rows)}
All 180 held-out pairs had sufficient texture; abstentions: **0 positives, 0 negatives**. The protocol treats insufficient-texture decisions as nonmatches for binary metrics. AP, AUROC, and PR curves use ungated raw scores. Single-component results are rescoring ablations; they do **not** measure the speed of running only that component.
![Held-out precision–recall and score distributions](evaluation/vision_evaluation.png)
## Error analysis and uncertainty
The frozen fusion mislabeled **19/60 same-category negatives** and **16/60 cross-category negatives** as matches. It missed **20/60 positive pairs**. Approximate 95% F1 interval: **{ci[0]:.1%}–{ci[1]:.1%}**, from 2,000 bootstrap resamples of anchor-product triplets. This interval is conditional on the frozen configuration; negative partners recur across anchors, so it does not capture all dependence or calibration-selection uncertainty.
Each category below contributes five positive and ten negative anchored pairs; these tiny category slices are descriptive, not rankings of generalization quality.
| Anchor category | TP | FP | FN | TN | F1 |
|---|---:|---:|---:|---:|---:|
{chr(10).join(categories)}
Full error IDs and scores are in [summary.json](evaluation/summary.json). Likely mechanisms to investigate next include view changes without geometric registration, white-background/padding similarity, and the information loss from using mean color. Those are architectural hypotheses, not manually confirmed explanations for every error. The result does not support a claim that weighted fusion consistently beats all component baselines.
## Runtime and operational scope
Across the 180 held-out calls with two client workers, server processing p50/p95 was **{s['latency_ms']['server']['p50']:.1f}/{s['latency_ms']['server']['p95']:.1f} ms**; client p50/p95 was **{s['latency_ms']['client']['p50']:.1f}/{s['latency_ms']['client']['p95']:.1f} ms**. Server timing includes comparison and visual generation; client timing includes input upload, queueing and the Gradio response, with generated artifact downloads disabled. Shared CPU hardware and network variability limit transfer to other deployments.
The optimized implementation adds a 64-image in-memory LRU cache for SIFT keypoints/descriptors; FLANN still runs for every pair. Entries are keyed by normalized grayscale pixels plus the content region and extractor settings. No source photographs are retained by this cache; entries disappear on restart. Feature extraction and FLANN timings and cache-hit diagnostics are exposed separately.
"""
comparison=BASE/'runtime_comparison.json'
if comparison.exists():
r=json.loads(comparison.read_text())
text+=f"""
### Repeated-image performance experiment
Twelve calibration positive pairs, one per category, were run in the same order for three sequential rounds before and after caching. The first pass is reported separately; the headline compares the 24 repeated calls. Settings and source images were identical, and generated-file downloads were disabled.
| Repeated calls (n=24 per revision) | Before cache | After cache |
|---|---:|---:|
| Server p50 | {r['before']['server_ms']['p50']:.2f} ms | {r['after']['server_ms']['p50']:.2f} ms |
| Server p95 | {r['before']['server_ms']['p95']:.2f} ms | {r['after']['server_ms']['p95']:.2f} ms |
| Client p50 | {r['before']['client_ms']['p50']:.2f} ms | {r['after']['client_ms']['p50']:.2f} ms |
Observed server p50 reduction: **{r['server_p50_reduction_pct']:.1f}%**. All **{r['comparisons_verified']} before/after comparisons** retained identical component scores, hash diagnostics, decisions, and correspondence counts. This gain applies to repeated images; it is not a cold-image speedup. Runs were sequential on different deployed revisions, not randomized concurrent A/B trials, so system noise remains a confounder. See [complete comparison](evaluation/runtime_comparison.json) and the first-pass distributions in `runtime_before.summary.json` and `runtime_after.summary.json`.
"""
text+="""
![Server processing and client time on repeated images](evaluation/runtime_evaluation.png)
### Runtime and browser regression checks
An additional live regression suite passed **36/36 checks** across three original demonstration pairs before caching, on first use, on warm reuse, and after eviction. Numerical diagnostics and decoded RGB hashes of both match overlays and SSIM heatmaps stayed identical. Seventy distinct inputs exercised the 64-entry bound; the earliest original image missed again after eviction. Browser tests passed **19/19 checks**, including the evaluated preset and original reset, real comparison payloads, unchanged radar colors, desktop side-by-side images, 1440/390/360 px layouts, and no JavaScript errors. These checks are separate from the labeled accuracy benchmark and timed performance samples.
[Regression evidence and reproduction](evaluation/cache_validation_README.md) · [Cache checks](evaluation/cache_validation_after.json) · [Browser checks](evaluation/ui_validation_results/20260917T021751Z/report.json).
## Reproduce and inspect
Artifacts: [protocol](evaluation/protocol.json), [frozen calibration](evaluation/frozen_config.json), [calibration raw JSONL](evaluation/baseline_calibration.jsonl), [test raw JSONL](evaluation/baseline_test.jsonl), [metric summary](evaluation/summary.json), [runtime benchmark script](evaluation/runtime_benchmark.py).
Clone this Space and use a separate evaluation environment. `evaluation/requirements-eval.txt` records the measured analysis/client versions. Source preparation additionally needs `pyarrow==17.0.0`, `fsspec`, and `aiohttp`. To recompute the published metrics without API calls, run `python evaluation/analyze.py report`. To redownload images, run `python evaluation/prepare_dataset.py`; signed source URLs may require rate-limit backoff.
To repeat a new experiment, use a copy of the evaluation folder and archive its existing outputs/configuration first. Run `benchmark.py --split calibration --output baseline_calibration.jsonl` from that copy with output paths pointing into the evaluation folder, then `analyze.py freeze`, then `benchmark.py --split test --output baseline_test.jsonl`, then `analyze.py report`. Freezing refuses to overwrite an existing decision; test collection verifies the frozen configuration and Space revision. A new revision is a new experiment, not a replacement for the published measurements.
Next accuracy work should use a new development/test split and compare foreground cropping, robust color distributions, geometric verification, or learned image embeddings. The present holdout has already been inspected and must not be reused to advertise new unbiased improvements.
"""
(BASE/'EVALUATION.md').write_text(text)
print(BASE/'EVALUATION.md')