Upload source code (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Start-DefectRAG.cmd +3 -0
- Start-DefectRAG.ps1 +39 -0
- scripts/consolidate_environment.py +117 -0
- scripts/diagnose_encoder.py +146 -0
- scripts/diagnose_rag.py +24 -0
- scripts/download_visa.py +31 -0
- scripts/encoder_banks.py +225 -0
- scripts/encoder_banks_report.py +167 -0
- scripts/encoder_candidates.py +240 -0
- scripts/encoder_candidates_report.py +198 -0
- scripts/encoder_finetune.py +338 -0
- scripts/encoder_finetune_report.py +143 -0
- scripts/encoder_tuned_coreset.py +106 -0
- scripts/encoder_tuned_coreset_report.py +140 -0
- scripts/export_showcase.py +127 -0
- scripts/export_showcase_tuned.py +175 -0
- scripts/fetch_public_assets.py +40 -0
- scripts/mvtec_eval.py +229 -0
- scripts/mvtec_report.py +154 -0
- scripts/package_benchmark.py +41 -0
- scripts/package_release.py +75 -0
- scripts/package_showcase.py +45 -0
- scripts/prepare_assets.py +28 -0
- scripts/prepare_dinov2.py +27 -0
- scripts/prepare_github_export.py +85 -0
- scripts/prepare_knowledge.py +8 -0
- scripts/prepare_macaroni_recall.py +43 -0
- scripts/prepare_sensitive_calibration.py +58 -0
- scripts/profile_inference.py +49 -0
- scripts/qwen_after_training.py +129 -0
- scripts/qwen_build_training_data.py +191 -0
- scripts/qwen_compare.py +46 -0
- scripts/qwen_eval.py +614 -0
- scripts/qwen_finetune.py +181 -0
- scripts/qwen_merge.py +42 -0
- scripts/qwen_serve.py +99 -0
- scripts/qwen_short_questions.py +113 -0
- scripts/space_dry_run.py +62 -0
- scripts/summarize_accuracy.py +46 -0
- scripts/train.py +161 -0
- scripts/train_anomalib.py +46 -0
- scripts/verify_all_categories.py +48 -0
- scripts/verify_assistant_quality.py +37 -0
- scripts/verify_evidence_scope.py +31 -0
- scripts/verify_highres_application.py +62 -0
- scripts/verify_packaged.py +58 -0
- scripts/verify_showcase.py +47 -0
- scripts/verify_startup.py +18 -0
- tests/__init__.py +1 -0
- tests/conftest.py +63 -0
Start-DefectRAG.cmd
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@echo off
|
| 2 |
+
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0Start-DefectRAG.ps1" %*
|
| 3 |
+
pause
|
Start-DefectRAG.ps1
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param([switch]$Setup,[switch]$NoBrowser,[switch]$Verify,[int]$Port=8765,[string]$PythonPath='')
|
| 2 |
+
$ErrorActionPreference='Stop'
|
| 3 |
+
Set-Location $PSScriptRoot
|
| 4 |
+
$env:USE_TF='0'
|
| 5 |
+
$localDeps=Join-Path $PSScriptRoot '.python-deps'
|
| 6 |
+
if (Test-Path -LiteralPath $localDeps) { $env:PYTHONPATH=$localDeps }
|
| 7 |
+
$pythonExe=Join-Path $PSScriptRoot '.venv\Scripts\python.exe'
|
| 8 |
+
if ($PythonPath) { $pythonExe=$PythonPath }
|
| 9 |
+
elseif (-not (Test-Path -LiteralPath $pythonExe)) {
|
| 10 |
+
# No .venv: use DEFECTRAG_PYTHON or the conda env "defectrag" when present.
|
| 11 |
+
. (Join-Path $PSScriptRoot 'deployment\project_python.ps1')
|
| 12 |
+
try { $pythonExe=Get-ProjectPython } catch { }
|
| 13 |
+
}
|
| 14 |
+
if (-not (Test-Path -LiteralPath $pythonExe)) {
|
| 15 |
+
if (-not $Setup) { throw 'First run: .\Start-DefectRAG.ps1 -Setup. This installs dependencies into a separate venv.' }
|
| 16 |
+
& py -3.11 -m venv .venv
|
| 17 |
+
if ($LASTEXITCODE -ne 0) { throw 'Python 3.11 is required for automatic setup. Install Python or pass -PythonPath to an existing compatible environment.' }
|
| 18 |
+
}
|
| 19 |
+
if ($Setup) {
|
| 20 |
+
& $pythonExe -m pip install -r requirements.txt
|
| 21 |
+
if ($LASTEXITCODE -ne 0) { throw 'Dependency setup failed. Check your network and Python version.' }
|
| 22 |
+
}
|
| 23 |
+
if (-not (Test-Path -LiteralPath 'models\encoder\model.safetensors') -and -not (Test-Path -LiteralPath 'models\encoder_dinov2\model.safetensors')) { throw 'Encoder asset missing. See README asset setup.' }
|
| 24 |
+
if (-not (Test-Path -LiteralPath 'frontend\dist\index.html')) {
|
| 25 |
+
& npm.cmd ci --prefix frontend --no-audit --no-fund
|
| 26 |
+
if ($LASTEXITCODE -ne 0) { throw 'Frontend dependency installation failed' }
|
| 27 |
+
& npm.cmd run build --prefix frontend
|
| 28 |
+
if ($LASTEXITCODE -ne 0) { throw 'Frontend build failed' }
|
| 29 |
+
}
|
| 30 |
+
if ($Verify) {
|
| 31 |
+
& $pythonExe -m scripts.verify_startup
|
| 32 |
+
if ($LASTEXITCODE -ne 0) { throw 'Startup validation failed' }
|
| 33 |
+
exit 0
|
| 34 |
+
}
|
| 35 |
+
Write-Host "DefectRAG: http://127.0.0.1:$Port"
|
| 36 |
+
Write-Host 'For generated answers, run Ollama with qwen2.5:3b. Retrieval fallback remains available.'
|
| 37 |
+
if (-not $NoBrowser) { Start-Process "http://127.0.0.1:$Port" }
|
| 38 |
+
& $pythonExe -m uvicorn backend.main:app --host 127.0.0.1 --port $Port
|
| 39 |
+
exit $LASTEXITCODE
|
scripts/consolidate_environment.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Repair an already moved Windows venv, or verify the consolidated local app.
|
| 2 |
+
|
| 3 |
+
No package downloads, model fitting, archive creation or directory deletion.
|
| 4 |
+
Run with the moved .venv/Scripts/python.exe. Moves are handled separately.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import importlib.metadata
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import sqlite3
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import venv
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
sys.path.insert(0, str(ROOT))
|
| 17 |
+
SUPPORT = ROOT / 'development-support'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def save(name, result):
|
| 21 |
+
SUPPORT.mkdir(exist_ok=True)
|
| 22 |
+
(SUPPORT / name).write_text(json.dumps(result, indent=2), encoding='utf-8')
|
| 23 |
+
print(json.dumps(result, indent=2), flush=True)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def repair():
|
| 27 |
+
target = ROOT / '.venv'
|
| 28 |
+
assert Path(sys.prefix).resolve() == target.resolve(), 'Use this project virtual environment'
|
| 29 |
+
assert (ROOT / '.python-deps').is_dir(), 'Local dependency overlay missing'
|
| 30 |
+
site = target / 'Lib/site-packages'
|
| 31 |
+
(site / 'defectrag-local-deps.pth').write_text('../../../.python-deps\n', encoding='utf-8')
|
| 32 |
+
# Refresh activation/configuration without reinstalling packages or copying
|
| 33 |
+
# the running executable. Installed CUDA libraries stay untouched.
|
| 34 |
+
builder = venv.EnvBuilder(with_pip=False)
|
| 35 |
+
context = builder.ensure_directories(str(target))
|
| 36 |
+
builder.create_configuration(context)
|
| 37 |
+
builder.setup_scripts(context)
|
| 38 |
+
from pip._vendor.distlib.scripts import ScriptMaker
|
| 39 |
+
maker = ScriptMaker(None, str(target / 'Scripts'))
|
| 40 |
+
maker.executable = str(target / 'Scripts/python.exe')
|
| 41 |
+
maker.clobber = True
|
| 42 |
+
maker.variants = {''}
|
| 43 |
+
written = set()
|
| 44 |
+
for distribution in importlib.metadata.distributions():
|
| 45 |
+
for entry in distribution.entry_points:
|
| 46 |
+
if entry.group not in ('console_scripts', 'gui_scripts') or entry.name in written:
|
| 47 |
+
continue
|
| 48 |
+
if Path(entry.name).name != entry.name:
|
| 49 |
+
raise ValueError('Unsafe installed entry point')
|
| 50 |
+
maker.make(entry.name + ' = ' + entry.value,
|
| 51 |
+
options={'gui': entry.group == 'gui_scripts'})
|
| 52 |
+
written.add(entry.name)
|
| 53 |
+
for name in ('pip', 'pip3', 'pip3.12'):
|
| 54 |
+
maker.make(name + ' = pip._internal.cli.main:main')
|
| 55 |
+
save('environment-relocation.json', {'status': 'passed', 'python': sys.executable,
|
| 56 |
+
'repaired_console_entry_points': len(written), 'packages_reinstalled': False})
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def verify():
|
| 60 |
+
import torch
|
| 61 |
+
from backend.config import Settings, CATEGORIES
|
| 62 |
+
from backend.main import create_app
|
| 63 |
+
from fastapi.testclient import TestClient
|
| 64 |
+
from backend.vision import sha256
|
| 65 |
+
assert Path(sys.prefix).resolve() == (ROOT / '.venv').resolve()
|
| 66 |
+
for module in ('fastapi', 'uvicorn', 'transformers', 'langchain_core',
|
| 67 |
+
'langchain_community', 'langchain_text_splitters', 'langgraph'):
|
| 68 |
+
__import__(module)
|
| 69 |
+
verified = 0
|
| 70 |
+
for experiment in ('official_visa_v1', 'dinov2_highres_v1'):
|
| 71 |
+
for category in CATEGORIES:
|
| 72 |
+
folder = ROOT / 'experiments' / experiment / category
|
| 73 |
+
receipt = json.loads((folder / 'complete.json').read_text())
|
| 74 |
+
for name, expected in receipt['files'].items():
|
| 75 |
+
assert sha256(folder / name) == expected, str(folder / name)
|
| 76 |
+
verified += 1
|
| 77 |
+
# Private rows must survive consolidation unchanged.
|
| 78 |
+
backup = SUPPORT / 'saved-runtime/desktop-before-highres.sqlite3'
|
| 79 |
+
with sqlite3.connect(backup.as_uri() + '?mode=ro', uri=True) as old:
|
| 80 |
+
with sqlite3.connect((ROOT / 'runtime/inspection.sqlite3').as_uri() + '?mode=ro', uri=True) as current:
|
| 81 |
+
for table in ('inspections', 'messages'):
|
| 82 |
+
rows = set(current.execute('select * from ' + table).fetchall())
|
| 83 |
+
assert all(row in rows for row in old.execute('select * from ' + table))
|
| 84 |
+
app = create_app(Settings(data=ROOT / 'runtime/consolidation-check'))
|
| 85 |
+
with TestClient(app) as client:
|
| 86 |
+
assert client.get('/').status_code == 200
|
| 87 |
+
assert client.get('/api/health').status_code == 200
|
| 88 |
+
sample = ROOT / 'samples/pcb1_anomalous.jpg'
|
| 89 |
+
response = client.post('/api/inspect', data={'category': 'pcb1', 'batch': 'consolidation-check'},
|
| 90 |
+
files={'file': (sample.name, sample.read_bytes(), 'image/jpeg')})
|
| 91 |
+
response.raise_for_status()
|
| 92 |
+
record = response.json()['data']
|
| 93 |
+
assert record['model_id'] == 'dinov2-highres-pcb1-v1'
|
| 94 |
+
assert client.get(record['heatmap_url']).status_code == 200
|
| 95 |
+
answer = client.post('/api/assistant', json={'inspection_id': record['id'],
|
| 96 |
+
'question': 'Is this image anomalous?'})
|
| 97 |
+
answer.raise_for_status()
|
| 98 |
+
assert record['verdict'] in answer.json()['data']['answer']
|
| 99 |
+
for executable in ('pip.exe', 'uvicorn.exe'):
|
| 100 |
+
subprocess.run([str(ROOT / '.venv/Scripts' / executable), '--version'], check=True)
|
| 101 |
+
save('consolidation-verification.json', {'status': 'passed', 'python': sys.executable,
|
| 102 |
+
'torch': torch.__version__, 'cuda': torch.cuda.is_available(),
|
| 103 |
+
'experiment_files_hash_verified': verified, 'complete_experiments': 2,
|
| 104 |
+
'categories_each': 12, 'private_history': 'preserved',
|
| 105 |
+
'real_api_inspection': {key: record[key] for key in ('model_id', 'score', 'verdict', 'device')},
|
| 106 |
+
'assistant': 'passed', 'console_launchers': 'passed', 'packages_reinstalled': False})
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == '__main__':
|
| 110 |
+
parser = argparse.ArgumentParser()
|
| 111 |
+
parser.add_argument('--repair', action='store_true')
|
| 112 |
+
parser.add_argument('--verify', action='store_true')
|
| 113 |
+
args = parser.parse_args()
|
| 114 |
+
if args.repair:
|
| 115 |
+
repair()
|
| 116 |
+
if args.verify:
|
| 117 |
+
verify()
|
scripts/diagnose_encoder.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Where does the frozen DINOv2 detector fail? A read-only diagnostic.
|
| 2 |
+
|
| 3 |
+
python -m scripts.diagnose_encoder
|
| 4 |
+
|
| 5 |
+
It reads only files that already exist: the cached per-image test scores and held-out normal
|
| 6 |
+
calibration scores in experiments/dinov2_highres_v1/<category>/ (thresholds are rebuilt from the
|
| 7 |
+
calibration scores: q95 for every category, plus the deployed q80 for Macaroni1/2), the VisA annotation
|
| 8 |
+
CSV (defect type text) and the VisA masks (defect size).
|
| 9 |
+
No model is loaded, nothing is trained and nothing in the app is changed. Masks are used for
|
| 10 |
+
diagnosis only. Results are written to results/encoder_diagnostic.json.
|
| 11 |
+
|
| 12 |
+
These test images were already seen during development, so the figures are descriptive, not a
|
| 13 |
+
fresh validation.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import csv
|
| 17 |
+
import json
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
from PIL import Image
|
| 21 |
+
|
| 22 |
+
from backend.config import ROOT
|
| 23 |
+
|
| 24 |
+
RUNS = ROOT / "experiments" / "dinov2_highres_v1"
|
| 25 |
+
VISA = ROOT / "VisA_20220922"
|
| 26 |
+
OUT = ROOT / "results" / "encoder_diagnostic.json"
|
| 27 |
+
MIN_GROUP = 8 # below this many anomalous images a rate is too noisy to read
|
| 28 |
+
DEPLOYED_BANK = 3 # bank_3 is the operational bank; banks 0-2 are the benchmark seeds
|
| 29 |
+
DEPLOYED_QUANTILE = {"macaroni1": 0.80, "macaroni2": 0.80} # macaroni-recall-v1 policy; every other category is q95
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def auroc(positive, negative):
|
| 33 |
+
"""Probability that a random anomaly scores higher than a random normal (ties count half)."""
|
| 34 |
+
p, n = np.asarray(positive, float), np.asarray(negative, float)
|
| 35 |
+
if len(p) == 0 or len(n) == 0:
|
| 36 |
+
return None
|
| 37 |
+
greater = (p[:, None] > n[None, :]).sum()
|
| 38 |
+
ties = (p[:, None] == n[None, :]).sum()
|
| 39 |
+
return float((greater + 0.5 * ties) / (len(p) * len(n)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def mask_fraction(path):
|
| 43 |
+
with Image.open(path) as image:
|
| 44 |
+
return float((np.asarray(image.convert("L")) > 0).mean())
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def analyse(category):
|
| 48 |
+
rows = json.loads((RUNS / category / "test_progress.json").read_text(encoding="utf-8"))
|
| 49 |
+
calibration = json.loads((RUNS / category / "normal_calibration.json").read_text(encoding="utf-8"))
|
| 50 |
+
held_out = np.array([p["score"] for p in calibration["predictions"]])
|
| 51 |
+
annotations = {r["image"]: r for r in csv.DictReader((VISA / category / "image_anno.csv").open(encoding="utf-8"))}
|
| 52 |
+
# The cards in models/highres still hold the older "maximum held-out normal" threshold. The deployed
|
| 53 |
+
# thresholds are linear quantiles of the held-out normal scores: q95 everywhere, q80 for Macaroni1/2.
|
| 54 |
+
q95 = float(np.quantile(held_out, 0.95))
|
| 55 |
+
deployed_quantile = DEPLOYED_QUANTILE.get(category, 0.95)
|
| 56 |
+
threshold = float(np.quantile(held_out, deployed_quantile))
|
| 57 |
+
items = []
|
| 58 |
+
for row in rows:
|
| 59 |
+
note = annotations[row["image"]]
|
| 60 |
+
entry = {"label": row["label"], "score": row["scores"][DEPLOYED_BANK], "image": row["image"]}
|
| 61 |
+
if row["label"] == 1:
|
| 62 |
+
entry["types"] = [t.strip() for t in note["label"].split(",") if t.strip()] or ["unlabelled"]
|
| 63 |
+
entry["area"] = mask_fraction(VISA / note["mask"]) if note["mask"] else None
|
| 64 |
+
items.append(entry)
|
| 65 |
+
normal = np.array([i["score"] for i in items if i["label"] == 0])
|
| 66 |
+
anomaly = [i for i in items if i["label"] == 1]
|
| 67 |
+
anomaly_scores = np.array([i["score"] for i in anomaly])
|
| 68 |
+
seeds = [auroc([r["scores"][b] for r in rows if r["label"] == 1], [r["scores"][b] for r in rows if r["label"] == 0])
|
| 69 |
+
for b in range(len(rows[0]["scores"]))]
|
| 70 |
+
result = {
|
| 71 |
+
"deployed_policy": f"q{round(deployed_quantile * 100)}",
|
| 72 |
+
"threshold": threshold,
|
| 73 |
+
"threshold_q95": q95,
|
| 74 |
+
"recall_at_q95": float((anomaly_scores >= q95).mean()),
|
| 75 |
+
"normal_false_alarm_rate_at_q95": float((normal >= q95).mean()),
|
| 76 |
+
"n_normal": int(len(normal)),
|
| 77 |
+
"n_anomaly": int(len(anomaly)),
|
| 78 |
+
"auroc_deployed": auroc(anomaly_scores, normal),
|
| 79 |
+
"auroc_all_banks": [round(s, 4) for s in seeds],
|
| 80 |
+
"recall_at_threshold": float((anomaly_scores >= threshold).mean()),
|
| 81 |
+
"normal_false_alarm_rate": float((normal >= threshold).mean()),
|
| 82 |
+
"normal_score_median": float(np.median(normal)),
|
| 83 |
+
"normal_score_p95": float(np.percentile(normal, 95)),
|
| 84 |
+
"anomaly_score_median": float(np.median(anomaly_scores)),
|
| 85 |
+
}
|
| 86 |
+
by_type = {}
|
| 87 |
+
for name in sorted({t for i in anomaly for t in i["types"]}):
|
| 88 |
+
group = [i["score"] for i in anomaly if name in i["types"]]
|
| 89 |
+
by_type[name] = {
|
| 90 |
+
"n": len(group),
|
| 91 |
+
"detected_at_threshold": float((np.array(group) >= threshold).mean()),
|
| 92 |
+
"auroc_vs_normals": auroc(group, normal),
|
| 93 |
+
}
|
| 94 |
+
result["by_defect_type"] = by_type
|
| 95 |
+
sized = [i for i in anomaly if i.get("area") is not None]
|
| 96 |
+
if len(sized) >= 3 * MIN_GROUP:
|
| 97 |
+
cuts = np.quantile([i["area"] for i in sized], [1 / 3, 2 / 3])
|
| 98 |
+
buckets = {"small": lambda a: a <= cuts[0], "medium": lambda a: cuts[0] < a <= cuts[1], "large": lambda a: a > cuts[1]}
|
| 99 |
+
by_size = {}
|
| 100 |
+
for name, test in buckets.items():
|
| 101 |
+
group = [i for i in sized if test(i["area"])]
|
| 102 |
+
scores = np.array([i["score"] for i in group])
|
| 103 |
+
by_size[name] = {
|
| 104 |
+
"n": len(group),
|
| 105 |
+
"median_mask_area_percent": round(100 * float(np.median([i["area"] for i in group])), 3),
|
| 106 |
+
"detected_at_threshold": float((scores >= threshold).mean()),
|
| 107 |
+
"auroc_vs_normals": auroc(scores, normal),
|
| 108 |
+
}
|
| 109 |
+
result["by_defect_size"] = by_size
|
| 110 |
+
return result
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
categories = sorted(p.name for p in RUNS.iterdir() if (p / "test_progress.json").exists())
|
| 115 |
+
report = {}
|
| 116 |
+
for category in categories:
|
| 117 |
+
report[category] = analyse(category)
|
| 118 |
+
OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 119 |
+
|
| 120 |
+
print("Per category, deployed bank (descriptive, development-exposed test set).")
|
| 121 |
+
print("AUROC does not depend on the threshold. 'q95' columns compare every category on the same policy;")
|
| 122 |
+
print("'deployed' shows the policy the app really uses (q80 for macaroni1/2).\n")
|
| 123 |
+
print(f"{'category':<11}{'AUROC':>7}{'bank spread':>13} | {'q95 recall':>10}{'q95 false':>10} | {'deployed':>8}{'recall':>8}{'false':>7}")
|
| 124 |
+
for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"]):
|
| 125 |
+
spread = max(r["auroc_all_banks"]) - min(r["auroc_all_banks"])
|
| 126 |
+
print(f"{name:<11}{r['auroc_deployed']:>7.3f}{spread:>13.3f} | {r['recall_at_q95']:>10.0%}{r['normal_false_alarm_rate_at_q95']:>10.0%} | "
|
| 127 |
+
f"{r['deployed_policy']:>8}{r['recall_at_threshold']:>8.0%}{r['normal_false_alarm_rate']:>7.0%}")
|
| 128 |
+
print("\nWeakest categories: by defect size (small / medium / large thirds of the anomalous test images)")
|
| 129 |
+
for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"])[:5]:
|
| 130 |
+
size = r.get("by_defect_size")
|
| 131 |
+
if not size:
|
| 132 |
+
continue
|
| 133 |
+
cells = " ".join(f"{k}: AUROC {v['auroc_vs_normals']:.2f}, found {v['detected_at_threshold']:.0%} "
|
| 134 |
+
f"(median {v['median_mask_area_percent']}% of image)" for k, v in size.items())
|
| 135 |
+
print(f" {name:<10}{cells}")
|
| 136 |
+
print(f"\nWeakest categories: by defect type (groups with at least {MIN_GROUP} images)")
|
| 137 |
+
for name, r in sorted(report.items(), key=lambda kv: kv[1]["auroc_deployed"])[:5]:
|
| 138 |
+
print(f" {name}")
|
| 139 |
+
for kind, v in sorted(r["by_defect_type"].items(), key=lambda kv: kv[1]["auroc_vs_normals"]):
|
| 140 |
+
if v["n"] >= MIN_GROUP:
|
| 141 |
+
print(f" {kind[:60]:<60} n={v['n']:<3} AUROC {v['auroc_vs_normals']:.2f} found {v['detected_at_threshold']:.0%}")
|
| 142 |
+
print(f"\nWritten to {OUT.relative_to(ROOT)}. Nothing else was touched.")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
main()
|
scripts/diagnose_rag.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read existing local inspection evidence and capture one raw Qwen response."""
|
| 2 |
+
import json
|
| 3 |
+
import httpx
|
| 4 |
+
from backend.config import ROOT
|
| 5 |
+
from backend.rag import PROMPT
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
with httpx.Client(timeout=100,trust_env=False) as client:
|
| 9 |
+
base='http://127.0.0.1:8766'
|
| 10 |
+
health=client.get(base+'/api/health');health.raise_for_status()
|
| 11 |
+
records=client.get(base+'/api/inspections?category=pcb1').json()['data']
|
| 12 |
+
record=records[-1]
|
| 13 |
+
question='Explain this anomaly score and its limitations.'
|
| 14 |
+
response=client.post(base+'/api/retrieve',json={'question':question+' pcb1 anomaly inspection'})
|
| 15 |
+
response.raise_for_status();evidence=response.json()['data']
|
| 16 |
+
fields={k:record.get(k) for k in ('category','verdict','score','threshold','scope','localization')}
|
| 17 |
+
prompt=PROMPT.format(inspection=json.dumps(fields),history='[]',question=question,evidence=json.dumps(evidence))
|
| 18 |
+
response=client.post('http://127.0.0.1:11434/api/generate',json={'model':'qwen2.5:3b','prompt':prompt,'stream':False,'format':'json','keep_alive':'2m','options':{'temperature':0,'num_predict':450,'num_ctx':4096}})
|
| 19 |
+
response.raise_for_status()
|
| 20 |
+
body=response.json()
|
| 21 |
+
report={'inspection_id':record['id'],'question':question,'evidence':evidence,'raw_response':body}
|
| 22 |
+
(ROOT/'results'/'rag_diagnostic.json').write_text(json.dumps(report,indent=2))
|
| 23 |
+
print(json.dumps({'response':body.get('response'),'done_reason':body.get('done_reason'),'prompt_eval_count':body.get('prompt_eval_count'),'eval_count':body.get('eval_count')},indent=2),flush=True)
|
| 24 |
+
if __name__=='__main__':main()
|
scripts/download_visa.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit opt-in downloader. No download happens during app startup."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import tarfile
|
| 5 |
+
import urllib.request
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
URL='https://amazon-visual-anomaly.s3.us-west-2.amazonaws.com/VisA_20220922.tar'
|
| 9 |
+
EXPECTED='2eb8690c803ab37de0324772964100169ec8ba1fa3f7e94291c9ca673f40f362'
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser()
|
| 12 |
+
parser.add_argument('--destination',type=Path,required=True)
|
| 13 |
+
parser.add_argument('--authorize-download',action='store_true',help='Explicit approval for the multi-GB dataset download')
|
| 14 |
+
args=parser.parse_args()
|
| 15 |
+
if not args.authorize_download: parser.error('Major dataset download requires --authorize-download')
|
| 16 |
+
args.destination.mkdir(parents=True,exist_ok=True)
|
| 17 |
+
archive=args.destination/'VisA_20220922.tar'
|
| 18 |
+
if not archive.exists(): urllib.request.urlretrieve(URL,archive)
|
| 19 |
+
digest=hashlib.sha256()
|
| 20 |
+
with archive.open('rb') as stream:
|
| 21 |
+
for block in iter(lambda:stream.read(1024*1024),b''):digest.update(block)
|
| 22 |
+
if digest.hexdigest()!=EXPECTED: raise RuntimeError('Dataset archive checksum mismatch; extraction refused')
|
| 23 |
+
with tarfile.open(archive) as tar:
|
| 24 |
+
# Python 3.11.8+ provides the data filter; refuse links and traversal explicitly too.
|
| 25 |
+
base=args.destination.resolve()
|
| 26 |
+
for item in tar.getmembers():
|
| 27 |
+
target=(base/item.name).resolve()
|
| 28 |
+
if not target.is_relative_to(base) or item.issym() or item.islnk(): raise ValueError('Unsafe archive member')
|
| 29 |
+
tar.extractall(base,filter='data')
|
| 30 |
+
print('Dataset extracted and checksum verified')
|
| 31 |
+
if __name__=='__main__': main()
|
scripts/encoder_banks.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Smaller banks, rotated banks and a DINOv3 bank (round 3 of the detector study; needs the GPU).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_banks --smoke --categories macaroni2 # quick check
|
| 4 |
+
python -m scripts.encoder_banks # all 12 categories
|
| 5 |
+
|
| 6 |
+
Round 2 (scripts.encoder_candidates) showed that using every normal patch as the memory bank beats the deployed
|
| 7 |
+
32,768-patch sample in all 12 categories, but the full banks total 8.2 GB. This round asks how small a bank can be
|
| 8 |
+
and still keep the gain, and tests two more ideas. Nothing is trained and nothing in the app is changed. Candidates,
|
| 9 |
+
fixed before any result:
|
| 10 |
+
|
| 11 |
+
cap128/256/512 random patches per training image (3/4 foreground, 1/4 other, the deployed recipe scaled up)
|
| 12 |
+
core32k/64k/96k greedy farthest-point coreset of all patches (random 128-d projection, the PatchCore idea)
|
| 13 |
+
rot four rotations (0/90/180/270 degrees) of every training image, 256 random patches each; about
|
| 14 |
+
as many patches as the full bank, so the full bank is its control
|
| 15 |
+
dinov3full the retained DINOv3 ViT-S/16 with a full bank, scored over all patches (no foreground mask)
|
| 16 |
+
base the deployed bank, recomputed to prove the harness matches the app
|
| 17 |
+
|
| 18 |
+
Scores are written to experiments/dinov2_banks/<category>.json; scripts.encoder_candidates_report merges them with the
|
| 19 |
+
round-2 scores. Test images were already seen during development, so results are descriptive.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import json
|
| 24 |
+
import time
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
from PIL import Image
|
| 30 |
+
from transformers import AutoModel
|
| 31 |
+
|
| 32 |
+
from backend.config import CATEGORIES, ROOT
|
| 33 |
+
from backend.highres import HighResolutionEncoder, foreground_mask
|
| 34 |
+
from backend.vision import distances
|
| 35 |
+
from scripts.diagnose_encoder import auroc
|
| 36 |
+
from scripts.encoder_candidates import RUNS, SOURCE, encode, knn_distance, open_image, top_mean
|
| 37 |
+
|
| 38 |
+
OUT = ROOT / "experiments" / "dinov2_banks"
|
| 39 |
+
DINOV3 = ROOT / "models" / "encoder"
|
| 40 |
+
CAPS = (128, 256, 512)
|
| 41 |
+
CORESETS = {"core32k": 32768, "core64k": 65536, "core96k": 98304}
|
| 42 |
+
ROTATION_CAP = 256
|
| 43 |
+
PROJECTION = 128
|
| 44 |
+
ROTATIONS = (None, Image.Transpose.ROTATE_90, Image.Transpose.ROTATE_180, Image.Transpose.ROTATE_270)
|
| 45 |
+
CANDIDATES = ("base", *(f"cap{c}" for c in CAPS), *CORESETS, "rot", "dinov3full")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Dinov3:
|
| 49 |
+
"""The retained DINOv3 ViT-S/16, frozen, with the same short-edge-448 preprocessing as the DINOv2 detector."""
|
| 50 |
+
|
| 51 |
+
def __init__(self, device):
|
| 52 |
+
self.device = device
|
| 53 |
+
self.model = AutoModel.from_pretrained(str(DINOV3), local_files_only=True).eval().to(device).half()
|
| 54 |
+
self.model.requires_grad_(False)
|
| 55 |
+
self.patch = int(self.model.config.patch_size)
|
| 56 |
+
self.skip = 1 + int(self.model.config.num_register_tokens)
|
| 57 |
+
self.mean = torch.tensor([0.485, 0.456, 0.406], device=device, dtype=torch.half)[:, None, None]
|
| 58 |
+
self.std = torch.tensor([0.229, 0.224, 0.225], device=device, dtype=torch.half)[:, None, None]
|
| 59 |
+
|
| 60 |
+
@torch.inference_mode()
|
| 61 |
+
def patches(self, image, resolution=448):
|
| 62 |
+
width, height = image.size
|
| 63 |
+
factor = resolution / min(width, height)
|
| 64 |
+
resized = (int(width * factor), int(height * factor))
|
| 65 |
+
cropped = tuple(v - v % self.patch for v in resized)
|
| 66 |
+
pixels = np.array(image.resize(resized, Image.Resampling.BICUBIC).crop((0, 0, *cropped)), copy=True)
|
| 67 |
+
values = torch.from_numpy(pixels).permute(2, 0, 1).to(self.device, dtype=torch.half) / 255
|
| 68 |
+
out = self.model(pixel_values=((values - self.mean) / self.std)[None]).last_hidden_state[0, self.skip :]
|
| 69 |
+
return F.normalize(out.float(), dim=-1)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def pick(mask, cap, rng):
|
| 73 |
+
"""Random patch indices: 3/4 of the cap from the foreground, 1/4 from the rest (the deployed 48 + 16 recipe)."""
|
| 74 |
+
foreground, other = np.flatnonzero(mask), np.flatnonzero(~mask)
|
| 75 |
+
return np.r_[
|
| 76 |
+
rng.choice(foreground, min(cap * 3 // 4, len(foreground)), replace=False),
|
| 77 |
+
rng.choice(other, min(cap // 4, len(other)), replace=False),
|
| 78 |
+
].astype(int)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@torch.inference_mode()
|
| 82 |
+
def greedy_coreset(points, count, seed):
|
| 83 |
+
"""Farthest-point selection in a random 128-d projection. The first n picks form the n-patch coreset."""
|
| 84 |
+
device = points.device
|
| 85 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 86 |
+
projection = torch.randn(points.shape[1], PROJECTION, device=device, generator=generator) / PROJECTION**0.5
|
| 87 |
+
small = torch.cat([(part.float() @ projection).half() for part in points.split(65536)])
|
| 88 |
+
norms = (small.float() ** 2).sum(1)
|
| 89 |
+
first = torch.randint(len(small), (1,), device=device, generator=generator)[0]
|
| 90 |
+
chosen = torch.empty(count, dtype=torch.long, device=device)
|
| 91 |
+
chosen[0] = first
|
| 92 |
+
nearest = (norms - 2 * (small @ small[first]).float() + norms[first]).clamp_min(0)
|
| 93 |
+
for i in range(1, count):
|
| 94 |
+
index = nearest.argmax()
|
| 95 |
+
chosen[i] = index
|
| 96 |
+
nearest = torch.minimum(nearest, (norms - 2 * (small @ small[index]).float() + norms[index]).clamp_min(0))
|
| 97 |
+
return chosen
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def run_category(category, encoder, smoke):
|
| 101 |
+
run = RUNS / category
|
| 102 |
+
split = json.loads((run / "split.json").read_text(encoding="utf-8"))
|
| 103 |
+
calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8"))
|
| 104 |
+
cached = {r["image"]: r["scores"][3] for r in json.loads((run / "test_progress.json").read_text(encoding="utf-8"))}
|
| 105 |
+
held_names = [p["image"] for p in calibration["predictions"]]
|
| 106 |
+
skip = set(held_names)
|
| 107 |
+
fit_names = [r["image"] for r in split["train"] if r["image"] not in skip]
|
| 108 |
+
test_rows = split["test"]
|
| 109 |
+
if smoke:
|
| 110 |
+
fit_names, held_names = fit_names[:100], held_names[:20]
|
| 111 |
+
test_rows = test_rows[:: max(1, len(test_rows) // 40)]
|
| 112 |
+
names = held_names + [r["image"] for r in test_rows]
|
| 113 |
+
device = encoder.device
|
| 114 |
+
started = time.perf_counter()
|
| 115 |
+
scores = {name: {} for name in names}
|
| 116 |
+
|
| 117 |
+
# DINOv2: encode every training normal and build the sampled, coreset and rotated banks.
|
| 118 |
+
fine, capped, rotated = [], {c: [] for c in CAPS}, []
|
| 119 |
+
for number, name in enumerate(fit_names):
|
| 120 |
+
image = open_image(name)
|
| 121 |
+
for turn, rotation in enumerate(ROTATIONS):
|
| 122 |
+
view = image if rotation is None else image.transpose(rotation)
|
| 123 |
+
tokens, _, grid = encode(encoder, view, 448)
|
| 124 |
+
mask = foreground_mask(tokens, grid)
|
| 125 |
+
normal = F.normalize(tokens, dim=-1).half()
|
| 126 |
+
rng = np.random.default_rng(1000 * number + turn)
|
| 127 |
+
rotated.append(normal[torch.as_tensor(pick(mask, ROTATION_CAP, rng), device=device)])
|
| 128 |
+
if turn == 0:
|
| 129 |
+
fine.append(normal)
|
| 130 |
+
for cap in CAPS:
|
| 131 |
+
capped[cap].append(
|
| 132 |
+
normal[torch.as_tensor(pick(mask, cap, np.random.default_rng(number + cap)), device=device)]
|
| 133 |
+
)
|
| 134 |
+
banks = {f"cap{c}": torch.cat(parts) for c, parts in capped.items()}
|
| 135 |
+
banks["rot"] = torch.cat(rotated)
|
| 136 |
+
everything = torch.cat(fine)
|
| 137 |
+
del fine, capped, rotated
|
| 138 |
+
coreset = greedy_coreset(everything, max(CORESETS.values()), seed=42)
|
| 139 |
+
for label, size in CORESETS.items():
|
| 140 |
+
banks[label] = everything[coreset[:size]].clone()
|
| 141 |
+
sizes = {label: len(bank) for label, bank in banks.items()}
|
| 142 |
+
sizes["all_patches"] = len(everything)
|
| 143 |
+
del everything
|
| 144 |
+
with np.load(run / "bank_3.npz") as saved:
|
| 145 |
+
base_bank = F.normalize(torch.from_numpy(saved["patches"].astype("float32")).to(device), dim=-1)
|
| 146 |
+
sizes["base"] = len(base_bank)
|
| 147 |
+
fit_seconds = time.perf_counter() - started
|
| 148 |
+
|
| 149 |
+
for name in names:
|
| 150 |
+
tokens, _, grid = encode(encoder, open_image(name), 448)
|
| 151 |
+
mask = torch.as_tensor(foreground_mask(tokens, grid), device=device)
|
| 152 |
+
normal = F.normalize(tokens, dim=-1)
|
| 153 |
+
scores[name]["base"] = top_mean(distances(normal, base_bank), mask)
|
| 154 |
+
for label, bank in banks.items():
|
| 155 |
+
scores[name][label] = top_mean(knn_distance(normal, bank), mask)
|
| 156 |
+
del banks, base_bank
|
| 157 |
+
torch.cuda.empty_cache()
|
| 158 |
+
|
| 159 |
+
# DINOv3: a full bank, scored over all patches.
|
| 160 |
+
third = Dinov3(device)
|
| 161 |
+
bank = torch.cat([third.patches(open_image(n)).half() for n in fit_names])
|
| 162 |
+
sizes["dinov3full"] = len(bank)
|
| 163 |
+
for name in names:
|
| 164 |
+
patches = third.patches(open_image(name))
|
| 165 |
+
everywhere = torch.ones(len(patches), dtype=torch.bool, device=device)
|
| 166 |
+
scores[name]["dinov3full"] = top_mean(knn_distance(patches, bank), everywhere)
|
| 167 |
+
del bank, third
|
| 168 |
+
torch.cuda.empty_cache()
|
| 169 |
+
|
| 170 |
+
differences = [abs(scores[r["image"]]["base"] - cached[r["image"]]) for r in test_rows]
|
| 171 |
+
return {
|
| 172 |
+
"category": category,
|
| 173 |
+
"smoke": smoke,
|
| 174 |
+
"n_fit": len(fit_names),
|
| 175 |
+
"bank_patches": sizes,
|
| 176 |
+
"reproduction": {
|
| 177 |
+
"test_max_abs_difference": max(differences),
|
| 178 |
+
"test_mean_abs_difference": float(np.mean(differences)),
|
| 179 |
+
},
|
| 180 |
+
"seconds_fit": round(fit_seconds, 1),
|
| 181 |
+
"seconds_total": round(time.perf_counter() - started, 1),
|
| 182 |
+
"heldout": {n: scores[n] for n in held_names},
|
| 183 |
+
"test": {r["image"]: scores[r["image"]] for r in test_rows},
|
| 184 |
+
"labels": {r["image"]: 0 if r["label"] == "normal" else 1 for r in test_rows},
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def summarise(record):
|
| 189 |
+
labels = record["labels"]
|
| 190 |
+
positive = [n for n, v in labels.items() if v == 1]
|
| 191 |
+
negative = [n for n, v in labels.items() if v == 0]
|
| 192 |
+
return " ".join(
|
| 193 |
+
f"{c} {auroc([record['test'][n][c] for n in positive], [record['test'][n][c] for n in negative]):.3f}"
|
| 194 |
+
for c in CANDIDATES
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main():
|
| 199 |
+
parser = argparse.ArgumentParser()
|
| 200 |
+
parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES))
|
| 201 |
+
parser.add_argument("--smoke", action="store_true", help="100 fit images, 20 held-out, about 40 test images")
|
| 202 |
+
parser.add_argument("--force", action="store_true", help="recompute categories that already have a result file")
|
| 203 |
+
args = parser.parse_args()
|
| 204 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
encoder = HighResolutionEncoder(SOURCE)
|
| 206 |
+
for category in args.categories:
|
| 207 |
+
target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json")
|
| 208 |
+
if target.exists() and not args.force:
|
| 209 |
+
print(f"{category}: already done ({target.name})", flush=True)
|
| 210 |
+
continue
|
| 211 |
+
record = run_category(category, encoder, args.smoke)
|
| 212 |
+
torch.cuda.empty_cache()
|
| 213 |
+
target.write_text(json.dumps(record), encoding="utf-8")
|
| 214 |
+
rep = record["reproduction"]
|
| 215 |
+
print(
|
| 216 |
+
f"{category}: {record['seconds_total']} s (fit {record['seconds_fit']} s) | reproduces the app: "
|
| 217 |
+
f"max diff {rep['test_max_abs_difference']:.4f}",
|
| 218 |
+
flush=True,
|
| 219 |
+
)
|
| 220 |
+
print(" bank patches " + " ".join(f"{k}={v:,}" for k, v in record["bank_patches"].items()), flush=True)
|
| 221 |
+
print(" AUROC " + summarise(record), flush=True)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if __name__ == "__main__":
|
| 225 |
+
main()
|
scripts/encoder_banks_report.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Report for round 3 (CPU only; run scripts.encoder_banks first).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_banks_report
|
| 4 |
+
|
| 5 |
+
Merges the round-3 scores (experiments/dinov2_banks) with the round-2 scores (experiments/dinov2_candidates) and uses
|
| 6 |
+
the same rules as scripts.encoder_candidates_report: scores standardised with the 90 held-out normals only, paired
|
| 7 |
+
bootstrap 95% intervals of the AUROC difference, thresholds from held-out normals only. The one fusion is fixed
|
| 8 |
+
here, before any result: the full DINOv2 bank averaged with the DINOv3 full bank. Descriptive only, because the test
|
| 9 |
+
images were already seen during development.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from backend.config import ROOT
|
| 17 |
+
from scripts.diagnose_encoder import auroc
|
| 18 |
+
from scripts.encoder_candidates_report import (
|
| 19 |
+
DEPLOYED_QUANTILE,
|
| 20 |
+
HARD_TYPES,
|
| 21 |
+
RESULTS,
|
| 22 |
+
anomaly_types,
|
| 23 |
+
bootstrap_difference,
|
| 24 |
+
standardised,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
BANKS = ROOT / "experiments" / "dinov2_banks"
|
| 28 |
+
OUT = ROOT / "results" / "encoder_banks.json"
|
| 29 |
+
SIZES = ("base", "cap128", "cap256", "cap512", "core32k", "core64k", "core96k", "full")
|
| 30 |
+
OTHERS = ("base", "full", "rot", "dinov3full", "full+dinov3full")
|
| 31 |
+
FUSION = {"full+dinov3full": ("full", "dinov3full")}
|
| 32 |
+
WEAK = ("macaroni1", "macaroni2", "pcb2")
|
| 33 |
+
BYTES_PER_PATCH = 384 * 2 # half precision
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def load():
|
| 37 |
+
merged = {}
|
| 38 |
+
for path in sorted(BANKS.glob("*.json")):
|
| 39 |
+
if ".smoke" in path.name:
|
| 40 |
+
continue
|
| 41 |
+
banks = json.loads(path.read_text(encoding="utf-8"))
|
| 42 |
+
earlier = json.loads((RESULTS / path.name).read_text(encoding="utf-8"))
|
| 43 |
+
for split in ("heldout", "test"):
|
| 44 |
+
for name, scores in banks[split].items():
|
| 45 |
+
earlier[split][name].update(scores)
|
| 46 |
+
earlier["bank_patches"].update(banks["bank_patches"])
|
| 47 |
+
earlier["bank_patches"]["all_patches"] = banks["bank_patches"]["all_patches"]
|
| 48 |
+
earlier["reproduction_round3"] = banks["reproduction"]["test_max_abs_difference"]
|
| 49 |
+
merged[path.stem] = earlier
|
| 50 |
+
return merged
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
rng = np.random.default_rng(2027)
|
| 55 |
+
records = load()
|
| 56 |
+
categories = list(records)
|
| 57 |
+
methods = [m for m in dict.fromkeys(SIZES + OTHERS) if m != "base"]
|
| 58 |
+
report = {}
|
| 59 |
+
for category, record in records.items():
|
| 60 |
+
names = sorted(record["test"])
|
| 61 |
+
labels = np.array([record["labels"][n] for n in names])
|
| 62 |
+
_, base_test = standardised(record, ("base",))
|
| 63 |
+
_, full_test = standardised(record, ("full",))
|
| 64 |
+
entry = {}
|
| 65 |
+
for name in ["base"] + methods:
|
| 66 |
+
got = standardised(record, FUSION.get(name, (name,)))
|
| 67 |
+
if got is None:
|
| 68 |
+
continue
|
| 69 |
+
held, test = got
|
| 70 |
+
result = {
|
| 71 |
+
"auroc": auroc(test[labels == 1], test[labels == 0]),
|
| 72 |
+
"vs_base": None if name == "base" else bootstrap_difference(labels, test, base_test, rng).tolist(),
|
| 73 |
+
"vs_full": None
|
| 74 |
+
if name in ("base", "full")
|
| 75 |
+
else bootstrap_difference(labels, test, full_test, rng).tolist(),
|
| 76 |
+
}
|
| 77 |
+
for label, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))):
|
| 78 |
+
threshold = np.quantile(held, quantile)
|
| 79 |
+
result[f"recall_{label}"] = float((test[labels == 1] >= threshold).mean())
|
| 80 |
+
result[f"false_alarm_{label}"] = float((test[labels == 0] >= threshold).mean())
|
| 81 |
+
if category in HARD_TYPES:
|
| 82 |
+
kinds = anomaly_types(category, names)
|
| 83 |
+
hard = np.array([HARD_TYPES[category] in kinds[n] for n in names])
|
| 84 |
+
result["auroc_hard_type"] = auroc(test[hard & (labels == 1)], test[labels == 0])
|
| 85 |
+
entry[name] = result
|
| 86 |
+
report[category] = entry
|
| 87 |
+
OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 88 |
+
print(
|
| 89 |
+
f"Categories analysed: {len(categories)} (round-3 harness reproduces the app within "
|
| 90 |
+
f"{max(r['reproduction_round3'] for r in records.values()):.5f})\n"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def mark(m, key):
|
| 94 |
+
interval = m.get(key)
|
| 95 |
+
if not interval:
|
| 96 |
+
return " "
|
| 97 |
+
return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " "
|
| 98 |
+
|
| 99 |
+
def table(columns, key, title):
|
| 100 |
+
print(title)
|
| 101 |
+
print(f"{'category':<11}" + "".join(f"{c:>17}" for c in columns))
|
| 102 |
+
for category in categories:
|
| 103 |
+
cells = []
|
| 104 |
+
for c in columns:
|
| 105 |
+
m = report[category].get(c)
|
| 106 |
+
cells.append(f"{'n/a':>17}" if m is None else f"{m['auroc']:>15.3f}{mark(m, key)}")
|
| 107 |
+
print(f"{category:<11}" + "".join(cells))
|
| 108 |
+
means = []
|
| 109 |
+
for c in columns:
|
| 110 |
+
values = [report[k][c]["auroc"] for k in categories if c in report[k]]
|
| 111 |
+
means.append(f"{np.mean(values):>17.3f}" if len(values) == len(categories) else f"{'n/a':>17}")
|
| 112 |
+
print(f"{'MEAN':<11}" + "".join(means) + "\n")
|
| 113 |
+
|
| 114 |
+
table(SIZES, "vs_base", "Bank size: AUROC (▲/▼ = clearly better/worse than the deployed bank)")
|
| 115 |
+
|
| 116 |
+
print("Bank size summary")
|
| 117 |
+
print(
|
| 118 |
+
f"{'bank':<10}{'patches/cat':>13}{'MB (analysed)':>15}{'mean AUROC':>12}{'gain kept':>11}{'weak 3':>8}{'worse than full':>17}"
|
| 119 |
+
)
|
| 120 |
+
base_mean = np.mean([report[k]["base"]["auroc"] for k in categories])
|
| 121 |
+
full_mean = np.mean([report[k]["full"]["auroc"] for k in categories])
|
| 122 |
+
for name in SIZES:
|
| 123 |
+
sizes = [record["bank_patches"][name] for record in records.values()]
|
| 124 |
+
mean = np.mean([report[k][name]["auroc"] for k in categories])
|
| 125 |
+
weak_values = [report[k][name]["auroc"] for k in WEAK if k in report]
|
| 126 |
+
weak = np.mean(weak_values) if weak_values else float("nan")
|
| 127 |
+
worse = sum(1 for k in categories if mark(report[k][name], "vs_full") == " ▼")
|
| 128 |
+
kept = (mean - base_mean) / (full_mean - base_mean)
|
| 129 |
+
print(
|
| 130 |
+
f"{name:<10}{np.mean(sizes):>13,.0f}{sum(sizes) * BYTES_PER_PATCH / 1e6:>15,.0f}{mean:>12.3f}{kept:>11.0%}{weak:>8.3f}{worse:>17}"
|
| 131 |
+
)
|
| 132 |
+
print()
|
| 133 |
+
|
| 134 |
+
table(OTHERS, "vs_full", "Rotation and DINOv3: AUROC (▲/▼ = clearly better/worse than the FULL bank)")
|
| 135 |
+
|
| 136 |
+
cols = ("base", "full", "cap512", "core64k", "core96k", "rot", "dinov3full")
|
| 137 |
+
print("Hard defect types (AUROC of that type against all normals)")
|
| 138 |
+
print(f"{'category / type':<40}" + "".join(f"{c:>12}" for c in cols))
|
| 139 |
+
for category, kind in HARD_TYPES.items():
|
| 140 |
+
if category in report:
|
| 141 |
+
values = [report[category].get(c, {}).get("auroc_hard_type") for c in cols]
|
| 142 |
+
print(
|
| 143 |
+
f"{category + ' / ' + kind:<40}"
|
| 144 |
+
+ "".join(f"{'n/a':>12}" if v is None else f"{v:>12.3f}" for v in values)
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
affordable = [m for m in SIZES if m not in ("base", "full")]
|
| 148 |
+
best = max(affordable, key=lambda m: np.mean([report[k][m]["auroc"] for k in categories]))
|
| 149 |
+
print(
|
| 150 |
+
f"\nOperating points, q95 for every category (best affordable bank by mean AUROC: {best}); "
|
| 151 |
+
"deployed = q80 for macaroni1/2"
|
| 152 |
+
)
|
| 153 |
+
print(
|
| 154 |
+
f"{'category':<11}{'method':<10}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}"
|
| 155 |
+
)
|
| 156 |
+
for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report):
|
| 157 |
+
for name in ("base", best, "full"):
|
| 158 |
+
m = report[category][name]
|
| 159 |
+
print(
|
| 160 |
+
f"{category:<11}{name:<10}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}"
|
| 161 |
+
f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}"
|
| 162 |
+
)
|
| 163 |
+
print("\nWritten to results/encoder_banks.json. Descriptive only (test images already seen in development).")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
main()
|
scripts/encoder_candidates.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score extra detector candidates on the frozen DINOv2 features (step 1 of 2: needs the GPU).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_candidates --smoke --categories macaroni2 # quick check, about a minute
|
| 4 |
+
python -m scripts.encoder_candidates # all 12 categories
|
| 5 |
+
|
| 6 |
+
Nothing is trained and nothing in the app is changed. For each category it encodes the official VisA training normals
|
| 7 |
+
(the 810 used to fit the deployed bank), the 90 held-out normals and the 200 official test images, and records one
|
| 8 |
+
score per image for each candidate. Step 2 (scripts.encoder_candidates_report, CPU only) compares them.
|
| 9 |
+
|
| 10 |
+
Candidates (all fixed before looking at any result; the same top-1% foreground rule as the app):
|
| 11 |
+
base the deployed bank (32,768 sampled patches), recomputed here to prove the harness matches the app
|
| 12 |
+
full every patch of every fit normal as the bank (no sampling)
|
| 13 |
+
fullfg only the foreground patches of every fit normal
|
| 14 |
+
pos position-aware: nearest normal patch at the same place, within one patch of shift (aligned objects)
|
| 15 |
+
cls image-level distance between class tokens (global view)
|
| 16 |
+
meanpool image-level distance between mean foreground patch features
|
| 17 |
+
coarse the same idea at half the resolution (short edge 224) with a full bank (wider context)
|
| 18 |
+
|
| 19 |
+
Masks and defect labels are never read here. Test images were already seen during development, so results are
|
| 20 |
+
descriptive, not a fresh validation.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import json
|
| 25 |
+
import math
|
| 26 |
+
import time
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import torch
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from PIL import Image
|
| 32 |
+
|
| 33 |
+
from backend.config import CATEGORIES, ROOT
|
| 34 |
+
from backend.highres import HighResolutionEncoder, foreground_mask
|
| 35 |
+
from backend.vision import distances
|
| 36 |
+
from scripts.diagnose_encoder import auroc
|
| 37 |
+
|
| 38 |
+
RUNS = ROOT / "experiments" / "dinov2_highres_v1"
|
| 39 |
+
OUT = ROOT / "experiments" / "dinov2_candidates"
|
| 40 |
+
VISA = ROOT / "VisA_20220922"
|
| 41 |
+
SOURCE = ROOT / "models" / "encoder_dinov2"
|
| 42 |
+
OFFSETS = [(dy, dx) for dy in (-1, 0, 1) for dx in (-1, 0, 1)]
|
| 43 |
+
CANDIDATES = ("base", "full", "fullfg", "pos", "cls", "meanpool", "coarse")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@torch.inference_mode()
|
| 47 |
+
def encode(encoder, image, resolution):
|
| 48 |
+
"""Same preprocessing as HighResolutionEncoder.encode, but also returns the class token."""
|
| 49 |
+
width, height = image.size
|
| 50 |
+
factor = resolution / min(width, height)
|
| 51 |
+
resized = (int(width * factor), int(height * factor))
|
| 52 |
+
cropped = tuple(v - v % encoder.patch_size for v in resized)
|
| 53 |
+
pixels = np.array(image.resize(resized, Image.Resampling.BICUBIC).crop((0, 0, *cropped)), copy=True)
|
| 54 |
+
values = torch.from_numpy(pixels).permute(2, 0, 1).to(encoder.device, dtype=encoder.dtype) / 255
|
| 55 |
+
out = encoder.model(pixel_values=((values - encoder.mean) / encoder.std)[None]).last_hidden_state[0].float()
|
| 56 |
+
grid = (cropped[1] // encoder.patch_size, cropped[0] // encoder.patch_size)
|
| 57 |
+
return out[1:], out[0], grid
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def top_mean(distance, mask):
|
| 61 |
+
"""Mean of the largest 1% of foreground patch distances (the app's image score)."""
|
| 62 |
+
selected = distance[mask]
|
| 63 |
+
return float(selected.topk(max(1, math.ceil(len(selected) * 0.01))).values.mean())
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def knn_distance(patches, bank, chunk=32768):
|
| 67 |
+
"""1 - highest cosine similarity to any bank patch; the bank is stored in half precision."""
|
| 68 |
+
best = torch.full((len(patches),), -1.0, device=patches.device)
|
| 69 |
+
for part in bank.split(chunk):
|
| 70 |
+
best = torch.maximum(best, (patches @ part.float().T).amax(dim=1))
|
| 71 |
+
return (1 - best).clamp_min(0)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def positional_distance(patches, stack, grid):
|
| 75 |
+
"""Nearest normal patch at the same grid position or one step away; stack is [positions, images, features]."""
|
| 76 |
+
height, width = grid
|
| 77 |
+
device = patches.device
|
| 78 |
+
ys = torch.arange(height, device=device).repeat_interleave(width)
|
| 79 |
+
xs = torch.arange(width, device=device).repeat(height)
|
| 80 |
+
query = patches.half()[:, :, None]
|
| 81 |
+
best = torch.full((len(patches),), -1.0, device=device)
|
| 82 |
+
for dy, dx in OFFSETS:
|
| 83 |
+
y2, x2 = ys + dy, xs + dx
|
| 84 |
+
valid = (y2 >= 0) & (y2 < height) & (x2 >= 0) & (x2 < width)
|
| 85 |
+
index = y2.clamp(0, height - 1) * width + x2.clamp(0, width - 1)
|
| 86 |
+
similarity = torch.bmm(stack[index], query).squeeze(-1).amax(dim=1).float()
|
| 87 |
+
best = torch.where(valid, torch.maximum(best, similarity), best)
|
| 88 |
+
return (1 - best).clamp_min(0)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def open_image(relative):
|
| 92 |
+
return Image.open(VISA / relative).convert("RGB")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def run_category(category, encoder, smoke):
|
| 96 |
+
run = RUNS / category
|
| 97 |
+
split = json.loads((run / "split.json").read_text(encoding="utf-8"))
|
| 98 |
+
calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8"))
|
| 99 |
+
cached = {r["image"]: r["scores"][3] for r in json.loads((run / "test_progress.json").read_text(encoding="utf-8"))}
|
| 100 |
+
held_names = [p["image"] for p in calibration["predictions"]]
|
| 101 |
+
held_saved = {p["image"]: p["score"] for p in calibration["predictions"]}
|
| 102 |
+
skip = set(held_names)
|
| 103 |
+
fit_names = [r["image"] for r in split["train"] if r["image"] not in skip]
|
| 104 |
+
test_rows = split["test"]
|
| 105 |
+
if smoke:
|
| 106 |
+
fit_names = fit_names[:100]
|
| 107 |
+
held_names = held_names[:20]
|
| 108 |
+
test_rows = test_rows[:: max(1, len(test_rows) // 40)]
|
| 109 |
+
device = encoder.device
|
| 110 |
+
started = time.perf_counter()
|
| 111 |
+
|
| 112 |
+
# Fit: encode every training normal at both scales and keep the features on the GPU.
|
| 113 |
+
fine, fine_fg, coarse, cls_rows, mean_rows, same_grid = [], [], [], [], [], []
|
| 114 |
+
pos_grid = None
|
| 115 |
+
for name in fit_names:
|
| 116 |
+
image = open_image(name)
|
| 117 |
+
tokens, cls_token, grid = encode(encoder, image, 448)
|
| 118 |
+
mask = torch.as_tensor(foreground_mask(tokens, grid), device=device)
|
| 119 |
+
normal = F.normalize(tokens, dim=-1)
|
| 120 |
+
pos_grid = pos_grid or grid
|
| 121 |
+
fine.append(normal.half())
|
| 122 |
+
fine_fg.append(normal[mask].half())
|
| 123 |
+
cls_rows.append(F.normalize(cls_token, dim=-1))
|
| 124 |
+
mean_rows.append(F.normalize(normal[mask].mean(0) if mask.any() else normal.mean(0), dim=-1))
|
| 125 |
+
if grid == pos_grid:
|
| 126 |
+
same_grid.append(len(fine) - 1)
|
| 127 |
+
small, _, _ = encode(encoder, image, 224)
|
| 128 |
+
coarse.append(F.normalize(small, dim=-1).half())
|
| 129 |
+
full_bank = torch.cat(fine)
|
| 130 |
+
fullfg_bank = torch.cat(fine_fg)
|
| 131 |
+
coarse_bank = torch.cat(coarse)
|
| 132 |
+
stack = torch.stack([fine[i] for i in same_grid]).permute(1, 0, 2).contiguous()
|
| 133 |
+
cls_bank, mean_bank = torch.stack(cls_rows), torch.stack(mean_rows)
|
| 134 |
+
del fine, fine_fg, coarse
|
| 135 |
+
with np.load(run / "bank_3.npz") as saved:
|
| 136 |
+
base_bank = F.normalize(torch.from_numpy(saved["patches"].astype("float32")).to(device), dim=-1)
|
| 137 |
+
fit_seconds = time.perf_counter() - started
|
| 138 |
+
|
| 139 |
+
def score(name):
|
| 140 |
+
image = open_image(name)
|
| 141 |
+
tokens, cls_token, grid = encode(encoder, image, 448)
|
| 142 |
+
mask_np = foreground_mask(tokens, grid)
|
| 143 |
+
mask = torch.as_tensor(mask_np, device=device)
|
| 144 |
+
normal = F.normalize(tokens, dim=-1)
|
| 145 |
+
out = {
|
| 146 |
+
"base": top_mean(distances(normal, base_bank), mask),
|
| 147 |
+
"full": top_mean(knn_distance(normal, full_bank), mask),
|
| 148 |
+
"fullfg": top_mean(knn_distance(normal, fullfg_bank), mask),
|
| 149 |
+
"pos": top_mean(positional_distance(normal, stack, grid), mask) if grid == pos_grid else None,
|
| 150 |
+
"cls": float(1 - (cls_bank @ F.normalize(cls_token, dim=-1)).max()),
|
| 151 |
+
"meanpool": float(1 - (mean_bank @ F.normalize(normal[mask].mean(0), dim=-1)).max())
|
| 152 |
+
if mask.any()
|
| 153 |
+
else None,
|
| 154 |
+
}
|
| 155 |
+
small, _, small_grid = encode(encoder, image, 224)
|
| 156 |
+
small_mask = torch.as_tensor(foreground_mask(small, small_grid), device=device)
|
| 157 |
+
out["coarse"] = top_mean(knn_distance(F.normalize(small, dim=-1), coarse_bank), small_mask)
|
| 158 |
+
return out
|
| 159 |
+
|
| 160 |
+
held = {name: score(name) for name in held_names}
|
| 161 |
+
test = {row["image"]: score(row["image"]) for row in test_rows}
|
| 162 |
+
labels = {row["image"]: 0 if row["label"] == "normal" else 1 for row in test_rows}
|
| 163 |
+
differences = [abs(test[n]["base"] - cached[n]) for n in test]
|
| 164 |
+
held_differences = [abs(held[n]["base"] - held_saved[n]) for n in held]
|
| 165 |
+
record = {
|
| 166 |
+
"category": category,
|
| 167 |
+
"smoke": smoke,
|
| 168 |
+
"n_fit": len(fit_names),
|
| 169 |
+
"n_position_images": len(same_grid),
|
| 170 |
+
"grid": list(pos_grid),
|
| 171 |
+
"bank_patches": {
|
| 172 |
+
"base": len(base_bank),
|
| 173 |
+
"full": len(full_bank),
|
| 174 |
+
"fullfg": len(fullfg_bank),
|
| 175 |
+
"coarse": len(coarse_bank),
|
| 176 |
+
},
|
| 177 |
+
"reproduction": {
|
| 178 |
+
"test_max_abs_difference": max(differences),
|
| 179 |
+
"test_mean_abs_difference": float(np.mean(differences)),
|
| 180 |
+
"heldout_max_abs_difference": max(held_differences),
|
| 181 |
+
},
|
| 182 |
+
"seconds_fit": round(fit_seconds, 1),
|
| 183 |
+
"seconds_total": round(time.perf_counter() - started, 1),
|
| 184 |
+
"heldout": held,
|
| 185 |
+
"test": test,
|
| 186 |
+
"labels": labels,
|
| 187 |
+
}
|
| 188 |
+
return record
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def summarise(record):
|
| 192 |
+
labels = record["labels"]
|
| 193 |
+
positive = [n for n, v in labels.items() if v == 1]
|
| 194 |
+
negative = [n for n, v in labels.items() if v == 0]
|
| 195 |
+
parts = []
|
| 196 |
+
for name in CANDIDATES:
|
| 197 |
+
if any(record["test"][n][name] is None for n in labels):
|
| 198 |
+
parts.append(f"{name} n/a")
|
| 199 |
+
continue
|
| 200 |
+
value = auroc([record["test"][n][name] for n in positive], [record["test"][n][name] for n in negative])
|
| 201 |
+
parts.append(f"{name} {value:.3f}")
|
| 202 |
+
return " ".join(parts)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main():
|
| 206 |
+
parser = argparse.ArgumentParser()
|
| 207 |
+
parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES))
|
| 208 |
+
parser.add_argument("--smoke", action="store_true", help="100 fit images, 20 held-out, about 40 test images")
|
| 209 |
+
parser.add_argument("--force", action="store_true", help="recompute categories that already have a result file")
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--weights", help="round 4: a fine-tuned encoder state dict; results go to dinov2_candidates_ft"
|
| 212 |
+
)
|
| 213 |
+
parser.add_argument("--tag", default="ft", help="with --weights: results go to dinov2_candidates_<tag>")
|
| 214 |
+
args = parser.parse_args()
|
| 215 |
+
out = OUT.with_name(f"dinov2_candidates_{args.tag}") if args.weights else OUT
|
| 216 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 217 |
+
encoder = HighResolutionEncoder(SOURCE)
|
| 218 |
+
if args.weights:
|
| 219 |
+
# The deployed "base" bank was built with the original encoder, so its score (and the reproduction check) no
|
| 220 |
+
# longer match the app with these weights; every other candidate is rebuilt from the fine-tuned features.
|
| 221 |
+
encoder.model.load_state_dict(torch.load(args.weights, map_location=encoder.device))
|
| 222 |
+
for category in args.categories:
|
| 223 |
+
target = out / (f"{category}.smoke.json" if args.smoke else f"{category}.json")
|
| 224 |
+
if target.exists() and not args.force:
|
| 225 |
+
print(f"{category}: already done ({target.name})", flush=True)
|
| 226 |
+
continue
|
| 227 |
+
record = run_category(category, encoder, args.smoke)
|
| 228 |
+
torch.cuda.empty_cache() # the category's banks are freed when run_category returns
|
| 229 |
+
target.write_text(json.dumps(record), encoding="utf-8")
|
| 230 |
+
rep = record["reproduction"]
|
| 231 |
+
print(
|
| 232 |
+
f"{category}: {record['seconds_total']} s | reproduces the app: test max diff {rep['test_max_abs_difference']:.4f}, "
|
| 233 |
+
f"mean {rep['test_mean_abs_difference']:.4f}",
|
| 234 |
+
flush=True,
|
| 235 |
+
)
|
| 236 |
+
print(" AUROC " + summarise(record), flush=True)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
main()
|
scripts/encoder_candidates_report.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare the detector candidates (step 2 of 2, CPU only; run scripts.encoder_candidates first).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_candidates_report
|
| 4 |
+
|
| 5 |
+
Rules fixed before any result was seen:
|
| 6 |
+
* Every candidate score is standardised with the mean and spread of the 90 held-out NORMAL images (no labels).
|
| 7 |
+
* Fusions are plain averages of those standardised scores; the list below is complete, nothing was added after looking.
|
| 8 |
+
* Each method is compared with the deployed one ("base") by a paired bootstrap of the AUROC difference
|
| 9 |
+
(images resampled with replacement within normals and within anomalies, 2,000 rounds, 95% interval).
|
| 10 |
+
* A method counts as an improvement only if the interval for the difference stays above zero.
|
| 11 |
+
* Thresholds come from the held-out normals only: q95 for every category (a like-for-like comparison) and the
|
| 12 |
+
deployed q80 for Macaroni1/2.
|
| 13 |
+
* The 200 test images per category were already seen during development, so this is descriptive, not a fresh test.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import csv
|
| 18 |
+
import json
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from backend.config import ROOT
|
| 23 |
+
from scripts.diagnose_encoder import auroc
|
| 24 |
+
|
| 25 |
+
RESULTS = ROOT / "experiments" / "dinov2_candidates"
|
| 26 |
+
VISA = ROOT / "VisA_20220922"
|
| 27 |
+
OUT = ROOT / "results" / "encoder_candidates.json"
|
| 28 |
+
SINGLES = ("base", "full", "fullfg", "pos", "cls", "meanpool", "coarse")
|
| 29 |
+
FUSIONS = {
|
| 30 |
+
"base+cls": ("base", "cls"),
|
| 31 |
+
"base+coarse": ("base", "coarse"),
|
| 32 |
+
"base+pos": ("base", "pos"),
|
| 33 |
+
"full+cls": ("full", "cls"),
|
| 34 |
+
"full+meanpool": ("full", "meanpool"),
|
| 35 |
+
"full+coarse": ("full", "coarse"),
|
| 36 |
+
"full+pos": ("full", "pos"),
|
| 37 |
+
"fullfg+coarse": ("fullfg", "coarse"),
|
| 38 |
+
"full+coarse+cls": ("full", "coarse", "cls"),
|
| 39 |
+
"full+coarse+pos": ("full", "coarse", "pos"),
|
| 40 |
+
}
|
| 41 |
+
HARD_TYPES = {
|
| 42 |
+
"macaroni1": "chip around edge and corner",
|
| 43 |
+
"macaroni2": "small chip around edge",
|
| 44 |
+
"pcb2": "missing",
|
| 45 |
+
"pcb3": "missing",
|
| 46 |
+
"candle": "weird candle wick",
|
| 47 |
+
}
|
| 48 |
+
DEPLOYED_QUANTILE = {"macaroni1": 0.80, "macaroni2": 0.80}
|
| 49 |
+
ROUNDS = 2000
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def standardised(record, parts):
|
| 53 |
+
"""Average of the held-out-normal standardised scores of the named candidates, or None if unavailable."""
|
| 54 |
+
held_names, test_names = sorted(record["heldout"]), sorted(record["test"])
|
| 55 |
+
held = np.zeros(len(held_names))
|
| 56 |
+
test = np.zeros(len(test_names))
|
| 57 |
+
for part in parts:
|
| 58 |
+
h = [record["heldout"][n][part] for n in held_names]
|
| 59 |
+
t = [record["test"][n][part] for n in test_names]
|
| 60 |
+
if any(v is None for v in h + t):
|
| 61 |
+
return None
|
| 62 |
+
h, t = np.array(h, float), np.array(t, float)
|
| 63 |
+
spread = h.std()
|
| 64 |
+
if spread == 0:
|
| 65 |
+
return None
|
| 66 |
+
held += (h - h.mean()) / spread / len(parts)
|
| 67 |
+
test += (t - h.mean()) / spread / len(parts)
|
| 68 |
+
return held, test
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def bootstrap_difference(labels, method, base, rng):
|
| 72 |
+
positive, negative = np.flatnonzero(labels == 1), np.flatnonzero(labels == 0)
|
| 73 |
+
differences = np.empty(ROUNDS)
|
| 74 |
+
for i in range(ROUNDS):
|
| 75 |
+
p = rng.choice(positive, len(positive))
|
| 76 |
+
n = rng.choice(negative, len(negative))
|
| 77 |
+
differences[i] = auroc(method[p], method[n]) - auroc(base[p], base[n])
|
| 78 |
+
return np.percentile(differences, [2.5, 97.5])
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def anomaly_types(category, names):
|
| 82 |
+
rows = {r["image"]: r for r in csv.DictReader((VISA / category / "image_anno.csv").open(encoding="utf-8"))}
|
| 83 |
+
return {n: [t.strip() for t in rows[n]["label"].split(",")] for n in names}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main():
|
| 87 |
+
parser = argparse.ArgumentParser()
|
| 88 |
+
parser.add_argument("--anchor", default="base", choices=SINGLES, help="method every difference is measured against")
|
| 89 |
+
anchor = parser.parse_args().anchor
|
| 90 |
+
rng = np.random.default_rng(2026)
|
| 91 |
+
records = {
|
| 92 |
+
p.stem: json.loads(p.read_text(encoding="utf-8"))
|
| 93 |
+
for p in sorted(RESULTS.glob("*.json"))
|
| 94 |
+
if ".smoke" not in p.name
|
| 95 |
+
}
|
| 96 |
+
methods = list(SINGLES) + list(FUSIONS)
|
| 97 |
+
report = {}
|
| 98 |
+
for category, record in records.items():
|
| 99 |
+
names = sorted(record["test"])
|
| 100 |
+
labels = np.array([record["labels"][n] for n in names])
|
| 101 |
+
entry = {"reproduction_max_abs_difference": record["reproduction"]["test_max_abs_difference"], "methods": {}}
|
| 102 |
+
_, base_test = standardised(record, (anchor,))
|
| 103 |
+
for name in methods:
|
| 104 |
+
parts = (name,) if name in SINGLES else FUSIONS[name]
|
| 105 |
+
got = standardised(record, parts)
|
| 106 |
+
if got is None:
|
| 107 |
+
continue
|
| 108 |
+
held, test = got
|
| 109 |
+
value = auroc(test[labels == 1], test[labels == 0])
|
| 110 |
+
interval = None if name == anchor else bootstrap_difference(labels, test, base_test, rng).tolist()
|
| 111 |
+
result = {"auroc": value, "difference_vs_base_95": interval}
|
| 112 |
+
for label, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))):
|
| 113 |
+
threshold = np.quantile(held, quantile)
|
| 114 |
+
result[f"recall_{label}"] = float((test[labels == 1] >= threshold).mean())
|
| 115 |
+
result[f"false_alarm_{label}"] = float((test[labels == 0] >= threshold).mean())
|
| 116 |
+
if category in HARD_TYPES:
|
| 117 |
+
types = anomaly_types(category, names)
|
| 118 |
+
hard = np.array([HARD_TYPES[category] in types[n] for n in names])
|
| 119 |
+
result["auroc_hard_type"] = auroc(test[hard & (labels == 1)], test[labels == 0])
|
| 120 |
+
entry["methods"][name] = result
|
| 121 |
+
report[category] = entry
|
| 122 |
+
target = OUT if anchor == "base" else OUT.with_name(f"encoder_candidates_vs_{anchor}.json")
|
| 123 |
+
target.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 124 |
+
|
| 125 |
+
categories = list(report)
|
| 126 |
+
print(
|
| 127 |
+
f"Categories analysed: {len(categories)}. Harness reproduces the app: largest difference "
|
| 128 |
+
f"{max(e['reproduction_max_abs_difference'] for e in report.values()):.5f}\n"
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def table(columns, title):
|
| 132 |
+
print(title)
|
| 133 |
+
print(f"{'category':<11}" + "".join(f"{c:>17}" for c in columns))
|
| 134 |
+
for category in categories:
|
| 135 |
+
cells = []
|
| 136 |
+
for c in columns:
|
| 137 |
+
m = report[category]["methods"].get(c)
|
| 138 |
+
if m is None:
|
| 139 |
+
cells.append(f"{'n/a':>17}")
|
| 140 |
+
continue
|
| 141 |
+
mark = ""
|
| 142 |
+
if m["difference_vs_base_95"] is not None:
|
| 143 |
+
low, high = m["difference_vs_base_95"]
|
| 144 |
+
mark = " ▲" if low > 0 else " ▼" if high < 0 else ""
|
| 145 |
+
cells.append(f"{m['auroc']:>15.3f}{mark:<2}")
|
| 146 |
+
print(f"{category:<11}" + "".join(cells))
|
| 147 |
+
macro = []
|
| 148 |
+
for c in columns:
|
| 149 |
+
values = [report[k]["methods"][c]["auroc"] for k in categories if c in report[k]["methods"]]
|
| 150 |
+
macro.append(f"{np.mean(values):>17.3f}" if len(values) == len(categories) else f"{'n/a':>17}")
|
| 151 |
+
print(f"{'MEAN':<11}" + "".join(macro) + "\n")
|
| 152 |
+
|
| 153 |
+
print(f"AUROC per category. ▲ = better than '{anchor}' (95% interval above 0), ▼ = worse.\n")
|
| 154 |
+
table(SINGLES, "Single candidates")
|
| 155 |
+
table(list(FUSIONS)[:5], "Fusions (1/2)")
|
| 156 |
+
table(list(FUSIONS)[5:], "Fusions (2/2)")
|
| 157 |
+
|
| 158 |
+
print("Hard defect types (AUROC of that type against all normals)")
|
| 159 |
+
print(
|
| 160 |
+
f"{'category / type':<40}"
|
| 161 |
+
+ "".join(f"{c:>14}" for c in ("base", "full", "fullfg", "coarse", "full+coarse", "full+pos"))
|
| 162 |
+
)
|
| 163 |
+
for category, kind in HARD_TYPES.items():
|
| 164 |
+
if category not in report:
|
| 165 |
+
continue
|
| 166 |
+
cells = [
|
| 167 |
+
report[category]["methods"].get(c, {}).get("auroc_hard_type")
|
| 168 |
+
for c in ("base", "full", "fullfg", "coarse", "full+coarse", "full+pos")
|
| 169 |
+
]
|
| 170 |
+
print(f"{category + ' / ' + kind:<40}" + "".join(f"{'n/a':>14}" if v is None else f"{v:>14.3f}" for v in cells))
|
| 171 |
+
|
| 172 |
+
ranked = sorted(
|
| 173 |
+
(m for m in methods if m != "base" and all(m in report[k]["methods"] for k in categories)),
|
| 174 |
+
key=lambda m: -np.mean([report[k]["methods"][m]["auroc"] for k in categories]),
|
| 175 |
+
)
|
| 176 |
+
print("\nOperating points for the three best methods by mean AUROC (thresholds from held-out normals only)")
|
| 177 |
+
print("q95 = same policy everywhere; deployed = q80 for macaroni1/2")
|
| 178 |
+
shown = ["base", "full"] + [m for m in ranked if m != "full"][:2]
|
| 179 |
+
print(
|
| 180 |
+
f"{'category':<11}{'method':<17}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}"
|
| 181 |
+
)
|
| 182 |
+
for category in categories:
|
| 183 |
+
if category not in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew"):
|
| 184 |
+
continue
|
| 185 |
+
for name in shown:
|
| 186 |
+
m = report[category]["methods"][name]
|
| 187 |
+
print(
|
| 188 |
+
f"{category:<11}{name:<17}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}"
|
| 189 |
+
f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}"
|
| 190 |
+
)
|
| 191 |
+
print(
|
| 192 |
+
"\nA method is an improvement only if the weak categories gain with an interval above 0 and no category is "
|
| 193 |
+
"significantly worse (▼). Written to results/encoder_candidates.json."
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
main()
|
scripts/encoder_finetune.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fine-tune the last blocks of DINOv2 with synthetic structural defects (round 4 of the detector study; needs the GPU).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_finetune --cache # step 1: resize all training normals once (CPU, about 10 minutes)
|
| 4 |
+
python -m scripts.encoder_finetune --train # step 2: train (GPU, about 30 minutes)
|
| 5 |
+
|
| 6 |
+
Why: round 1 found that the weak spots are structural defects (chipped edges, missing parts), where each small patch
|
| 7 |
+
can still look normal. This tests whether a DINOv2 whose last blocks have seen such defects separates them better.
|
| 8 |
+
|
| 9 |
+
Fixed before any result (one configuration, nothing tuned on the test images):
|
| 10 |
+
* One shared model for all 12 categories. Training images: only the fit normals per category that the deployed banks use
|
| 11 |
+
(about 90% of the training normals: 810 for the larger categories, 405-487 for the others). The held-out normals and
|
| 12 |
+
the test images are never read here.
|
| 13 |
+
* Synthetic defects made from normal images only: cut-and-paste of a patch from another image, an "erased" region
|
| 14 |
+
filled with the local background (a missing part), and an edge region swapped with foreign content (a chip). One to
|
| 15 |
+
three per image; 20% of the images stay clean.
|
| 16 |
+
* Trained: the last 4 transformer blocks, the final layer norm and a linear patch head that predicts which patches
|
| 17 |
+
hold a synthetic defect. The first 8 blocks stay frozen. A consistency loss keeps the features of untouched patches
|
| 18 |
+
close to the original frozen model, so the strong categories should not drift.
|
| 19 |
+
* 2,500 steps, batch 8, AdamW (1e-5 backbone, 1e-3 head), cosine schedule, bf16.
|
| 20 |
+
|
| 21 |
+
Evaluation (separate step): python -m scripts.encoder_candidates --weights experiments/dinov2_finetune/encoder_ft.pt
|
| 22 |
+
rebuilds every bank with the fine-tuned encoder and scores the same test images, compared with the frozen full bank.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import json
|
| 27 |
+
import math
|
| 28 |
+
import time
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import torch
|
| 32 |
+
import torch.nn.functional as F
|
| 33 |
+
from PIL import Image, ImageDraw, ImageFilter
|
| 34 |
+
from transformers import AutoModel
|
| 35 |
+
|
| 36 |
+
from backend.config import CATEGORIES, ROOT
|
| 37 |
+
|
| 38 |
+
RUNS = ROOT / "experiments" / "dinov2_highres_v1"
|
| 39 |
+
VISA = ROOT / "VisA_20220922"
|
| 40 |
+
SOURCE = ROOT / "models" / "encoder_dinov2"
|
| 41 |
+
OUT = ROOT / "experiments" / "dinov2_finetune"
|
| 42 |
+
OUT_REALISTIC = ROOT / "experiments" / "dinov2_finetune_realistic"
|
| 43 |
+
SIZE = 448
|
| 44 |
+
GRID = SIZE // 14
|
| 45 |
+
STEPS = 2500
|
| 46 |
+
BATCH = 8
|
| 47 |
+
TRAINABLE_BLOCKS = 4
|
| 48 |
+
CONSISTENCY = 2.0
|
| 49 |
+
CLEAN_SHARE = 0.2
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def fit_names(category):
|
| 53 |
+
run = RUNS / category
|
| 54 |
+
split = json.loads((run / "split.json").read_text(encoding="utf-8"))
|
| 55 |
+
held = {
|
| 56 |
+
p["image"] for p in json.loads((run / "normal_calibration.json").read_text(encoding="utf-8"))["predictions"]
|
| 57 |
+
}
|
| 58 |
+
return [r["image"] for r in split["train"] if r["image"] not in held]
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def build_cache():
|
| 62 |
+
"""Resize every fit normal to short edge 448, centre-crop 448 x 448 and store it as raw bytes on disk."""
|
| 63 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
entries = [(c, n) for c in CATEGORIES for n in fit_names(c)]
|
| 65 |
+
cache = np.lib.format.open_memmap(
|
| 66 |
+
OUT / "train_448.npy", mode="w+", dtype=np.uint8, shape=(len(entries), SIZE, SIZE, 3)
|
| 67 |
+
)
|
| 68 |
+
for i, (_, name) in enumerate(entries):
|
| 69 |
+
with Image.open(VISA / name) as image:
|
| 70 |
+
image = image.convert("RGB")
|
| 71 |
+
factor = SIZE / min(image.size)
|
| 72 |
+
image = image.resize(
|
| 73 |
+
(max(SIZE, round(image.width * factor)), max(SIZE, round(image.height * factor))),
|
| 74 |
+
Image.Resampling.BICUBIC,
|
| 75 |
+
)
|
| 76 |
+
left, top = (image.width - SIZE) // 2, (image.height - SIZE) // 2
|
| 77 |
+
cache[i] = np.asarray(image.crop((left, top, left + SIZE, top + SIZE)))
|
| 78 |
+
if i % 1000 == 0:
|
| 79 |
+
print(f"cached {i}/{len(entries)}", flush=True)
|
| 80 |
+
cache.flush()
|
| 81 |
+
(OUT / "train_index.json").write_text(json.dumps(entries), encoding="utf-8")
|
| 82 |
+
print(f"cached {len(entries)} images", flush=True)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def rectangle(rng, height, width):
|
| 86 |
+
area = rng.uniform(0.004, 0.04) * height * width
|
| 87 |
+
ratio = rng.uniform(0.5, 2.0)
|
| 88 |
+
rh, rw = int(math.sqrt(area * ratio)), int(math.sqrt(area / ratio))
|
| 89 |
+
rh, rw = max(8, min(rh, height // 3)), max(8, min(rw, width // 3))
|
| 90 |
+
return rng.integers(0, height - rh), rng.integers(0, width - rw), rh, rw
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def synthesise(image, other, rng):
|
| 94 |
+
"""Return a copy of the image with 1-3 synthetic structural defects and the boolean mask of the changed pixels."""
|
| 95 |
+
height, width, _ = image.shape
|
| 96 |
+
out, mask = image.copy(), np.zeros((height, width), bool)
|
| 97 |
+
gradient = np.hypot(*np.gradient(image.mean(2)))
|
| 98 |
+
edge_points = np.argwhere(gradient > np.quantile(gradient, 0.97))
|
| 99 |
+
for _ in range(rng.integers(1, 4)):
|
| 100 |
+
kind = rng.choice(("cutpaste", "erase", "chip"))
|
| 101 |
+
if kind == "cutpaste":
|
| 102 |
+
y, x, rh, rw = rectangle(rng, height, width)
|
| 103 |
+
sy, sx = rng.integers(0, height - rh), rng.integers(0, width - rw)
|
| 104 |
+
piece = other[sy : sy + rh, sx : sx + rw].astype(np.float32) * rng.uniform(0.9, 1.1)
|
| 105 |
+
out[y : y + rh, x : x + rw] = np.clip(piece, 0, 255).astype(np.uint8)
|
| 106 |
+
mask[y : y + rh, x : x + rw] = True
|
| 107 |
+
elif kind == "erase":
|
| 108 |
+
y, x, rh, rw = rectangle(rng, height, width)
|
| 109 |
+
ring = np.concatenate(
|
| 110 |
+
[
|
| 111 |
+
image[max(0, y - 6) : y, x : x + rw].reshape(-1, 3),
|
| 112 |
+
image[y + rh : y + rh + 6, x : x + rw].reshape(-1, 3),
|
| 113 |
+
]
|
| 114 |
+
)
|
| 115 |
+
fill = ring.mean(0) if len(ring) else image.reshape(-1, 3).mean(0)
|
| 116 |
+
out[y : y + rh, x : x + rw] = fill.astype(np.uint8)
|
| 117 |
+
mask[y : y + rh, x : x + rw] = True
|
| 118 |
+
elif len(edge_points):
|
| 119 |
+
cy, cx = edge_points[rng.integers(len(edge_points))]
|
| 120 |
+
radius = int(rng.integers(8, 28))
|
| 121 |
+
yy, xx = np.ogrid[:height, :width]
|
| 122 |
+
disk = (yy - cy) ** 2 + (xx - cx) ** 2 <= radius**2
|
| 123 |
+
sy, sx = rng.integers(0, height), rng.integers(0, width)
|
| 124 |
+
foreign = np.roll(other, (sy - cy, sx - cx), axis=(0, 1))
|
| 125 |
+
out[disk] = foreign[disk]
|
| 126 |
+
mask |= disk
|
| 127 |
+
return out, mask
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def smooth_noise(rng, scales=(3, 6, 12)):
|
| 131 |
+
"""Low-frequency random field in [-1, 1] at SIZE x SIZE: a few octaves of coarse noise, upsampled."""
|
| 132 |
+
total = np.zeros((SIZE, SIZE), np.float32)
|
| 133 |
+
for scale in scales:
|
| 134 |
+
grid = Image.fromarray(rng.random((scale, scale)).astype(np.float32))
|
| 135 |
+
total += np.asarray(grid.resize((SIZE, SIZE), Image.Resampling.BICUBIC)) / len(scales)
|
| 136 |
+
total -= total.mean()
|
| 137 |
+
return total / (np.abs(total).max() + 1e-6)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def blob(rng, centre, radius, roughness=0.5):
|
| 141 |
+
"""Irregular blob: a disk whose edge is pushed in and out by smooth noise."""
|
| 142 |
+
yy, xx = np.ogrid[:SIZE, :SIZE]
|
| 143 |
+
distance = np.hypot(yy - centre[0], xx - centre[1]) / radius
|
| 144 |
+
return distance + roughness * smooth_noise(rng, (4, 8)) < 1
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def foreground_guess(image):
|
| 148 |
+
"""Object pixels = colour far from the median of the image border (None if that does not separate anything)."""
|
| 149 |
+
border = np.concatenate([image[:12].reshape(-1, 3), image[-12:].reshape(-1, 3)])
|
| 150 |
+
background = np.median(border, axis=0)
|
| 151 |
+
difference = np.linalg.norm(image.astype(np.float32) - background, axis=2)
|
| 152 |
+
mask = Image.fromarray(((difference > 28) * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(5))
|
| 153 |
+
mask = np.asarray(mask.filter(ImageFilter.MaxFilter(5))) > 0
|
| 154 |
+
return (mask, background) if 0.04 < mask.mean() < 0.9 else (None, background)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def boundary_points(mask):
|
| 158 |
+
inner = np.asarray(Image.fromarray((mask * 255).astype(np.uint8)).filter(ImageFilter.MinFilter(5))) > 0
|
| 159 |
+
return np.argwhere(mask & ~inner)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def scratch_mask(rng):
|
| 163 |
+
canvas = Image.new("L", (SIZE, SIZE), 0)
|
| 164 |
+
draw = ImageDraw.Draw(canvas)
|
| 165 |
+
y, x = rng.integers(40, SIZE - 40, 2).astype(float)
|
| 166 |
+
angle = rng.uniform(0, 2 * math.pi)
|
| 167 |
+
points = [(x, y)]
|
| 168 |
+
for _ in range(int(rng.integers(8, 20))):
|
| 169 |
+
angle += rng.normal(0, 0.35)
|
| 170 |
+
x, y = x + 9 * math.cos(angle), y + 9 * math.sin(angle)
|
| 171 |
+
points.append((x, y))
|
| 172 |
+
draw.line(points, fill=255, width=int(rng.integers(2, 6)))
|
| 173 |
+
return np.asarray(canvas) > 0
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def synthesise_realistic(image, other, rng):
|
| 177 |
+
"""1-3 more realistic defects: irregular chips that bite the object's edge, missing pieces, textured blotches
|
| 178 |
+
blended from another image, stains and scratches. Returns the edited copy and the mask of changed pixels."""
|
| 179 |
+
out, mask = image.astype(np.float32), np.zeros((SIZE, SIZE), bool)
|
| 180 |
+
foreground, background = foreground_guess(image)
|
| 181 |
+
edge = boundary_points(foreground) if foreground is not None else np.empty((0, 2), int)
|
| 182 |
+
for _ in range(rng.integers(1, 4)):
|
| 183 |
+
kind = rng.choice(("chip", "chip", "missing", "texture", "stain", "scratch"))
|
| 184 |
+
if kind in ("chip", "missing") and len(edge):
|
| 185 |
+
centre = edge[rng.integers(len(edge))]
|
| 186 |
+
radius = rng.uniform(8, 26) if kind == "chip" else rng.uniform(18, 48)
|
| 187 |
+
region = blob(rng, centre, radius) & foreground
|
| 188 |
+
if region.sum() < 30:
|
| 189 |
+
continue
|
| 190 |
+
fill = background + rng.normal(0, 3, 3)
|
| 191 |
+
out[region] = fill
|
| 192 |
+
ring = np.asarray(Image.fromarray((region * 255).astype(np.uint8)).filter(ImageFilter.MaxFilter(7))) > 0
|
| 193 |
+
out[ring & ~region & foreground] *= rng.uniform(0.75, 0.95) # darker fracture rim, as on a real break
|
| 194 |
+
mask |= ring
|
| 195 |
+
elif kind == "texture" or (kind in ("chip", "missing") and not len(edge)):
|
| 196 |
+
region = blob(rng, rng.integers(40, SIZE - 40, 2), rng.uniform(15, 50), roughness=0.7)
|
| 197 |
+
shift = (int(rng.integers(0, SIZE)), int(rng.integers(0, SIZE)))
|
| 198 |
+
alpha = rng.uniform(0.6, 1.0)
|
| 199 |
+
out[region] = (1 - alpha) * out[region] + alpha * np.roll(other, shift, axis=(0, 1))[region]
|
| 200 |
+
mask |= region
|
| 201 |
+
elif kind == "stain":
|
| 202 |
+
region = blob(rng, rng.integers(40, SIZE - 40, 2), rng.uniform(15, 45), roughness=0.7)
|
| 203 |
+
tint = rng.uniform(0.45, 0.85) if rng.random() < 0.6 else rng.uniform(1.15, 1.5)
|
| 204 |
+
out[region] = out[region] * tint + rng.normal(0, 10, 3)
|
| 205 |
+
mask |= region
|
| 206 |
+
else:
|
| 207 |
+
region = scratch_mask(rng)
|
| 208 |
+
out[region] = out[region] * (rng.uniform(0.4, 0.7) if rng.random() < 0.5 else rng.uniform(1.3, 1.7))
|
| 209 |
+
mask |= region
|
| 210 |
+
return np.clip(out, 0, 255).astype(np.uint8), mask
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def batch(cache, index, ranges, rng, synth=synthesise):
|
| 214 |
+
images, targets, clean = [], [], []
|
| 215 |
+
for _ in range(BATCH):
|
| 216 |
+
i = int(rng.integers(len(cache)))
|
| 217 |
+
low, high = next(r for r in ranges if r[0] <= i < r[1])
|
| 218 |
+
j = int(rng.integers(low, high))
|
| 219 |
+
image, other = np.array(cache[i]), np.array(cache[j])
|
| 220 |
+
if rng.random() < CLEAN_SHARE:
|
| 221 |
+
mask, keep = np.zeros((SIZE, SIZE), bool), True
|
| 222 |
+
else:
|
| 223 |
+
image, mask = synth(image, other, rng)
|
| 224 |
+
keep = False
|
| 225 |
+
if rng.random() < 0.5:
|
| 226 |
+
image, mask = image[:, ::-1], mask[:, ::-1]
|
| 227 |
+
if rng.random() < 0.5:
|
| 228 |
+
image, mask = image[::-1], mask[::-1]
|
| 229 |
+
images.append(np.ascontiguousarray(image))
|
| 230 |
+
targets.append(mask.reshape(GRID, 14, GRID, 14).mean((1, 3)))
|
| 231 |
+
clean.append(keep)
|
| 232 |
+
return np.stack(images), np.stack(targets).astype(np.float32), clean
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def train(realistic=False):
|
| 236 |
+
device = torch.device("cuda")
|
| 237 |
+
cache = np.load(OUT / "train_448.npy", mmap_mode="r")
|
| 238 |
+
entries = json.loads((OUT / "train_index.json").read_text(encoding="utf-8"))
|
| 239 |
+
ranges, start = [], 0
|
| 240 |
+
for category in CATEGORIES:
|
| 241 |
+
count = sum(1 for c, _ in entries if c == category)
|
| 242 |
+
ranges.append((start, start + count))
|
| 243 |
+
start += count
|
| 244 |
+
student = AutoModel.from_pretrained(str(SOURCE), local_files_only=True).to(device)
|
| 245 |
+
teacher = AutoModel.from_pretrained(str(SOURCE), local_files_only=True).to(device).eval()
|
| 246 |
+
teacher.requires_grad_(False)
|
| 247 |
+
student.requires_grad_(False)
|
| 248 |
+
parameters = []
|
| 249 |
+
for block in student.encoder.layer[-TRAINABLE_BLOCKS:]:
|
| 250 |
+
block.requires_grad_(True)
|
| 251 |
+
parameters += list(block.parameters())
|
| 252 |
+
student.layernorm.requires_grad_(True)
|
| 253 |
+
parameters += list(student.layernorm.parameters())
|
| 254 |
+
head = torch.nn.Linear(student.config.hidden_size, 1).to(device)
|
| 255 |
+
optimiser = torch.optim.AdamW(
|
| 256 |
+
[{"params": parameters, "lr": 1e-5}, {"params": head.parameters(), "lr": 1e-3}], weight_decay=0.01
|
| 257 |
+
)
|
| 258 |
+
schedule = torch.optim.lr_scheduler.CosineAnnealingLR(optimiser, STEPS)
|
| 259 |
+
mean = torch.tensor([0.485, 0.456, 0.406], device=device)[None, :, None, None]
|
| 260 |
+
std = torch.tensor([0.229, 0.224, 0.225], device=device)[None, :, None, None]
|
| 261 |
+
rng = np.random.default_rng(2026)
|
| 262 |
+
started = time.perf_counter()
|
| 263 |
+
for step in range(1, STEPS + 1):
|
| 264 |
+
images, targets, _ = batch(cache, entries, ranges, rng, synthesise_realistic if realistic else synthesise)
|
| 265 |
+
pixels = (torch.from_numpy(images).to(device).permute(0, 3, 1, 2).float() / 255 - mean) / std
|
| 266 |
+
target = torch.from_numpy(targets).to(device).reshape(BATCH, -1)
|
| 267 |
+
with torch.autocast("cuda", dtype=torch.bfloat16):
|
| 268 |
+
tokens = student(pixel_values=pixels).last_hidden_state[:, 1:]
|
| 269 |
+
with torch.no_grad():
|
| 270 |
+
original = teacher(pixel_values=pixels).last_hidden_state[:, 1:]
|
| 271 |
+
logits = head(tokens).squeeze(-1)
|
| 272 |
+
untouched = (target == 0).float()
|
| 273 |
+
similarity = F.cosine_similarity(tokens.float(), original.float(), dim=-1)
|
| 274 |
+
consistency = ((1 - similarity) * untouched).sum() / untouched.sum().clamp_min(1)
|
| 275 |
+
detection = F.binary_cross_entropy_with_logits(logits.float(), target.clamp(0, 1))
|
| 276 |
+
loss = detection + CONSISTENCY * consistency
|
| 277 |
+
optimiser.zero_grad(set_to_none=True)
|
| 278 |
+
loss.backward()
|
| 279 |
+
torch.nn.utils.clip_grad_norm_(parameters + list(head.parameters()), 1.0)
|
| 280 |
+
optimiser.step()
|
| 281 |
+
schedule.step()
|
| 282 |
+
if step % 100 == 0 or step == 1:
|
| 283 |
+
hit = ((logits > 0).float() == (target > 0.2).float()).float().mean().item()
|
| 284 |
+
print(
|
| 285 |
+
f"step {step:4d}/{STEPS} loss {loss.item():.4f} detection {detection.item():.4f} "
|
| 286 |
+
f"consistency {consistency.item():.4f} patch accuracy {hit:.3f} {time.perf_counter() - started:.0f}s",
|
| 287 |
+
flush=True,
|
| 288 |
+
)
|
| 289 |
+
state = {k: v.detach().half().cpu() for k, v in student.state_dict().items()}
|
| 290 |
+
target = OUT_REALISTIC if realistic else OUT
|
| 291 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 292 |
+
torch.save(state, target / "encoder_ft.pt")
|
| 293 |
+
torch.save({k: v.detach().cpu() for k, v in head.state_dict().items()}, target / "head_ft.pt")
|
| 294 |
+
print(f"saved {target / 'encoder_ft.pt'} in {time.perf_counter() - started:.0f}s", flush=True)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def preview():
|
| 298 |
+
"""Write 12 images (one category each, original above, synthetic defects below) to check the defects look plausible."""
|
| 299 |
+
cache = np.load(OUT / "train_448.npy", mmap_mode="r")
|
| 300 |
+
entries = json.loads((OUT / "train_index.json").read_text(encoding="utf-8"))
|
| 301 |
+
rng = np.random.default_rng(7)
|
| 302 |
+
tiles = []
|
| 303 |
+
for category in CATEGORIES:
|
| 304 |
+
rows = [i for i, (c, _) in enumerate(entries) if c == category]
|
| 305 |
+
i, j = int(rng.choice(rows)), int(rng.choice(rows))
|
| 306 |
+
original, other = np.array(cache[i]), np.array(cache[j])
|
| 307 |
+
edited, mask = synthesise_realistic(original, other, rng)
|
| 308 |
+
outline = np.asarray(Image.fromarray((mask * 255).astype(np.uint8)).filter(ImageFilter.FIND_EDGES)) > 0
|
| 309 |
+
marked = edited.copy()
|
| 310 |
+
marked[outline] = (255, 0, 0)
|
| 311 |
+
tiles.append(np.concatenate([original, edited, marked], axis=0))
|
| 312 |
+
sheet = np.concatenate([np.concatenate(tiles[r * 6 : r * 6 + 6], axis=1) for r in range(2)], axis=0)
|
| 313 |
+
target = OUT_REALISTIC
|
| 314 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 315 |
+
Image.fromarray(sheet).resize((sheet.shape[1] // 4, sheet.shape[0] // 4)).save(target / "preview.jpg", quality=90)
|
| 316 |
+
print(f"wrote {target / 'preview.jpg'}")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def main():
|
| 320 |
+
parser = argparse.ArgumentParser()
|
| 321 |
+
parser.add_argument("--cache", action="store_true")
|
| 322 |
+
parser.add_argument("--train", action="store_true")
|
| 323 |
+
parser.add_argument("--realistic", action="store_true", help="round 4b: more realistic synthetic defects")
|
| 324 |
+
parser.add_argument("--preview", action="store_true", help="save a picture of synthetic defects (CPU)")
|
| 325 |
+
args = parser.parse_args()
|
| 326 |
+
if args.preview:
|
| 327 |
+
preview()
|
| 328 |
+
return
|
| 329 |
+
if args.cache:
|
| 330 |
+
build_cache()
|
| 331 |
+
if args.train:
|
| 332 |
+
train(args.realistic)
|
| 333 |
+
if not (args.cache or args.train):
|
| 334 |
+
parser.error("choose --cache and/or --train")
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
if __name__ == "__main__":
|
| 338 |
+
main()
|
scripts/encoder_finetune_report.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Report for round 4, the fine-tuned encoder (CPU only; run scripts.encoder_finetune and
|
| 2 |
+
scripts.encoder_candidates --weights first).
|
| 3 |
+
|
| 4 |
+
python -m scripts.encoder_finetune_report
|
| 5 |
+
|
| 6 |
+
Compares, on the same 200 test images per category, the frozen DINOv2 (experiments/dinov2_candidates) with the
|
| 7 |
+
fine-tuned one (experiments/dinov2_candidates_ft). The primary comparison, fixed before any result: the fine-tuned full
|
| 8 |
+
bank against the frozen full bank (same bank recipe, only the encoder differs). Same rules as
|
| 9 |
+
scripts.encoder_candidates_report: scores standardised with the 90 held-out normals only, paired bootstrap 95% intervals,
|
| 10 |
+
thresholds from held-out normals only (q95 for every category, and the deployed q80 for macaroni1/2 shown separately).
|
| 11 |
+
The "base" score in the fine-tuned files mixes the deployed bank (built with the frozen encoder) with fine-tuned
|
| 12 |
+
features and is not meaningful, so the deployed reference always comes from the frozen files. Descriptive only.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from backend.config import ROOT
|
| 21 |
+
from scripts.diagnose_encoder import auroc
|
| 22 |
+
from scripts.encoder_candidates_report import (
|
| 23 |
+
DEPLOYED_QUANTILE,
|
| 24 |
+
HARD_TYPES,
|
| 25 |
+
RESULTS,
|
| 26 |
+
anomaly_types,
|
| 27 |
+
bootstrap_difference,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
FROZEN = RESULTS
|
| 31 |
+
TUNED = ROOT / "experiments" / "dinov2_candidates_ft"
|
| 32 |
+
OUT = ROOT / "results" / "encoder_finetune.json"
|
| 33 |
+
METHODS = (("frozen base", "frozen", "base"), ("frozen full", "frozen", "full"), ("tuned full", "tuned", "full"))
|
| 34 |
+
EXTRA = (("tuned fullfg", "tuned", "fullfg"), ("tuned pos", "tuned", "pos"), ("frozen pos", "frozen", "pos"))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def scores(record, name, names):
|
| 38 |
+
return np.array([record["test"][n][name] for n in names], float)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def held(record, name):
|
| 42 |
+
return np.array([record["heldout"][n][name] for n in sorted(record["heldout"])], float)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
global TUNED, OUT
|
| 47 |
+
parser = argparse.ArgumentParser()
|
| 48 |
+
parser.add_argument("--tag", default="ft", help="read experiments/dinov2_candidates_<tag>")
|
| 49 |
+
args = parser.parse_args()
|
| 50 |
+
TUNED = ROOT / "experiments" / f"dinov2_candidates_{args.tag}"
|
| 51 |
+
OUT = ROOT / "results" / ("encoder_finetune.json" if args.tag == "ft" else f"encoder_finetune_{args.tag}.json")
|
| 52 |
+
rng = np.random.default_rng(2027)
|
| 53 |
+
report, categories = {}, sorted(p.stem for p in TUNED.glob("*.json") if ".smoke" not in p.name)
|
| 54 |
+
for category in categories:
|
| 55 |
+
records = {
|
| 56 |
+
"frozen": json.loads((FROZEN / f"{category}.json").read_text(encoding="utf-8")),
|
| 57 |
+
"tuned": json.loads((TUNED / f"{category}.json").read_text(encoding="utf-8")),
|
| 58 |
+
}
|
| 59 |
+
names = sorted(records["frozen"]["test"])
|
| 60 |
+
assert names == sorted(records["tuned"]["test"])
|
| 61 |
+
labels = np.array([records["frozen"]["labels"][n] for n in names])
|
| 62 |
+
entry, cache = {}, {}
|
| 63 |
+
for label, source, name in METHODS + EXTRA:
|
| 64 |
+
h = held(records[source], name)
|
| 65 |
+
if any(v is None for v in h) or h.std() == 0:
|
| 66 |
+
continue
|
| 67 |
+
t = np.array([records[source]["test"][n][name] for n in names], float)
|
| 68 |
+
if np.isnan(t).any():
|
| 69 |
+
continue
|
| 70 |
+
cache[label] = (h, t)
|
| 71 |
+
full_test = (cache["frozen full"][1] - cache["frozen full"][0].mean()) / cache["frozen full"][0].std()
|
| 72 |
+
for label, (h, t) in cache.items():
|
| 73 |
+
z_held, z_test = (h - h.mean()) / h.std(), (t - h.mean()) / h.std()
|
| 74 |
+
result = {"auroc": auroc(z_test[labels == 1], z_test[labels == 0])}
|
| 75 |
+
if label != "frozen full":
|
| 76 |
+
result["vs_frozen_full"] = bootstrap_difference(labels, z_test, full_test, rng).tolist()
|
| 77 |
+
for tag, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))):
|
| 78 |
+
threshold = np.quantile(z_held, quantile)
|
| 79 |
+
result[f"recall_{tag}"] = float((z_test[labels == 1] >= threshold).mean())
|
| 80 |
+
result[f"false_alarm_{tag}"] = float((z_test[labels == 0] >= threshold).mean())
|
| 81 |
+
if category in HARD_TYPES:
|
| 82 |
+
kinds = anomaly_types(category, names)
|
| 83 |
+
hard = np.array([HARD_TYPES[category] in kinds[n] for n in names])
|
| 84 |
+
result["auroc_hard_type"] = auroc(z_test[hard & (labels == 1)], z_test[labels == 0])
|
| 85 |
+
entry[label] = result
|
| 86 |
+
report[category] = entry
|
| 87 |
+
OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 88 |
+
|
| 89 |
+
def mark(m):
|
| 90 |
+
interval = m.get("vs_frozen_full")
|
| 91 |
+
if not interval:
|
| 92 |
+
return " "
|
| 93 |
+
return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " "
|
| 94 |
+
|
| 95 |
+
labels_all = [m[0] for m in METHODS + EXTRA]
|
| 96 |
+
print(f"Categories: {len(categories)} (▲/▼ = clearly better/worse than the FROZEN full bank)\n")
|
| 97 |
+
print(f"{'category':<11}" + "".join(f"{c:>15}" for c in labels_all))
|
| 98 |
+
for category in categories:
|
| 99 |
+
row = "".join(
|
| 100 |
+
f"{report[category][c]['auroc']:>13.3f}{mark(report[category][c])}"
|
| 101 |
+
if c in report[category]
|
| 102 |
+
else f"{'n/a':>15}"
|
| 103 |
+
for c in labels_all
|
| 104 |
+
)
|
| 105 |
+
print(f"{category:<11}{row}")
|
| 106 |
+
print(
|
| 107 |
+
f"{'MEAN':<11}"
|
| 108 |
+
+ "".join(
|
| 109 |
+
f"{np.mean([report[k][c]['auroc'] for k in categories]):>15.3f}"
|
| 110 |
+
if all(c in report[k] for k in categories)
|
| 111 |
+
else f"{'n/a':>15}"
|
| 112 |
+
for c in labels_all
|
| 113 |
+
)
|
| 114 |
+
)
|
| 115 |
+
wins = sum(mark(report[k]["tuned full"]) == " ▲" for k in categories)
|
| 116 |
+
losses = sum(mark(report[k]["tuned full"]) == " ▼" for k in categories)
|
| 117 |
+
print(f"\ntuned full vs frozen full: clearly better in {wins}, clearly worse in {losses} of {len(categories)}\n")
|
| 118 |
+
|
| 119 |
+
print("Hard defect types (AUROC of that type against all normals)")
|
| 120 |
+
print(f"{'category / type':<40}{'frozen base':>13}{'frozen full':>13}{'tuned full':>13}")
|
| 121 |
+
for category, kind in HARD_TYPES.items():
|
| 122 |
+
if category in report:
|
| 123 |
+
cells = "".join(
|
| 124 |
+
f"{report[category][c]['auroc_hard_type']:>13.3f}" for c in ("frozen base", "frozen full", "tuned full")
|
| 125 |
+
)
|
| 126 |
+
print(f"{category + ' / ' + kind:<40}{cells}")
|
| 127 |
+
|
| 128 |
+
print("\nOperating points: q95 for every category; deployed = q80 for macaroni1/2")
|
| 129 |
+
print(
|
| 130 |
+
f"{'category':<11}{'method':<13}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}"
|
| 131 |
+
)
|
| 132 |
+
for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report):
|
| 133 |
+
for label in ("frozen base", "frozen full", "tuned full"):
|
| 134 |
+
m = report[category][label]
|
| 135 |
+
print(
|
| 136 |
+
f"{category:<11}{label:<13}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}"
|
| 137 |
+
f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}"
|
| 138 |
+
)
|
| 139 |
+
print(f"\nWritten to results/{OUT.name}. Descriptive only (test images already seen in development).")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if __name__ == "__main__":
|
| 143 |
+
main()
|
scripts/encoder_tuned_coreset.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Round 5: a deployable 32,768-patch coreset built from the fine-tuned (realistic-defect) encoder. Needs the GPU.
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_tuned_coreset # all 12 categories, about 40 minutes
|
| 4 |
+
python -m scripts.encoder_tuned_coreset --smoke --categories macaroni2
|
| 5 |
+
|
| 6 |
+
Fixed before any result: the encoder is experiments/dinov2_finetune_realistic/encoder_ft.pt (round 4b, the only
|
| 7 |
+
variant carried forward), the bank is a greedy farthest-point coreset of 32,768 patches taken from every patch of the
|
| 8 |
+
810 fit normals, exactly as in round 3 (scripts.encoder_banks), and scores use the same top-1% foreground rule.
|
| 9 |
+
Held-out normals and test images are only scored, never used to build anything. Compare with
|
| 10 |
+
scripts.encoder_tuned_coreset_report. Results go to experiments/dinov2_tuned_coreset/<category>.json.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn.functional as F
|
| 19 |
+
|
| 20 |
+
from backend.config import CATEGORIES, ROOT
|
| 21 |
+
from backend.highres import HighResolutionEncoder, foreground_mask
|
| 22 |
+
from scripts.diagnose_encoder import auroc
|
| 23 |
+
from scripts.encoder_banks import greedy_coreset
|
| 24 |
+
from scripts.encoder_candidates import RUNS, SOURCE, encode, knn_distance, open_image, top_mean
|
| 25 |
+
|
| 26 |
+
WEIGHTS = ROOT / "experiments" / "dinov2_finetune_realistic" / "encoder_ft.pt"
|
| 27 |
+
OUT = ROOT / "experiments" / "dinov2_tuned_coreset"
|
| 28 |
+
SIZE = 32768
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def run_category(category, encoder, smoke):
|
| 32 |
+
run = RUNS / category
|
| 33 |
+
split = json.loads((run / "split.json").read_text(encoding="utf-8"))
|
| 34 |
+
calibration = json.loads((run / "normal_calibration.json").read_text(encoding="utf-8"))
|
| 35 |
+
held_names = [p["image"] for p in calibration["predictions"]]
|
| 36 |
+
fit_names = [r["image"] for r in split["train"] if r["image"] not in set(held_names)]
|
| 37 |
+
test_rows = split["test"]
|
| 38 |
+
if smoke:
|
| 39 |
+
fit_names, held_names = fit_names[:100], held_names[:20]
|
| 40 |
+
test_rows = test_rows[:: max(1, len(test_rows) // 40)]
|
| 41 |
+
device = encoder.device
|
| 42 |
+
started = time.perf_counter()
|
| 43 |
+
parts = []
|
| 44 |
+
for name in fit_names:
|
| 45 |
+
tokens, _, _ = encode(encoder, open_image(name), 448)
|
| 46 |
+
parts.append(F.normalize(tokens, dim=-1).half())
|
| 47 |
+
everything = torch.cat(parts)
|
| 48 |
+
del parts
|
| 49 |
+
chosen = greedy_coreset(everything, SIZE, seed=42)
|
| 50 |
+
bank = everything[chosen].clone()
|
| 51 |
+
total = len(everything)
|
| 52 |
+
del everything
|
| 53 |
+
torch.cuda.empty_cache()
|
| 54 |
+
fit_seconds = time.perf_counter() - started
|
| 55 |
+
|
| 56 |
+
def score(name):
|
| 57 |
+
tokens, _, grid = encode(encoder, open_image(name), 448)
|
| 58 |
+
mask = torch.as_tensor(foreground_mask(tokens, grid), device=device)
|
| 59 |
+
return top_mean(knn_distance(F.normalize(tokens, dim=-1), bank), mask)
|
| 60 |
+
|
| 61 |
+
held = {n: {"core32k": score(n)} for n in held_names}
|
| 62 |
+
test = {r["image"]: {"core32k": score(r["image"])} for r in test_rows}
|
| 63 |
+
return {
|
| 64 |
+
"category": category,
|
| 65 |
+
"smoke": smoke,
|
| 66 |
+
"weights": str(WEIGHTS.relative_to(ROOT)),
|
| 67 |
+
"n_fit": len(fit_names),
|
| 68 |
+
"all_patches": total,
|
| 69 |
+
"bank_patches": len(bank),
|
| 70 |
+
"seconds_fit": round(fit_seconds, 1),
|
| 71 |
+
"seconds_total": round(time.perf_counter() - started, 1),
|
| 72 |
+
"heldout": held,
|
| 73 |
+
"test": test,
|
| 74 |
+
"labels": {r["image"]: 0 if r["label"] == "normal" else 1 for r in test_rows},
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main():
|
| 79 |
+
parser = argparse.ArgumentParser()
|
| 80 |
+
parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES))
|
| 81 |
+
parser.add_argument("--smoke", action="store_true")
|
| 82 |
+
parser.add_argument("--force", action="store_true")
|
| 83 |
+
args = parser.parse_args()
|
| 84 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 85 |
+
encoder = HighResolutionEncoder(SOURCE)
|
| 86 |
+
encoder.model.load_state_dict(torch.load(WEIGHTS, map_location=encoder.device))
|
| 87 |
+
for category in args.categories:
|
| 88 |
+
target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json")
|
| 89 |
+
if target.exists() and not args.force:
|
| 90 |
+
print(f"{category}: already done", flush=True)
|
| 91 |
+
continue
|
| 92 |
+
record = run_category(category, encoder, args.smoke)
|
| 93 |
+
torch.cuda.empty_cache()
|
| 94 |
+
target.write_text(json.dumps(record), encoding="utf-8")
|
| 95 |
+
labels = record["labels"]
|
| 96 |
+
pos = [record["test"][n]["core32k"] for n, v in labels.items() if v == 1]
|
| 97 |
+
neg = [record["test"][n]["core32k"] for n, v in labels.items() if v == 0]
|
| 98 |
+
print(
|
| 99 |
+
f"{category}: {record['seconds_total']} s (fit {record['seconds_fit']} s) | tuned coreset 32k AUROC "
|
| 100 |
+
f"{auroc(pos, neg):.3f}",
|
| 101 |
+
flush=True,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
main()
|
scripts/encoder_tuned_coreset_report.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Report for round 5 (CPU only; run scripts.encoder_tuned_coreset first).
|
| 2 |
+
|
| 3 |
+
python -m scripts.encoder_tuned_coreset_report
|
| 4 |
+
|
| 5 |
+
Primary comparison, fixed before any result: the 32,768-patch coreset built from the fine-tuned (realistic-defect)
|
| 6 |
+
encoder against the 32,768-patch coreset built from the frozen encoder, the version that would be shipped otherwise.
|
| 7 |
+
Also shown: the deployed bank, the frozen full bank and the tuned full bank. Same rules as round 2/3: scores standardised
|
| 8 |
+
with the 90 held-out normals only, paired bootstrap 95% intervals, thresholds from held-out normals only (q95 for every
|
| 9 |
+
category, and the deployed q80 for macaroni1/2 shown separately). Descriptive only: the test images were already seen.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from backend.config import ROOT
|
| 17 |
+
from scripts.diagnose_encoder import auroc
|
| 18 |
+
from scripts.encoder_candidates_report import (
|
| 19 |
+
DEPLOYED_QUANTILE,
|
| 20 |
+
HARD_TYPES,
|
| 21 |
+
RESULTS,
|
| 22 |
+
anomaly_types,
|
| 23 |
+
bootstrap_difference,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
EXPERIMENTS = ROOT / "experiments"
|
| 27 |
+
TUNED_CORESET = EXPERIMENTS / "dinov2_tuned_coreset"
|
| 28 |
+
OUT = ROOT / "results" / "encoder_tuned_coreset.json"
|
| 29 |
+
METHODS = ("frozen base", "frozen core32k", "frozen full", "tuned full", "tuned core32k")
|
| 30 |
+
REFERENCE = "frozen core32k"
|
| 31 |
+
WEAK = ("macaroni1", "macaroni2", "pcb2")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def read(path):
|
| 35 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def pick(category):
|
| 39 |
+
"""(held-out, test) score arrays per method, in the order of the sorted test image names."""
|
| 40 |
+
frozen = read(RESULTS / f"{category}.json")
|
| 41 |
+
banks = read(EXPERIMENTS / "dinov2_banks" / f"{category}.json")
|
| 42 |
+
tuned_full = read(EXPERIMENTS / "dinov2_candidates_realistic" / f"{category}.json")
|
| 43 |
+
tuned_core = read(TUNED_CORESET / f"{category}.json")
|
| 44 |
+
names = sorted(frozen["test"])
|
| 45 |
+
held_names = sorted(frozen["heldout"])
|
| 46 |
+
sources = {
|
| 47 |
+
"frozen base": (frozen, "base"),
|
| 48 |
+
"frozen core32k": (banks, "core32k"),
|
| 49 |
+
"frozen full": (frozen, "full"),
|
| 50 |
+
"tuned full": (tuned_full, "full"),
|
| 51 |
+
"tuned core32k": (tuned_core, "core32k"),
|
| 52 |
+
}
|
| 53 |
+
out = {}
|
| 54 |
+
for label, (record, key) in sources.items():
|
| 55 |
+
out[label] = (
|
| 56 |
+
np.array([record["heldout"][n][key] for n in held_names], float),
|
| 57 |
+
np.array([record["test"][n][key] for n in names], float),
|
| 58 |
+
)
|
| 59 |
+
labels = np.array([frozen["labels"][n] for n in names])
|
| 60 |
+
return out, labels, names
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def main():
|
| 64 |
+
rng = np.random.default_rng(2027)
|
| 65 |
+
categories = sorted(p.stem for p in TUNED_CORESET.glob("*.json") if ".smoke" not in p.name)
|
| 66 |
+
report = {}
|
| 67 |
+
for category in categories:
|
| 68 |
+
arrays, labels, names = pick(category)
|
| 69 |
+
standard = {k: ((h - h.mean()) / h.std(), (t - h.mean()) / h.std()) for k, (h, t) in arrays.items()}
|
| 70 |
+
reference = standard[REFERENCE][1]
|
| 71 |
+
entry = {}
|
| 72 |
+
for label, (z_held, z_test) in standard.items():
|
| 73 |
+
result = {"auroc": auroc(z_test[labels == 1], z_test[labels == 0])}
|
| 74 |
+
if label != REFERENCE:
|
| 75 |
+
result["vs_frozen_core32k"] = bootstrap_difference(labels, z_test, reference, rng).tolist()
|
| 76 |
+
for tag, quantile in (("q95", 0.95), ("deployed", DEPLOYED_QUANTILE.get(category, 0.95))):
|
| 77 |
+
threshold = np.quantile(z_held, quantile)
|
| 78 |
+
result[f"recall_{tag}"] = float((z_test[labels == 1] >= threshold).mean())
|
| 79 |
+
result[f"false_alarm_{tag}"] = float((z_test[labels == 0] >= threshold).mean())
|
| 80 |
+
if category in HARD_TYPES:
|
| 81 |
+
kinds = anomaly_types(category, names)
|
| 82 |
+
hard = np.array([HARD_TYPES[category] in kinds[n] for n in names])
|
| 83 |
+
result["auroc_hard_type"] = auroc(z_test[hard & (labels == 1)], z_test[labels == 0])
|
| 84 |
+
entry[label] = result
|
| 85 |
+
report[category] = entry
|
| 86 |
+
OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 87 |
+
|
| 88 |
+
def mark(m):
|
| 89 |
+
interval = m.get("vs_frozen_core32k")
|
| 90 |
+
if not interval:
|
| 91 |
+
return " "
|
| 92 |
+
return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " "
|
| 93 |
+
|
| 94 |
+
print(f"Categories: {len(categories)} (▲/▼ = clearly better/worse than the FROZEN 32k coreset)\n")
|
| 95 |
+
print(f"{'category':<11}" + "".join(f"{m:>16}" for m in METHODS))
|
| 96 |
+
for category in categories:
|
| 97 |
+
print(
|
| 98 |
+
f"{category:<11}"
|
| 99 |
+
+ "".join(f"{report[category][m]['auroc']:>14.3f}{mark(report[category][m])}" for m in METHODS)
|
| 100 |
+
)
|
| 101 |
+
print(f"{'MEAN':<11}" + "".join(f"{np.mean([report[k][m]['auroc'] for k in categories]):>16.3f}" for m in METHODS))
|
| 102 |
+
weak = [k for k in WEAK if k in report]
|
| 103 |
+
if weak:
|
| 104 |
+
print(
|
| 105 |
+
f"{'weak 3':<11}"
|
| 106 |
+
+ "".join(f"{np.mean([report[k][m]['auroc'] for k in weak]):>16.3f}" for m in METHODS)
|
| 107 |
+
+ f" (mean over {', '.join(weak)})"
|
| 108 |
+
)
|
| 109 |
+
tuned = "tuned core32k"
|
| 110 |
+
better = sum(mark(report[k][tuned]) == " ▲" for k in categories)
|
| 111 |
+
worse = sum(mark(report[k][tuned]) == " ▼" for k in categories)
|
| 112 |
+
print(
|
| 113 |
+
f"\ntuned coreset vs frozen coreset: clearly better in {better}, clearly worse in {worse} of {len(categories)}"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
print("\nHard defect types (AUROC of that type against all normals)")
|
| 117 |
+
print(f"{'category / type':<40}" + "".join(f"{m:>16}" for m in METHODS))
|
| 118 |
+
for category, kind in HARD_TYPES.items():
|
| 119 |
+
if category in report:
|
| 120 |
+
print(
|
| 121 |
+
f"{category + ' / ' + kind:<40}"
|
| 122 |
+
+ "".join(f"{report[category][m]['auroc_hard_type']:>16.3f}" for m in METHODS)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
print("\nOperating points: q95 for every category; deployed = q80 for macaroni1/2")
|
| 126 |
+
print(
|
| 127 |
+
f"{'category':<11}{'method':<16}{'AUROC':>7}{'q95 recall':>12}{'q95 false':>11}{'dep. recall':>13}{'dep. false':>12}"
|
| 128 |
+
)
|
| 129 |
+
for category in (c for c in ("macaroni1", "macaroni2", "pcb2", "candle", "cashew") if c in report):
|
| 130 |
+
for label in ("frozen base", "frozen core32k", "tuned core32k"):
|
| 131 |
+
m = report[category][label]
|
| 132 |
+
print(
|
| 133 |
+
f"{category:<11}{label:<16}{m['auroc']:>7.3f}{m['recall_q95']:>12.0%}{m['false_alarm_q95']:>11.0%}"
|
| 134 |
+
f"{m['recall_deployed']:>13.0%}{m['false_alarm_deployed']:>12.0%}"
|
| 135 |
+
)
|
| 136 |
+
print(f"\nWritten to results/{OUT.name}. Descriptive only (test images already seen in development).")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if __name__ == "__main__":
|
| 140 |
+
main()
|
scripts/export_showcase.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export only allowlisted, already measured VisA acceptance examples.
|
| 2 |
+
|
| 3 |
+
Reads SQLite in read-only mode; never performs inference or publishes arbitrary uploads.
|
| 4 |
+
"""
|
| 5 |
+
import csv
|
| 6 |
+
import hashlib
|
| 7 |
+
import html
|
| 8 |
+
import io
|
| 9 |
+
import json
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
import shutil
|
| 12 |
+
import sqlite3
|
| 13 |
+
|
| 14 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
+
OUTPUT = ROOT / 'frontend' / 'public' / 'showcase'
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def export(output=OUTPUT):
|
| 19 |
+
acceptance = json.loads((ROOT / 'results/acceptance.json').read_text())
|
| 20 |
+
examples = list(acceptance['real_images'])
|
| 21 |
+
if len(examples) != 6 or len({e['id'] for e in examples}) != 6:
|
| 22 |
+
raise ValueError('Expected six distinct verified acceptance examples')
|
| 23 |
+
scope = json.loads((ROOT / 'results/evidence_scope_verification.json').read_text())
|
| 24 |
+
quality_path=ROOT/'results/assistant_quality_verification.json'
|
| 25 |
+
quality=json.loads(quality_path.read_text()) if quality_path.exists() else {}
|
| 26 |
+
if quality and quality.get('status')!='passed':raise ValueError('Finish assistant acceptance before exporting')
|
| 27 |
+
final_fingerprint = scope['answers'][0]['knowledge_fingerprint']
|
| 28 |
+
examples.append({**scope['answers'][0]['observation'], 'truth': 1})
|
| 29 |
+
extra_path=ROOT/'results/all_categories_acceptance.json'
|
| 30 |
+
extra=json.loads(extra_path.read_text())['real_images'] if extra_path.exists() else []
|
| 31 |
+
examples.extend(extra)
|
| 32 |
+
extra_ids={e['id'] for e in extra}
|
| 33 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 34 |
+
(output / 'images').mkdir(exist_ok=True)
|
| 35 |
+
(output / 'reports').mkdir(exist_ok=True)
|
| 36 |
+
records, samples, conversations = [], [], {}
|
| 37 |
+
fields = ['id', 'created_at', 'category', 'verdict', 'score', 'threshold',
|
| 38 |
+
'uncertainty_margin', 'inference_ms', 'model_id']
|
| 39 |
+
database = ROOT / 'runtime/inspection.sqlite3'
|
| 40 |
+
with sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) as db:
|
| 41 |
+
for example in examples:
|
| 42 |
+
extra_db=sqlite3.connect((ROOT/'runtime/verification12/inspection.sqlite3').as_uri()+'?mode=ro',uri=True) if example['id'] in extra_ids else None
|
| 43 |
+
selected=extra_db or db
|
| 44 |
+
row = selected.execute('SELECT payload FROM inspections WHERE id=?', (example['id'],)).fetchone()
|
| 45 |
+
if not row:
|
| 46 |
+
raise ValueError('Saved measured example missing: ' + example['id'])
|
| 47 |
+
source = json.loads(row[0])
|
| 48 |
+
record = {k: source[k] for k in fields if k in source}
|
| 49 |
+
if record['score'] != example['score'] or record['verdict'] != example['verdict']:
|
| 50 |
+
raise ValueError('Example differs from measured acceptance record')
|
| 51 |
+
identifier = record['id']
|
| 52 |
+
record.update(batch='Verified VisA examples', filename='VisA example',
|
| 53 |
+
image_url=f'showcase/images/{identifier}.jpg',
|
| 54 |
+
heatmap_url=f'showcase/images/{identifier}_heatmap.jpg')
|
| 55 |
+
for suffix in ('.jpg', '_heatmap.jpg'):
|
| 56 |
+
artifacts=ROOT/('runtime/verification12/artifacts' if extra_db else 'runtime/artifacts')
|
| 57 |
+
shutil.copyfile(artifacts / (identifier + suffix),
|
| 58 |
+
output / 'images' / (identifier + suffix))
|
| 59 |
+
name = record['category'] + ('_anomalous' if example['truth'] else '_good')
|
| 60 |
+
if identifier == scope['inspection_id']:
|
| 61 |
+
name += '_followup'
|
| 62 |
+
samples.append({'name': name, 'category': record['category'], 'record_id': identifier,
|
| 63 |
+
'url': record['image_url'], 'attribution': 'VisA · Zou et al., ECCV 2022 · CC BY 4.0'})
|
| 64 |
+
# Publish saved validated answers and abstentions; omit obsolete fallback diagnostics.
|
| 65 |
+
rows = selected.execute('SELECT role,payload FROM messages WHERE inspection_id=? ORDER BY id', (identifier,)).fetchall()
|
| 66 |
+
if extra_db:extra_db.close()
|
| 67 |
+
messages = []
|
| 68 |
+
for previous, current in zip(rows, rows[1:]):
|
| 69 |
+
if previous[0] != 'user' or current[0] != 'assistant':
|
| 70 |
+
continue
|
| 71 |
+
answer = json.loads(current[1])
|
| 72 |
+
if answer.get('mode') not in ('llm', 'abstained'):
|
| 73 |
+
continue
|
| 74 |
+
if answer.get('mode') == 'llm' and answer.get('knowledge_fingerprint') != final_fingerprint:
|
| 75 |
+
continue
|
| 76 |
+
messages.extend([{'role': 'user', 'question': json.loads(previous[1])['question']},
|
| 77 |
+
{'role': 'assistant', **{k: answer[k] for k in ('answer', 'mode', 'evidence', 'trace') if k in answer}}])
|
| 78 |
+
if identifier == scope['inspection_id']:
|
| 79 |
+
messages = []
|
| 80 |
+
for answer in quality.get('answers',scope['answers']):
|
| 81 |
+
messages.extend([{'role': 'user', 'question': answer['question']},
|
| 82 |
+
{'role': 'assistant', **{k: answer[k] for k in ('answer', 'mode', 'evidence', 'trace')}}])
|
| 83 |
+
conversations[identifier] = messages
|
| 84 |
+
records.append(record)
|
| 85 |
+
esc = lambda value: html.escape(str(value))
|
| 86 |
+
table = ''.join(f'<tr><th>{esc(k)}</th><td>{esc(record.get(k, ""))}</td></tr>' for k in fields)
|
| 87 |
+
discussion = ''.join('<p>' + esc(m.get('question', m.get('answer', ''))) + '</p>' for m in messages) or '<p>No evidence conversation was recorded for this inspection.</p>'
|
| 88 |
+
sources = {s['chunk_id']: s for m in messages for s in m.get('evidence', [])}
|
| 89 |
+
discussion += '<h2>Retrieved source passages</h2>' + (''.join(
|
| 90 |
+
'<article><h3>' + esc(k) + ' · ' + esc(s['title']) + '</h3><p>' + esc(s['text']) + '</p><p>' + esc(s['url']) + '</p></article>'
|
| 91 |
+
for k, s in sources.items()) or '<p>No documentation was retrieved for this inspection.</p>')
|
| 92 |
+
(output / 'reports' / (identifier + '.html')).write_text(
|
| 93 |
+
'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
| 94 |
+
'<title>Saved DefectRAG example</title><style>body{font:16px system-ui;max-width:900px;margin:30px auto;padding:16px}img{max-width:46%}th,td{padding:6px;text-align:left}@media print{button{display:none}}</style>'
|
| 95 |
+
'<h1>Saved inspection example</h1><p>Previously measured VisA example. No live inference runs on this website.</p>'
|
| 96 |
+
'<p>VisA · Zou et al., ECCV 2022 · CC BY 4.0 · resized images and model overlay. '
|
| 97 |
+
'<a href="https://github.com/amazon-science/spot-diff">Dataset source</a></p>'
|
| 98 |
+
'<button onclick="window.print()">Print / save PDF</button><table>' + table + '</table>'
|
| 99 |
+
f'<h2>Image and measured heatmap</h2><img alt="VisA sample" src="../images/{identifier}.jpg"><img alt="Saved heatmap" src="../images/{identifier}_heatmap.jpg">'
|
| 100 |
+
'<h2>Recorded evidence conversation</h2>' + discussion + '</html>', encoding='utf-8')
|
| 101 |
+
evaluation = json.loads((ROOT / 'results/evaluation.json').read_text())
|
| 102 |
+
evaluation['serving_profile'] = json.loads((ROOT / 'results/serving_profile.json').read_text())
|
| 103 |
+
# These files contain only evaluation metrics/configuration, not private runtime paths.
|
| 104 |
+
data = {'schema': 1, 'mode': 'saved_examples', 'records': records, 'samples': samples,
|
| 105 |
+
'messages': conversations, 'evaluation': evaluation,
|
| 106 |
+
'official_evaluation':json.loads((ROOT/'results/official_evaluation.json').read_text()),
|
| 107 |
+
'attribution': 'VisA · Zou et al., ECCV 2022 · CC BY 4.0 · resized images and model overlays',
|
| 108 |
+
'source': 'https://github.com/amazon-science/spot-diff'}
|
| 109 |
+
candidate=ROOT/'results/highres_evaluation.json'
|
| 110 |
+
if candidate.exists():data['official_evaluation']['candidate']=json.loads(candidate.read_text())
|
| 111 |
+
text = json.dumps(data, indent=2)
|
| 112 |
+
if ':\\' in text or 'Users/' in text or 'localhost' in text or '127.0.0.1' in text:
|
| 113 |
+
raise ValueError('Local path or service address found in public snapshot')
|
| 114 |
+
(output / 'data.json').write_text(text, encoding='utf-8')
|
| 115 |
+
buffer = io.StringIO(newline='')
|
| 116 |
+
writer = csv.DictWriter(buffer, fieldnames=fields, extrasaction='ignore')
|
| 117 |
+
writer.writeheader(); writer.writerows(records)
|
| 118 |
+
(output / 'inspections.csv').write_text(buffer.getvalue(), encoding='utf-8')
|
| 119 |
+
hashes = {p.relative_to(output).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
|
| 120 |
+
for p in sorted(output.rglob('*')) if p.is_file() and p.name != 'manifest.json'}
|
| 121 |
+
(output / 'manifest.json').write_text(json.dumps({'files': hashes, 'records': len(records),
|
| 122 |
+
'provenance': 'allowlisted acceptance + all_categories_acceptance + passed assistant_quality receipts; original saved runtime artifacts; old experiments not repeated'}, indent=2))
|
| 123 |
+
print(json.dumps({'status': 'passed', 'examples': len(records), 'files': len(hashes), 'output': str(output)}))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == '__main__':
|
| 127 |
+
export()
|
scripts/export_showcase_tuned.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rebuild the saved-example showcase from inspections made by the deployed tuned detector.
|
| 2 |
+
|
| 3 |
+
Reads a finished inspection database and its artifacts in read-only mode. It never runs the model and never
|
| 4 |
+
publishes arbitrary uploads: only inspections whose file name is one of the 24 allowlisted VisA samples
|
| 5 |
+
(`<product>_good.jpg` / `<product>_anomalous.jpg`) are exported, with every result kept exactly as measured
|
| 6 |
+
(including the cases the detector got wrong).
|
| 7 |
+
|
| 8 |
+
python -m scripts.export_showcase_tuned --source <folder with inspection.sqlite3 and artifacts/>
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import hashlib
|
| 14 |
+
import html
|
| 15 |
+
import io
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import shutil
|
| 19 |
+
import sqlite3
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
OUTPUT = ROOT / "frontend" / "public" / "showcase"
|
| 24 |
+
FIELDS = [
|
| 25 |
+
"id",
|
| 26 |
+
"created_at",
|
| 27 |
+
"category",
|
| 28 |
+
"verdict",
|
| 29 |
+
"score",
|
| 30 |
+
"threshold",
|
| 31 |
+
"uncertainty_margin",
|
| 32 |
+
"inference_ms",
|
| 33 |
+
"model_id",
|
| 34 |
+
]
|
| 35 |
+
CATEGORIES = [
|
| 36 |
+
"candle",
|
| 37 |
+
"capsules",
|
| 38 |
+
"cashew",
|
| 39 |
+
"chewinggum",
|
| 40 |
+
"fryum",
|
| 41 |
+
"macaroni1",
|
| 42 |
+
"macaroni2",
|
| 43 |
+
"pcb1",
|
| 44 |
+
"pcb2",
|
| 45 |
+
"pcb3",
|
| 46 |
+
"pcb4",
|
| 47 |
+
"pipe_fryum",
|
| 48 |
+
]
|
| 49 |
+
ALLOWED = {f"{c}_{kind}.jpg": (c, kind) for c in CATEGORIES for kind in ("good", "anomalous")}
|
| 50 |
+
ATTRIBUTION = "VisA · Zou et al., ECCV 2022 · CC BY 4.0"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def read_json(relative):
|
| 54 |
+
return json.loads((ROOT / relative).read_text(encoding="utf-8"))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def load_inspections(source):
|
| 58 |
+
database = Path(source) / "inspection.sqlite3"
|
| 59 |
+
with sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) as db:
|
| 60 |
+
payloads = [json.loads(row[0]) for row in db.execute("SELECT payload FROM inspections")]
|
| 61 |
+
chosen = {}
|
| 62 |
+
for payload in sorted(payloads, key=lambda p: p["created_at"]):
|
| 63 |
+
name = payload.get("filename")
|
| 64 |
+
if name in ALLOWED and payload["category"] == ALLOWED[name][0]:
|
| 65 |
+
chosen[name] = payload # the latest run of each sample wins
|
| 66 |
+
missing = sorted(set(ALLOWED) - set(chosen))
|
| 67 |
+
if missing:
|
| 68 |
+
raise ValueError("Missing saved inspections for: " + ", ".join(missing))
|
| 69 |
+
models = {p["model_id"].split("-")[0] + "-" + p["model_id"].split("-")[1] for p in chosen.values()}
|
| 70 |
+
if models != {"dinov2-tuned"}:
|
| 71 |
+
raise ValueError("Expected only inspections by the tuned detector, found: " + ", ".join(sorted(models)))
|
| 72 |
+
return [chosen[name] for name in sorted(chosen)]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def report_page(record, esc):
|
| 76 |
+
table = "".join(f"<tr><th>{esc(k)}</th><td>{esc(record.get(k, ''))}</td></tr>" for k in FIELDS)
|
| 77 |
+
identifier = record["id"]
|
| 78 |
+
return (
|
| 79 |
+
'<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
| 80 |
+
"<title>Saved DefectRAG example</title><style>body{font:16px system-ui;max-width:900px;margin:30px auto;padding:16px}"
|
| 81 |
+
"img{max-width:46%}th,td{padding:6px;text-align:left}@media print{button{display:none}}</style>"
|
| 82 |
+
"<h1>Saved inspection example</h1><p>Previously measured VisA example. No live inference runs on this website.</p>"
|
| 83 |
+
f"<p>{ATTRIBUTION} · resized images and model overlay. "
|
| 84 |
+
'<a href="https://github.com/amazon-science/spot-diff">Dataset source</a></p>'
|
| 85 |
+
'<button onclick="window.print()">Print / save PDF</button><table>' + table + "</table>"
|
| 86 |
+
f'<h2>Image and measured heatmap</h2><img alt="VisA sample" src="../images/{identifier}.jpg">'
|
| 87 |
+
f'<img alt="Saved heatmap" src="../images/{identifier}_heatmap.jpg">'
|
| 88 |
+
"<h2>Recorded evidence conversation</h2><p>No evidence conversation was recorded for this inspection.</p></html>"
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def export(source, output=OUTPUT):
|
| 93 |
+
source = Path(source)
|
| 94 |
+
inspections = load_inspections(source)
|
| 95 |
+
for folder in ("images", "reports"):
|
| 96 |
+
shutil.rmtree(output / folder, ignore_errors=True)
|
| 97 |
+
(output / folder).mkdir(parents=True, exist_ok=True)
|
| 98 |
+
records, samples, conversations = [], [], {}
|
| 99 |
+
esc = lambda value: html.escape(str(value)) # noqa: E731
|
| 100 |
+
for payload in inspections:
|
| 101 |
+
identifier = payload["id"]
|
| 102 |
+
record = {k: payload[k] for k in FIELDS if k in payload}
|
| 103 |
+
record.update(
|
| 104 |
+
batch="Verified VisA examples",
|
| 105 |
+
filename="VisA example",
|
| 106 |
+
image_url=f"showcase/images/{identifier}.jpg",
|
| 107 |
+
heatmap_url=f"showcase/images/{identifier}_heatmap.jpg",
|
| 108 |
+
)
|
| 109 |
+
for suffix in (".jpg", "_heatmap.jpg"):
|
| 110 |
+
shutil.copyfile(source / "artifacts" / (identifier + suffix), output / "images" / (identifier + suffix))
|
| 111 |
+
stem = Path(payload["filename"]).stem
|
| 112 |
+
samples.append(
|
| 113 |
+
{
|
| 114 |
+
"name": stem,
|
| 115 |
+
"category": record["category"],
|
| 116 |
+
"record_id": identifier,
|
| 117 |
+
"url": record["image_url"],
|
| 118 |
+
"attribution": ATTRIBUTION,
|
| 119 |
+
}
|
| 120 |
+
)
|
| 121 |
+
conversations[identifier] = []
|
| 122 |
+
records.append(record)
|
| 123 |
+
(output / "reports" / (identifier + ".html")).write_text(report_page(record, esc), encoding="utf-8")
|
| 124 |
+
evaluation = read_json("results/tuned_deployment_evaluation.json")
|
| 125 |
+
official = read_json("results/official_evaluation.json")
|
| 126 |
+
if (ROOT / "results/highres_evaluation.json").exists():
|
| 127 |
+
official["candidate"] = read_json("results/highres_evaluation.json")
|
| 128 |
+
if (ROOT / "results/mvtec_summary.json").exists():
|
| 129 |
+
official["mvtec"] = read_json("results/mvtec_summary.json")
|
| 130 |
+
data = {
|
| 131 |
+
"schema": 1,
|
| 132 |
+
"mode": "saved_examples",
|
| 133 |
+
"records": records,
|
| 134 |
+
"samples": samples,
|
| 135 |
+
"messages": conversations,
|
| 136 |
+
"evaluation": evaluation,
|
| 137 |
+
"official_evaluation": official,
|
| 138 |
+
"attribution": ATTRIBUTION + " · resized images and model overlays",
|
| 139 |
+
"source": "https://github.com/amazon-science/spot-diff",
|
| 140 |
+
}
|
| 141 |
+
text = json.dumps(data, indent=2)
|
| 142 |
+
if ":\\" in text or "Users/" in text or "localhost" in text or "127.0.0.1" in text:
|
| 143 |
+
raise ValueError("Local path or service address found in public snapshot")
|
| 144 |
+
(output / "data.json").write_text(text, encoding="utf-8")
|
| 145 |
+
buffer = io.StringIO(newline="")
|
| 146 |
+
writer = csv.DictWriter(buffer, fieldnames=FIELDS, extrasaction="ignore")
|
| 147 |
+
writer.writeheader()
|
| 148 |
+
writer.writerows(records)
|
| 149 |
+
(output / "inspections.csv").write_text(buffer.getvalue(), encoding="utf-8")
|
| 150 |
+
hashes = {
|
| 151 |
+
p.relative_to(output).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest()
|
| 152 |
+
for p in sorted(output.rglob("*"))
|
| 153 |
+
if p.is_file() and p.name != "manifest.json"
|
| 154 |
+
}
|
| 155 |
+
(output / "manifest.json").write_text(
|
| 156 |
+
json.dumps(
|
| 157 |
+
{
|
| 158 |
+
"files": hashes,
|
| 159 |
+
"records": len(records),
|
| 160 |
+
"provenance": "24 inspections by the deployed tuned detector (dinov2_tuned_v1); results kept as measured, including misses; no assistant conversations",
|
| 161 |
+
},
|
| 162 |
+
indent=2,
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
print(json.dumps({"status": "passed", "examples": len(records), "files": len(hashes), "output": str(output)}))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if __name__ == "__main__":
|
| 169 |
+
parser = argparse.ArgumentParser()
|
| 170 |
+
parser.add_argument(
|
| 171 |
+
"--source",
|
| 172 |
+
default=str(Path(os.environ.get("TEMP", ".")) / "defectrag-thumb-data"),
|
| 173 |
+
help="folder holding inspection.sqlite3 and artifacts/",
|
| 174 |
+
)
|
| 175 |
+
export(parser.parse_args().source)
|
scripts/fetch_public_assets.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explicit, optional asset download for a fresh source clone; never fit models."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from huggingface_hub import snapshot_download
|
| 5 |
+
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
REPOSITORY='Wizzas/DefectRAG'
|
| 8 |
+
REVISION='bc6bc66c445388cce227bc3851bd602c88386741'
|
| 9 |
+
PATTERNS=['models/encoder_dinov2/*','models/highres/*','models/encoder_dinov2_tuned/*','models/highres_tuned/*','models/embedding/*',
|
| 10 |
+
'models/BGE-LICENSE.txt','samples/*','results/*.json']
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 14 |
+
parser.add_argument('--list',action='store_true',help='List public asset groups; download nothing')
|
| 15 |
+
args=parser.parse_args()
|
| 16 |
+
print(f'Public Space assets: {REPOSITORY} @ {REVISION}')
|
| 17 |
+
print('Groups: '+', '.join(PATTERNS))
|
| 18 |
+
if args.list:
|
| 19 |
+
return
|
| 20 |
+
# Only immutable public assets are downloaded; application code/config and
|
| 21 |
+
# private runtime are not part of this snapshot selection.
|
| 22 |
+
snapshot_download(REPOSITORY,repo_type='space',revision=REVISION,
|
| 23 |
+
allow_patterns=PATTERNS,local_dir=ROOT)
|
| 24 |
+
from backend.vision import sha256
|
| 25 |
+
import json
|
| 26 |
+
cards=list((ROOT/'models/highres').glob('*.json'))
|
| 27 |
+
assert len(cards)==12,'All 12 category cards are required'
|
| 28 |
+
for path in cards:
|
| 29 |
+
card=json.loads(path.read_text())
|
| 30 |
+
assert sha256(path.with_suffix('.npz'))==card['bank_sha256']
|
| 31 |
+
tuned=list((ROOT/'models/highres_tuned').glob('[!P]*.json'))
|
| 32 |
+
assert len(tuned)==12,'All 12 fine-tuned category cards are required'
|
| 33 |
+
for path in tuned:
|
| 34 |
+
card=json.loads(path.read_text())
|
| 35 |
+
assert sha256(path.with_suffix('.npz'))==card['bank_sha256']
|
| 36 |
+
assert sha256(ROOT/'models/encoder_dinov2_tuned/model.safetensors')==card['encoder_sha256']
|
| 37 |
+
print('All 12 bank checksums verified for both profiles (frozen and fine-tuned). No fitting, threshold change or GPU experiment.')
|
| 38 |
+
|
| 39 |
+
if __name__=='__main__':
|
| 40 |
+
main()
|
scripts/mvtec_eval.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One-shot MVTec AD evaluation of three detector arms (needs the GPU). Protocol: docs/MVTEC_EVALUATION.md.
|
| 2 |
+
|
| 3 |
+
python -m scripts.mvtec_eval --smoke --categories bottle # code check on a tiny subset; scores are discarded
|
| 4 |
+
python -m scripts.mvtec_eval # all 15 categories, one run, resumes finished ones
|
| 5 |
+
|
| 6 |
+
Arms (fixed in the protocol before any MVTec score existed):
|
| 7 |
+
A original DINOv2 + random-sample bank (up to 48 foreground + 16 other patches per fit image, cap 32,768)
|
| 8 |
+
B original DINOv2 + 32,768-patch farthest-point coreset
|
| 9 |
+
C VisA-fine-tuned DINOv2 (models/encoder_dinov2_tuned) + the same coreset
|
| 10 |
+
|
| 11 |
+
Nothing is trained or tuned here. Test images are used only for scoring.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import hashlib
|
| 16 |
+
import json
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from PIL import Image
|
| 23 |
+
|
| 24 |
+
from backend.config import ROOT
|
| 25 |
+
from backend.highres import HighResolutionEncoder, foreground_mask, restore_map, score_tokens
|
| 26 |
+
from scripts.benchmark_official import pixel_metrics, rank_metrics
|
| 27 |
+
from scripts.encoder_banks import greedy_coreset
|
| 28 |
+
|
| 29 |
+
DATA = ROOT / "MVTec_AD"
|
| 30 |
+
OUT = ROOT / "experiments" / "mvtec_eval"
|
| 31 |
+
PROTOCOL = ROOT / "docs" / "MVTEC_EVALUATION.md"
|
| 32 |
+
CATEGORIES = (
|
| 33 |
+
"bottle",
|
| 34 |
+
"cable",
|
| 35 |
+
"capsule",
|
| 36 |
+
"carpet",
|
| 37 |
+
"grid",
|
| 38 |
+
"hazelnut",
|
| 39 |
+
"leather",
|
| 40 |
+
"metal_nut",
|
| 41 |
+
"pill",
|
| 42 |
+
"screw",
|
| 43 |
+
"tile",
|
| 44 |
+
"toothbrush",
|
| 45 |
+
"transistor",
|
| 46 |
+
"wood",
|
| 47 |
+
"zipper",
|
| 48 |
+
)
|
| 49 |
+
ARMS = ("A_random_frozen", "B_coreset_frozen", "C_coreset_tuned")
|
| 50 |
+
BANK_SIZE = 32768
|
| 51 |
+
SEED = 42
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sha256_file(path):
|
| 55 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def listing(category):
|
| 59 |
+
base = DATA / category
|
| 60 |
+
train = sorted((base / "train" / "good").glob("*.png"))
|
| 61 |
+
rows = [
|
| 62 |
+
{"image": p, "label": 0, "mask": None, "type": "good"} for p in sorted((base / "test" / "good").glob("*.png"))
|
| 63 |
+
]
|
| 64 |
+
for p in sorted(base.glob("test/*/*.png")):
|
| 65 |
+
if p.parent.name != "good":
|
| 66 |
+
rows.append(
|
| 67 |
+
{
|
| 68 |
+
"image": p,
|
| 69 |
+
"label": 1,
|
| 70 |
+
"mask": base / "ground_truth" / p.parent.name / (p.stem + "_mask.png"),
|
| 71 |
+
"type": p.parent.name,
|
| 72 |
+
}
|
| 73 |
+
)
|
| 74 |
+
return train, rows
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def split_train(paths):
|
| 78 |
+
"""The VisA rule: sort by content hash and hold out every tenth distinct hash for thresholds."""
|
| 79 |
+
keyed = sorted(((sha256_file(p), p.name, p) for p in paths), key=lambda item: item[:2])
|
| 80 |
+
held_hashes = set(sorted({k[0] for k in keyed})[::10])
|
| 81 |
+
held = [k[2] for k in keyed if k[0] in held_hashes]
|
| 82 |
+
fit = sorted((k[2] for k in keyed if k[0] not in held_hashes), key=lambda p: p.name)
|
| 83 |
+
return fit, held
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def encode(encoder, path):
|
| 87 |
+
with Image.open(path) as image:
|
| 88 |
+
tokens, geometry = encoder.encode(image)
|
| 89 |
+
return tokens, foreground_mask(tokens, geometry["grid"]), geometry
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def random_bank(frozen, fit, rng):
|
| 93 |
+
"""Arm A: up to 48 foreground + 16 other patches per fit image; subsample to the cap."""
|
| 94 |
+
parts = []
|
| 95 |
+
for path in fit:
|
| 96 |
+
tokens, mask, _ = encode(frozen, path)
|
| 97 |
+
features = F.normalize(tokens, dim=-1).half()
|
| 98 |
+
foreground, other = np.flatnonzero(mask), np.flatnonzero(~mask)
|
| 99 |
+
chosen = np.r_[
|
| 100 |
+
rng.choice(foreground, min(48, len(foreground)), replace=False),
|
| 101 |
+
rng.choice(other, min(16, len(other)), replace=False),
|
| 102 |
+
].astype(int)
|
| 103 |
+
parts.append(features[torch.as_tensor(chosen, device=features.device)])
|
| 104 |
+
bank = torch.cat(parts)
|
| 105 |
+
if len(bank) > BANK_SIZE:
|
| 106 |
+
bank = bank[torch.as_tensor(rng.choice(len(bank), BANK_SIZE, replace=False), device=bank.device)]
|
| 107 |
+
return bank
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def coreset_bank(encoder, fit):
|
| 111 |
+
"""Arms B and C: greedy farthest-point coreset of every patch of every fit image."""
|
| 112 |
+
parts = [F.normalize(encode(encoder, path)[0], dim=-1).half() for path in fit]
|
| 113 |
+
everything = torch.cat(parts)
|
| 114 |
+
del parts
|
| 115 |
+
chosen = greedy_coreset(everything, min(BANK_SIZE, len(everything)), seed=SEED)
|
| 116 |
+
bank = everything[chosen].clone()
|
| 117 |
+
del everything
|
| 118 |
+
torch.cuda.empty_cache()
|
| 119 |
+
return bank
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def prepared(bank, device):
|
| 123 |
+
return F.normalize(bank.float().to(device), dim=-1)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def score_all(frozen, tuned, banks, path, want_maps):
|
| 127 |
+
"""Scores (and 224x224 maps) of one image for the three arms."""
|
| 128 |
+
out, maps = {}, {}
|
| 129 |
+
tokens, mask, geometry = encode(frozen, path)
|
| 130 |
+
for arm in ("A_random_frozen", "B_coreset_frozen"):
|
| 131 |
+
raw, score = score_tokens(tokens, banks[arm], mask)
|
| 132 |
+
out[arm] = score
|
| 133 |
+
if want_maps:
|
| 134 |
+
maps[arm] = restore_map(raw, geometry, (224, 224)).ravel().astype("float32")
|
| 135 |
+
tokens, mask, geometry = encode(tuned, path)
|
| 136 |
+
raw, score = score_tokens(tokens, banks["C_coreset_tuned"], mask)
|
| 137 |
+
out["C_coreset_tuned"] = score
|
| 138 |
+
if want_maps:
|
| 139 |
+
maps["C_coreset_tuned"] = restore_map(raw, geometry, (224, 224)).ravel().astype("float32")
|
| 140 |
+
return out, maps
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def mask_array(row):
|
| 144 |
+
if row["mask"] is None:
|
| 145 |
+
return np.zeros(224 * 224, dtype=bool)
|
| 146 |
+
with Image.open(row["mask"]) as image:
|
| 147 |
+
return (np.asarray(image.convert("L").resize((224, 224), Image.Resampling.NEAREST)) > 0).ravel()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def run_category(category, frozen, tuned, smoke):
|
| 151 |
+
train, rows = listing(category)
|
| 152 |
+
fit, held = split_train(train)
|
| 153 |
+
if smoke:
|
| 154 |
+
fit, held, rows = fit[:20], held[:4], rows[:: max(1, len(rows) // 10)]
|
| 155 |
+
started = time.perf_counter()
|
| 156 |
+
rng = np.random.default_rng(SEED)
|
| 157 |
+
banks = {
|
| 158 |
+
"A_random_frozen": prepared(random_bank(frozen, fit, rng), frozen.device),
|
| 159 |
+
"B_coreset_frozen": prepared(coreset_bank(frozen, fit), frozen.device),
|
| 160 |
+
"C_coreset_tuned": prepared(coreset_bank(tuned, fit), frozen.device),
|
| 161 |
+
}
|
| 162 |
+
fit_seconds = time.perf_counter() - started
|
| 163 |
+
held_scores = [score_all(frozen, tuned, banks, path, False)[0] for path in held]
|
| 164 |
+
test_scores, pixel_maps = [], {arm: [] for arm in ARMS}
|
| 165 |
+
for row in rows:
|
| 166 |
+
scores, maps = score_all(frozen, tuned, banks, row["image"], True)
|
| 167 |
+
test_scores.append(scores)
|
| 168 |
+
for arm in ARMS:
|
| 169 |
+
pixel_maps[arm].append(maps[arm])
|
| 170 |
+
truth = np.concatenate([mask_array(r) for r in rows])
|
| 171 |
+
labels = [r["label"] for r in rows]
|
| 172 |
+
metrics = {}
|
| 173 |
+
for arm in ARMS:
|
| 174 |
+
values = [s[arm] for s in test_scores]
|
| 175 |
+
metrics[arm] = {**rank_metrics(labels, values)}
|
| 176 |
+
if truth.any():
|
| 177 |
+
metrics[arm].update(pixel_metrics(truth, np.concatenate(pixel_maps[arm])))
|
| 178 |
+
return {
|
| 179 |
+
"category": category,
|
| 180 |
+
"smoke": smoke,
|
| 181 |
+
"protocol_sha256": sha256_file(PROTOCOL),
|
| 182 |
+
"seed": SEED,
|
| 183 |
+
"n_fit": len(fit),
|
| 184 |
+
"n_heldout": len(held),
|
| 185 |
+
"n_test": len(rows),
|
| 186 |
+
"bank_patches": {arm: len(b) for arm, b in banks.items()},
|
| 187 |
+
"seconds_fit": round(fit_seconds, 1),
|
| 188 |
+
"seconds_total": round(time.perf_counter() - started, 1),
|
| 189 |
+
"heldout": {p.name: s for p, s in zip(held, held_scores)},
|
| 190 |
+
"test": {f"{r['type']}/{r['image'].name}": s for r, s in zip(rows, test_scores)},
|
| 191 |
+
"labels": {f"{r['type']}/{r['image'].name}": r["label"] for r in rows},
|
| 192 |
+
"metrics": None if smoke else metrics,
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main():
|
| 197 |
+
parser = argparse.ArgumentParser()
|
| 198 |
+
parser.add_argument("--categories", nargs="+", choices=CATEGORIES, default=list(CATEGORIES))
|
| 199 |
+
parser.add_argument("--smoke", action="store_true", help="tiny subset to check the code; metrics are not stored")
|
| 200 |
+
args = parser.parse_args()
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
frozen = HighResolutionEncoder(ROOT / "models" / "encoder_dinov2")
|
| 203 |
+
tuned = HighResolutionEncoder(ROOT / "models" / "encoder_dinov2_tuned")
|
| 204 |
+
for category in args.categories:
|
| 205 |
+
target = OUT / (f"{category}.smoke.json" if args.smoke else f"{category}.json")
|
| 206 |
+
if target.exists() and not args.smoke:
|
| 207 |
+
print(f"{category}: already done", flush=True)
|
| 208 |
+
continue
|
| 209 |
+
record = run_category(category, frozen, tuned, args.smoke)
|
| 210 |
+
torch.cuda.empty_cache()
|
| 211 |
+
target.write_text(json.dumps(record), encoding="utf-8")
|
| 212 |
+
if args.smoke:
|
| 213 |
+
finite = all(np.isfinite(v) for s in record["test"].values() for v in s.values())
|
| 214 |
+
print(
|
| 215 |
+
f"{category}: smoke run OK in {record['seconds_total']} s | {record['n_fit']} fit, {record['n_test']} test"
|
| 216 |
+
f" | banks {record['bank_patches']} | all scores finite: {finite} (scores discarded)",
|
| 217 |
+
flush=True,
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
m = record["metrics"]
|
| 221 |
+
print(
|
| 222 |
+
f"{category}: {record['seconds_total']} s | image AUROC "
|
| 223 |
+
+ " ".join(f"{arm.split('_')[0]} {m[arm]['auroc']:.3f}" for arm in ARMS),
|
| 224 |
+
flush=True,
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
main()
|
scripts/mvtec_report.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Report for the one-shot MVTec AD evaluation (CPU only; run scripts.mvtec_eval first). Protocol: docs/MVTEC_EVALUATION.md.
|
| 2 |
+
|
| 3 |
+
python -m scripts.mvtec_report
|
| 4 |
+
|
| 5 |
+
Image AUROC (primary), pixel AUROC and image average precision per category and macro mean, paired bootstrap 95%
|
| 6 |
+
intervals for the differences B-A, C-B and C-A, and descriptive operating points at the q95 threshold of the held-out
|
| 7 |
+
normals (same rule for every category). Results are written to results/mvtec_eval.json.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
from backend.config import ROOT
|
| 15 |
+
from scripts.diagnose_encoder import auroc
|
| 16 |
+
from scripts.encoder_candidates_report import bootstrap_difference
|
| 17 |
+
from scripts.mvtec_eval import ARMS, CATEGORIES, OUT
|
| 18 |
+
|
| 19 |
+
RESULT = ROOT / "results" / "mvtec_eval.json"
|
| 20 |
+
SUMMARY = ROOT / "results" / "mvtec_summary.json"
|
| 21 |
+
PROTOCOL_URL = "https://github.com/WAYTECHG/DefectRAG/blob/main/docs/MVTEC_EVALUATION.md"
|
| 22 |
+
LABELS = {
|
| 23 |
+
"A_random_frozen": "Random-sample memory",
|
| 24 |
+
"B_coreset_frozen": "Coreset memory",
|
| 25 |
+
"C_coreset_tuned": "Coreset + fine-tuned encoder",
|
| 26 |
+
}
|
| 27 |
+
PAIRS = (
|
| 28 |
+
("B_coreset_frozen", "A_random_frozen"),
|
| 29 |
+
("C_coreset_tuned", "B_coreset_frozen"),
|
| 30 |
+
("C_coreset_tuned", "A_random_frozen"),
|
| 31 |
+
)
|
| 32 |
+
SHORT = {"A_random_frozen": "A", "B_coreset_frozen": "B", "C_coreset_tuned": "C"}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def main():
|
| 36 |
+
rng = np.random.default_rng(2027)
|
| 37 |
+
report = {}
|
| 38 |
+
for category in CATEGORIES:
|
| 39 |
+
path = OUT / f"{category}.json"
|
| 40 |
+
if not path.exists():
|
| 41 |
+
continue
|
| 42 |
+
record = json.loads(path.read_text(encoding="utf-8"))
|
| 43 |
+
names = sorted(record["test"])
|
| 44 |
+
labels = np.array([record["labels"][n] for n in names])
|
| 45 |
+
scores = {arm: np.array([record["test"][n][arm] for n in names]) for arm in ARMS}
|
| 46 |
+
entry = {
|
| 47 |
+
"n_test": len(names),
|
| 48 |
+
"n_fit": record["n_fit"],
|
| 49 |
+
"n_heldout": record["n_heldout"],
|
| 50 |
+
"arms": {},
|
| 51 |
+
"differences": {},
|
| 52 |
+
}
|
| 53 |
+
for arm in ARMS:
|
| 54 |
+
held = np.array([s[arm] for s in record["heldout"].values()])
|
| 55 |
+
threshold = float(np.quantile(held, 0.95))
|
| 56 |
+
values = scores[arm]
|
| 57 |
+
metrics = record["metrics"][arm]
|
| 58 |
+
entry["arms"][arm] = {
|
| 59 |
+
"auroc": auroc(values[labels == 1], values[labels == 0]),
|
| 60 |
+
"pixel_auroc": metrics.get("pixel_auroc"),
|
| 61 |
+
"average_precision": metrics["average_precision"],
|
| 62 |
+
"recall_q95": float((values[labels == 1] >= threshold).mean()),
|
| 63 |
+
"false_alarm_q95": float((values[labels == 0] >= threshold).mean()),
|
| 64 |
+
}
|
| 65 |
+
for better, base in PAIRS:
|
| 66 |
+
low, high = bootstrap_difference(labels, scores[better], scores[base], rng)
|
| 67 |
+
entry["differences"][f"{SHORT[better]}-{SHORT[base]}"] = [float(low), float(high)]
|
| 68 |
+
report[category] = entry
|
| 69 |
+
categories = list(report)
|
| 70 |
+
RESULT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 71 |
+
write_summary(report, categories)
|
| 72 |
+
|
| 73 |
+
def mark(interval):
|
| 74 |
+
return " ▲" if interval[0] > 0 else " ▼" if interval[1] < 0 else " "
|
| 75 |
+
|
| 76 |
+
print(
|
| 77 |
+
f"Categories scored: {len(categories)} of {len(CATEGORIES)} (▲/▼ = clearly better/worse by paired bootstrap)\n"
|
| 78 |
+
)
|
| 79 |
+
print(
|
| 80 |
+
f"{'category':<11}{'A random':>10}{'B coreset':>12}{'C tuned':>11} {'B-A':>5}{'C-B':>5}{'C-A':>5} pixel AUROC A / B / C"
|
| 81 |
+
)
|
| 82 |
+
for category in categories:
|
| 83 |
+
a = report[category]["arms"]
|
| 84 |
+
d = report[category]["differences"]
|
| 85 |
+
pixel = " / ".join(f"{a[arm]['pixel_auroc']:.3f}" for arm in ARMS)
|
| 86 |
+
print(
|
| 87 |
+
f"{category:<11}"
|
| 88 |
+
+ "".join(
|
| 89 |
+
f"{a[arm]['auroc']:>10.3f}" if i == 0 else f"{a[arm]['auroc']:>11.3f}" for i, arm in enumerate(ARMS)
|
| 90 |
+
)
|
| 91 |
+
+ f" {mark(d['B-A']):>5}{mark(d['C-B']):>5}{mark(d['C-A']):>5} {pixel}"
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def macro(arm, key):
|
| 95 |
+
return float(np.mean([report[c]["arms"][arm][key] for c in categories]))
|
| 96 |
+
|
| 97 |
+
print()
|
| 98 |
+
print(
|
| 99 |
+
f"{'MACRO MEAN':<11}"
|
| 100 |
+
+ "".join(
|
| 101 |
+
f"{macro(arm, 'auroc'):>10.3f}" if i == 0 else f"{macro(arm, 'auroc'):>11.3f}" for i, arm in enumerate(ARMS)
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
print("macro pixel AUROC: " + " ".join(f"{SHORT[arm]} {macro(arm, 'pixel_auroc'):.3f}" for arm in ARMS))
|
| 105 |
+
print("macro image AP: " + " ".join(f"{SHORT[arm]} {macro(arm, 'average_precision'):.3f}" for arm in ARMS))
|
| 106 |
+
print(
|
| 107 |
+
"q95 recall / false alarms (macro): "
|
| 108 |
+
+ " ".join(
|
| 109 |
+
f"{SHORT[arm]} {macro(arm, 'recall_q95'):.0%} / {macro(arm, 'false_alarm_q95'):.0%}" for arm in ARMS
|
| 110 |
+
)
|
| 111 |
+
)
|
| 112 |
+
for pair in ("B-A", "C-B", "C-A"):
|
| 113 |
+
better = sum(1 for c in categories if report[c]["differences"][pair][0] > 0)
|
| 114 |
+
worse = sum(1 for c in categories if report[c]["differences"][pair][1] < 0)
|
| 115 |
+
print(f"{pair}: clearly better in {better}, clearly worse in {worse} of {len(categories)} categories")
|
| 116 |
+
print(
|
| 117 |
+
"\nWritten to results/mvtec_eval.json. Descriptive; one run on a mirror copy of MVTec AD (docs/MVTEC_EVALUATION.md)."
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def write_summary(report, categories):
|
| 122 |
+
"""A compact file for the dashboard's Official benchmark page (macro means, per-product AUROC, clear differences)."""
|
| 123 |
+
keys = ("auroc", "average_precision", "pixel_auroc", "recall_q95", "false_alarm_q95")
|
| 124 |
+
macro = {arm: {k: float(np.mean([report[c]["arms"][arm][k] for c in categories])) for k in keys} for arm in ARMS}
|
| 125 |
+
comparisons = {
|
| 126 |
+
pair: {
|
| 127 |
+
"better": sum(1 for c in categories if report[c]["differences"][pair][0] > 0),
|
| 128 |
+
"worse": sum(1 for c in categories if report[c]["differences"][pair][1] < 0),
|
| 129 |
+
}
|
| 130 |
+
for pair in ("B-A", "C-B", "C-A")
|
| 131 |
+
}
|
| 132 |
+
summary = {
|
| 133 |
+
"dataset": "MVTec AD",
|
| 134 |
+
"scope": (
|
| 135 |
+
"One offline run on 15 products the detector was never built for. Each product's memory comes from its own "
|
| 136 |
+
"normal training photos; thresholds are the 95th percentile of held-out normal scores. These products are "
|
| 137 |
+
"not available for inspection in this app."
|
| 138 |
+
),
|
| 139 |
+
"protocol_url": PROTOCOL_URL,
|
| 140 |
+
"arms": [{"key": arm, "label": LABELS[arm]} for arm in ARMS],
|
| 141 |
+
"products": len(categories),
|
| 142 |
+
"test_images": int(sum(report[c]["n_test"] for c in categories)),
|
| 143 |
+
"macro_mean": macro,
|
| 144 |
+
"comparisons": comparisons,
|
| 145 |
+
"categories": {
|
| 146 |
+
c: {"n_test": report[c]["n_test"], "arms": report[c]["arms"], "differences": report[c]["differences"]}
|
| 147 |
+
for c in categories
|
| 148 |
+
},
|
| 149 |
+
}
|
| 150 |
+
SUMMARY.write_text(json.dumps(summary, indent=2), encoding="utf-8")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|
scripts/package_benchmark.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preserve completed official experiment assets, without rerunning a model."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import zipfile
|
| 6 |
+
import argparse
|
| 7 |
+
from backend.config import ROOT,CATEGORIES
|
| 8 |
+
|
| 9 |
+
def digest(path):
|
| 10 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 11 |
+
|
| 12 |
+
if __name__=='__main__':
|
| 13 |
+
parser=argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument('--experiment',choices=['official_visa_v1','dinov2_highres_v1'],default='official_visa_v1')
|
| 15 |
+
parser.add_argument('--name',default='DefectRAG-official-benchmark-assets.zip')
|
| 16 |
+
args=parser.parse_args()
|
| 17 |
+
if Path(args.name).name!=args.name or not args.name.endswith('.zip'):raise ValueError('Use a ZIP basename')
|
| 18 |
+
source=ROOT/'experiments'/args.experiment
|
| 19 |
+
archive=ROOT.parent/args.name
|
| 20 |
+
if archive.exists():raise FileExistsError('Earlier archive preserved: '+str(archive))
|
| 21 |
+
for category in CATEGORIES:
|
| 22 |
+
receipt=json.loads((source/category/'complete.json').read_text())
|
| 23 |
+
assert receipt['status']=='passed'
|
| 24 |
+
for name,expected in receipt['files'].items():
|
| 25 |
+
assert digest(source/category/name)==expected,(category,name)
|
| 26 |
+
paths=sorted(p for p in source.rglob('*') if p.is_file() and not set(p.relative_to(source).parts)&{'features','maps'})
|
| 27 |
+
manifest={p.relative_to(source).as_posix():digest(p) for p in paths}
|
| 28 |
+
with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=3) as output:
|
| 29 |
+
for path in paths:output.write(path,'experiments/'+args.experiment+'/'+path.relative_to(source).as_posix())
|
| 30 |
+
output.writestr('BENCHMARK_MANIFEST.json',json.dumps(manifest,indent=2))
|
| 31 |
+
with zipfile.ZipFile(archive) as output:
|
| 32 |
+
assert output.testzip() is None
|
| 33 |
+
for name,expected in manifest.items():
|
| 34 |
+
assert hashlib.sha256(output.read('experiments/'+args.experiment+'/'+name)).hexdigest()==expected
|
| 35 |
+
receipt={'status':'passed','archive':archive.name,'bytes':archive.stat().st_size,'sha256':digest(archive),
|
| 36 |
+
'categories':len(CATEGORIES),'files':len(paths)+1,'crc_and_hashes':'passed',
|
| 37 |
+
'restore':'Extract into project root; experiments/'+args.experiment+' appears. Do not overwrite newer experiments.',
|
| 38 |
+
'intermediate_caches':'Feature caches/maps retained on the workstation; not duplicated in this artifact',
|
| 39 |
+
'scope':'experimental banks, official split manifests, calibration, predictions, metrics; no source images or user history'}
|
| 40 |
+
archive.with_suffix('.receipt.json').write_text(json.dumps(receipt,indent=2))
|
| 41 |
+
print(json.dumps(receipt,indent=2),flush=True)
|
scripts/package_release.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a clean release with file hashes, then verify and optionally extract it.
|
| 2 |
+
Never modifies model assets, datasets, earlier ZIPs or an existing extraction.
|
| 3 |
+
"""
|
| 4 |
+
import argparse
|
| 5 |
+
from datetime import datetime, timezone
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import subprocess
|
| 10 |
+
import zipfile
|
| 11 |
+
|
| 12 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 13 |
+
EXCLUDED_PARTS={'node_modules','__pycache__','.pytest_cache','.git','runtime','development-support','.venv','.cache'}
|
| 14 |
+
HISTORICAL={'DEVELOPMENT_PROGRESS.previous.md','PAUSE_CHECKPOINT_20261016.md','acceptance_checkpoint.json',
|
| 15 |
+
'rag_diagnostic.json','scope_diagnostic.json','pause_processes.json'}
|
| 16 |
+
ROOT_FILES={'README.md','LICENSE','DEVELOPMENT_PROGRESS.md','.env.example','.gitignore','.dockerignore',
|
| 17 |
+
'requirements.txt','requirements-anomalib.txt','Start-DefectRAG.ps1','Start-DefectRAG.cmd','Dockerfile','compose.yaml','render.yaml'}
|
| 18 |
+
ROOT_DIRS={'backend','scripts','tests','knowledge','models','samples','results','docs','deployment','.vscode'}
|
| 19 |
+
|
| 20 |
+
def digest(path):
|
| 21 |
+
h=hashlib.sha256()
|
| 22 |
+
with path.open('rb') as stream:
|
| 23 |
+
for block in iter(lambda:stream.read(1024*1024),b''):h.update(block)
|
| 24 |
+
return h.hexdigest()
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
parser=argparse.ArgumentParser()
|
| 28 |
+
parser.add_argument('--name',default='DefectRAG-v2.zip')
|
| 29 |
+
parser.add_argument('--extract',action='store_true')
|
| 30 |
+
args=parser.parse_args()
|
| 31 |
+
if Path(args.name).name!=args.name or not args.name.endswith('.zip'):raise ValueError('Use a ZIP basename')
|
| 32 |
+
archive=ROOT.parent/args.name
|
| 33 |
+
if archive.exists():raise FileExistsError('Earlier archive preserved: '+str(archive))
|
| 34 |
+
paths=[]
|
| 35 |
+
for p in ROOT.rglob('*'):
|
| 36 |
+
if not p.is_file():continue
|
| 37 |
+
relative=p.relative_to(ROOT)
|
| 38 |
+
if set(relative.parts)&EXCLUDED_PARTS or p.name in HISTORICAL:continue
|
| 39 |
+
if p.name.startswith('.env') and p.name!='.env.example':continue
|
| 40 |
+
if p.suffix in {'.pyc','.zip','.bundle','.tar'} or '.sqlite' in p.name:continue
|
| 41 |
+
if len(relative.parts)==1:
|
| 42 |
+
include=p.name in ROOT_FILES
|
| 43 |
+
elif relative.parts[0]=='frontend':
|
| 44 |
+
include=relative.parts[1] in {'src','dist','dist-static','tests','public','package.json','package-lock.json','index.html','vite.config.js','vercel.json'}
|
| 45 |
+
else:include=relative.parts[0] in ROOT_DIRS
|
| 46 |
+
if include:paths.append(p)
|
| 47 |
+
required={'models/encoder/model.safetensors','models/embedding/model.safetensors','knowledge/index/index.npz',
|
| 48 |
+
'frontend/dist/index.html','results/software-tests.xml','README.md','docs/VERIFICATION_REPORT.md'}
|
| 49 |
+
names={p.relative_to(ROOT).as_posix() for p in paths}
|
| 50 |
+
if not required<=names:raise RuntimeError('Missing required release files: '+str(required-names))
|
| 51 |
+
manifest={'schema':1,'created_utc':datetime.now(timezone.utc).isoformat(),
|
| 52 |
+
'git_commit':subprocess.check_output(['git','-C',str(ROOT),'rev-parse','HEAD'],text=True).strip(),
|
| 53 |
+
'files':[{'path':p.relative_to(ROOT).as_posix(),'bytes':p.stat().st_size,'sha256':digest(p)} for p in sorted(paths)]}
|
| 54 |
+
manifest_path=ROOT/'RELEASE_MANIFEST.json';manifest_path.write_text(json.dumps(manifest,indent=2))
|
| 55 |
+
with zipfile.ZipFile(archive,'x',zipfile.ZIP_DEFLATED,compresslevel=3) as zipped:
|
| 56 |
+
for p in paths+[manifest_path]:zipped.write(p,'DefectRAG-v2/'+p.relative_to(ROOT).as_posix())
|
| 57 |
+
with zipfile.ZipFile(archive) as zipped:
|
| 58 |
+
assert zipped.testzip() is None
|
| 59 |
+
assert len(zipped.namelist())==len(set(zipped.namelist()))
|
| 60 |
+
for item in manifest['files']:
|
| 61 |
+
content=zipped.read('DefectRAG-v2/'+item['path'])
|
| 62 |
+
assert hashlib.sha256(content).hexdigest()==item['sha256']
|
| 63 |
+
extraction=None
|
| 64 |
+
if args.extract:
|
| 65 |
+
extraction=ROOT.parent/('release-verification-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
|
| 66 |
+
extraction.mkdir(exist_ok=False)
|
| 67 |
+
for name in zipped.namelist():
|
| 68 |
+
if not (extraction/name).resolve().is_relative_to(extraction.resolve()):raise ValueError('Unsafe archive entry')
|
| 69 |
+
zipped.extractall(extraction)
|
| 70 |
+
receipt={'archive':str(archive),'bytes':archive.stat().st_size,'sha256':digest(archive),
|
| 71 |
+
'file_count':len(paths)+1,'crc_and_file_hashes':'passed','duplicate_entries':False,
|
| 72 |
+
'git_commit':manifest['git_commit'],'extracted_project':str(extraction/'DefectRAG-v2') if extraction else None}
|
| 73 |
+
archive.with_suffix('.receipt.json').write_text(json.dumps(receipt,indent=2))
|
| 74 |
+
print(json.dumps(receipt,indent=2),flush=True)
|
| 75 |
+
if __name__=='__main__':main()
|
scripts/package_showcase.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Package the already built static showcase; preserve every earlier archive."""
|
| 2 |
+
import argparse
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
import zipfile
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument('--name', default='DefectRAG-v2-static.zip')
|
| 15 |
+
args = parser.parse_args()
|
| 16 |
+
if Path(args.name).name != args.name or not args.name.endswith('.zip'):
|
| 17 |
+
raise ValueError('Use a ZIP basename')
|
| 18 |
+
output = ROOT / 'frontend/dist-static'
|
| 19 |
+
if not (output / 'index.html').exists():
|
| 20 |
+
raise RuntimeError('Run npm run build:showcase inside frontend first')
|
| 21 |
+
archive = ROOT.parent / args.name
|
| 22 |
+
if archive.exists():
|
| 23 |
+
raise FileExistsError('Earlier archive preserved: ' + str(archive))
|
| 24 |
+
shutil.copyfile(ROOT / 'deployment/STATIC_SPACE.md', output / 'README.md')
|
| 25 |
+
shutil.copyfile(ROOT / 'LICENSE', output / 'LICENSE')
|
| 26 |
+
shutil.copyfile(ROOT / 'docs/THIRD_PARTY_NOTICES.md', output / 'THIRD_PARTY_NOTICES.md')
|
| 27 |
+
paths = sorted(p for p in output.rglob('*') if p.is_file())
|
| 28 |
+
with zipfile.ZipFile(archive, 'x', zipfile.ZIP_DEFLATED) as zipped:
|
| 29 |
+
for path in paths:
|
| 30 |
+
zipped.write(path, path.relative_to(output).as_posix())
|
| 31 |
+
with zipfile.ZipFile(archive) as zipped:
|
| 32 |
+
if zipped.testzip() is not None:
|
| 33 |
+
raise RuntimeError('Archive CRC failure')
|
| 34 |
+
for path in paths:
|
| 35 |
+
if zipped.read(path.relative_to(output).as_posix()) != path.read_bytes():
|
| 36 |
+
raise RuntimeError('Archived file mismatch')
|
| 37 |
+
receipt = {'status': 'passed', 'archive': str(archive), 'bytes': archive.stat().st_size,
|
| 38 |
+
'sha256': hashlib.sha256(archive.read_bytes()).hexdigest(), 'files': len(paths),
|
| 39 |
+
'mode': 'read-only saved real examples; no server, model download or secret required'}
|
| 40 |
+
archive.with_suffix('.receipt.json').write_text(json.dumps(receipt, indent=2))
|
| 41 |
+
print(json.dumps(receipt, indent=2))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == '__main__':
|
| 45 |
+
main()
|
scripts/prepare_assets.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copy only existing, selected public model files; never copy credentials or history."""
|
| 2 |
+
import argparse
|
| 3 |
+
import shutil
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from backend.config import ROOT
|
| 7 |
+
from backend.vision import sha256
|
| 8 |
+
|
| 9 |
+
def copy_tree(source,destination,names):
|
| 10 |
+
destination.mkdir(parents=True,exist_ok=True)
|
| 11 |
+
for name in names:
|
| 12 |
+
path=source/name
|
| 13 |
+
if path.is_file(): shutil.copyfile(path,destination/name)
|
| 14 |
+
if (source/'1_Pooling'/'config.json').exists():
|
| 15 |
+
(destination/'1_Pooling').mkdir(exist_ok=True)
|
| 16 |
+
shutil.copyfile(source/'1_Pooling'/'config.json',destination/'1_Pooling'/'config.json')
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
parser=argparse.ArgumentParser()
|
| 20 |
+
parser.add_argument('--encoder',type=Path,required=True)
|
| 21 |
+
parser.add_argument('--embedding',type=Path,required=True)
|
| 22 |
+
args=parser.parse_args()
|
| 23 |
+
copy_tree(args.encoder,ROOT/'models'/'encoder',['config.json','preprocessor_config.json','model.safetensors'])
|
| 24 |
+
copy_tree(args.embedding,ROOT/'models'/'embedding',['config.json','model.safetensors','config_sentence_transformers.json','modules.json','sentence_bert_config.json','special_tokens_map.json','tokenizer_config.json','tokenizer.json','vocab.txt','README.md'])
|
| 25 |
+
checksums={str(p.relative_to(ROOT)).replace('\\','/'):sha256(p) for p in (ROOT/'models').rglob('*') if p.is_file()}
|
| 26 |
+
(ROOT/'models'/'checksums.json').write_text(json.dumps(checksums,indent=2))
|
| 27 |
+
print('Copied cached public model assets, without modifying source files.')
|
| 28 |
+
if __name__=='__main__':main()
|
scripts/prepare_dinov2.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fetch only public DINOv2 tensor/config assets into a separate local directory."""
|
| 2 |
+
import json
|
| 3 |
+
from urllib.request import urlopen
|
| 4 |
+
from huggingface_hub import HfApi,snapshot_download
|
| 5 |
+
from backend.config import ROOT
|
| 6 |
+
from backend.vision import sha256
|
| 7 |
+
|
| 8 |
+
if __name__=='__main__':
|
| 9 |
+
destination=ROOT/'models/encoder_dinov2'
|
| 10 |
+
destination.mkdir(parents=True,exist_ok=True)
|
| 11 |
+
license_path=destination/'LICENSE'
|
| 12 |
+
if not license_path.exists():
|
| 13 |
+
with urlopen('https://raw.githubusercontent.com/facebookresearch/dinov2/main/LICENSE',timeout=30) as response:
|
| 14 |
+
license_path.write_bytes(response.read())
|
| 15 |
+
receipt=destination/'ASSET_RECEIPT.json'
|
| 16 |
+
if receipt.exists():
|
| 17 |
+
saved=json.loads(receipt.read_text())
|
| 18 |
+
assert sha256(destination/'model.safetensors')==saved['model_sha256']
|
| 19 |
+
print('Preserved existing verified DINOv2 asset.');raise SystemExit(0)
|
| 20 |
+
info=HfApi().model_info('facebook/dinov2-small')
|
| 21 |
+
snapshot_download('facebook/dinov2-small',revision=info.sha,local_dir=destination,
|
| 22 |
+
cache_dir=ROOT/'runtime/model-download-cache',
|
| 23 |
+
allow_patterns=['config.json','model.safetensors','preprocessor_config.json','README.md','LICENSE'])
|
| 24 |
+
receipt.write_text(json.dumps({'repo':'facebook/dinov2-small','revision':info.sha,
|
| 25 |
+
'model_sha256':sha256(destination/'model.safetensors'),'license':'Apache-2.0',
|
| 26 |
+
'source':'https://huggingface.co/facebook/dinov2-small','remote_code':False},indent=2))
|
| 27 |
+
print(receipt.read_text(),flush=True)
|
scripts/prepare_github_export.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a small source-only GitHub upload folder; never copy private state/history."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import shutil
|
| 7 |
+
import subprocess
|
| 8 |
+
|
| 9 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 10 |
+
DIRECTORIES=('backend/','scripts/','tests/','deployment/','knowledge/','frontend/src/',
|
| 11 |
+
'frontend/tests/','frontend/public/')
|
| 12 |
+
PUBLIC_DOCS={
|
| 13 |
+
'docs/SETUP.md','docs/SECURITY.md','docs/ARCHITECTURE.md','docs/STAFF_QUICK_GUIDE.md',
|
| 14 |
+
'docs/GUIDED_PRACTICE.md','docs/ACCURACY_AND_METRICS.md','docs/ACCURACY_RESULTS.md',
|
| 15 |
+
'docs/TRAINING_AND_EVALUATION.md','docs/MACARONI_RECALL_UPDATE.md',
|
| 16 |
+
'docs/SENSITIVITY_CALIBRATION.md','docs/THIRD_PARTY_NOTICES.md',
|
| 17 |
+
'docs/FRONTEND_LICENSES.txt','docs/GITHUB_PUBLISHING.md',
|
| 18 |
+
'docs/assets/hero.svg','docs/assets/dashboard.png','docs/assets/guided-practice.png',
|
| 19 |
+
'docs/assets/macaroni-recall.png','docs/assets/recall-policy.png',
|
| 20 |
+
}
|
| 21 |
+
FILES={'README.md','LICENSE','.gitignore','.dockerignore','.env.example','requirements.txt',
|
| 22 |
+
'requirements-anomalib.txt','Dockerfile','compose.yaml','render.yaml',
|
| 23 |
+
'Start-DefectRAG.cmd','Start-DefectRAG.ps1','frontend/package.json',
|
| 24 |
+
'frontend/package-lock.json','frontend/index.html','frontend/vite.config.js','frontend/localBuild.mjs',
|
| 25 |
+
'results/evaluation.json','results/official_evaluation.json','results/highres_evaluation.json',
|
| 26 |
+
'results/highres_deployment_evaluation.json','results/highres_comparison.json','results/highres_comparison.csv'}
|
| 27 |
+
FILES.update({'results/sensitive_deployment_evaluation.json','results/recall_threshold_audit.json',
|
| 28 |
+
'results/macaroni_recall_deployment_evaluation.json'})
|
| 29 |
+
FILES.update(PUBLIC_DOCS)
|
| 30 |
+
EXCLUDED=('knowledge/index/','frontend/public/config.js','docs/README_LEGACY.md',
|
| 31 |
+
'docs/SUPABASE_QUERY_CATALOG.md','docs/QA_ACCOUNT_REMOVAL.md',
|
| 32 |
+
'deployment/qa_account_backup_PRIVATE.sql','deployment/qa_account_cleanup_REVIEW_ONLY.sql',
|
| 33 |
+
'deployment/qa_account_deletion_preflight.sql','deployment/email_pending_qa_verification.sql',
|
| 34 |
+
'deployment/email_single_qa_verification.sql',
|
| 35 |
+
'deployment/Update-GitHub.ps1',
|
| 36 |
+
'deployment/corrective_actions_fresh_sink_result.sql',
|
| 37 |
+
'deployment/corrective_actions_replacement_sink_result.sql',
|
| 38 |
+
'deployment/corrective_actions_single_sink_metadata.sql',
|
| 39 |
+
'deployment/corrective_actions_single_sink_result.sql',
|
| 40 |
+
'deployment/email_qa_selection.sql','deployment/email_clock_where_fix_verification.sql',
|
| 41 |
+
'deployment/email_no_send_live_preflight.sql',
|
| 42 |
+
'scripts/checkpoint.py','scripts/package_release.py','scripts/sync_release.py',
|
| 43 |
+
'scripts/verify_packaged.py','scripts/verify_highres_preservation.py',
|
| 44 |
+
'scripts/verify_upgrade_preservation.py')
|
| 45 |
+
|
| 46 |
+
def selected(name):
|
| 47 |
+
return (name in FILES or name.startswith(DIRECTORIES)) and not name.startswith(EXCLUDED) and Path(name).suffix not in ('.sqlite','.npz','.safetensors','.pt','.zip','.log')
|
| 48 |
+
|
| 49 |
+
def main():
|
| 50 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 51 |
+
parser.add_argument('--output',type=Path,default=ROOT/'development-support/github-ready/DefectRAG')
|
| 52 |
+
args=parser.parse_args()
|
| 53 |
+
output=args.output.resolve()
|
| 54 |
+
assert output.is_relative_to(ROOT/'development-support'),'Keep exports under development-support.'
|
| 55 |
+
assert not output.exists(),'Choose a new empty export destination; existing exports are preserved.'
|
| 56 |
+
paths=subprocess.check_output(['git','ls-files','-z'],cwd=ROOT).decode().split('\0')
|
| 57 |
+
copied=[]
|
| 58 |
+
for name in filter(None,paths):
|
| 59 |
+
if not selected(name):continue
|
| 60 |
+
path=ROOT/name
|
| 61 |
+
if not path.is_file() or path.is_symlink():continue
|
| 62 |
+
if path.stat().st_size>15*1024*1024:raise ValueError('Unexpected large tracked file: '+name)
|
| 63 |
+
target=output/name
|
| 64 |
+
target.parent.mkdir(parents=True,exist_ok=True)
|
| 65 |
+
shutil.copy2(path,target)
|
| 66 |
+
copied.append(name)
|
| 67 |
+
config=output/'frontend/public/config.js'
|
| 68 |
+
config.parent.mkdir(parents=True,exist_ok=True)
|
| 69 |
+
config.write_text('window.DEFECTRAG_PUBLIC_CONFIG = {supabaseUrl:"",supabasePublishableKey:""};\n')
|
| 70 |
+
credential=re.compile(r'hf_[A-Za-z0-9]{25,}|sb_secret_[A-Za-z0-9_-]{20,}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}')
|
| 71 |
+
for path in output.rglob('*'):
|
| 72 |
+
if path.is_file() and (path.suffix in ('.py','.js','.jsx','.mjs','.json','.md','.txt','.html','.sql','.ps1','.yaml','.yml','.toml') or path.name=='.env.example'):
|
| 73 |
+
assert not credential.search(path.read_text(encoding='utf8',errors='replace')),'Credential-like value requires review: '+str(path.relative_to(output))
|
| 74 |
+
assert not any((output/name).exists() for name in ('models','runtime','experiments','.venv','.git','.env','DEVELOPMENT_PROGRESS.md'))
|
| 75 |
+
manifest={'source_commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip(),
|
| 76 |
+
'files':len(copied)+1,'public_config_blank':True,
|
| 77 |
+
'excluded':'Git history, models, datasets, private runtime, environments, local evidence, secrets, build outputs'}
|
| 78 |
+
# Export receipts belong to the private preparation folder, not the public tree.
|
| 79 |
+
receipt=output.parent/(output.name+'.export.json')
|
| 80 |
+
assert not receipt.exists(),'Earlier export receipt preserved.'
|
| 81 |
+
receipt.write_text(json.dumps(manifest,indent=2))
|
| 82 |
+
print(json.dumps({'folder':str(output),**manifest}))
|
| 83 |
+
|
| 84 |
+
if __name__=='__main__':
|
| 85 |
+
main()
|
scripts/prepare_knowledge.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from backend.config import Settings
|
| 2 |
+
from backend.rag import KnowledgeIndex
|
| 3 |
+
|
| 4 |
+
if __name__=='__main__':
|
| 5 |
+
settings=Settings()
|
| 6 |
+
index=KnowledgeIndex(settings.root,settings.root/'knowledge'/'index')
|
| 7 |
+
index.ensure()
|
| 8 |
+
print('Indexed',len(index.documents),'source-attributed passages')
|
scripts/prepare_macaroni_recall.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Macaroni-only q80 calibration from cached normal scores; no GPU or refitting."""
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
import json
|
| 4 |
+
from scripts.audit_recall import ROOT, digest, metrics, quantile
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
source=ROOT/'results/sensitive_deployment_evaluation.json'
|
| 9 |
+
baseline=json.loads(source.read_text())
|
| 10 |
+
candidate=deepcopy(baseline)
|
| 11 |
+
candidate.update(decision_policy='macaroni-recall-v1',
|
| 12 |
+
protocol='Same frozen DINOv2 banks and official VisA assignments. Macaroni1/2 use the fixed linear 80th percentile of held-out training-normal scores; the other ten products retain their q95 policy. Higher recall with substantially more false alarms. Retrospective development evaluation, not independent validation.',
|
| 13 |
+
decision_policy_reason='User authorized focusing only on Macaroni1/2 recall, prioritizing anomaly detection with more false alarms and minimal compute.',
|
| 14 |
+
policy_selection_context='Operating policy adopted after examining development-exposed test-score diagnostics. Numeric thresholds use normal calibration only; no test-optimal threshold search or independent-validation claim.',
|
| 15 |
+
previous_evaluation_sha256=digest(source))
|
| 16 |
+
for category in ('macaroni1','macaroni2'):
|
| 17 |
+
directory=ROOT/'experiments/dinov2_highres_v1'/category
|
| 18 |
+
calibration=json.loads((directory/'normal_calibration.json').read_text())
|
| 19 |
+
rows=json.loads((directory/'test_progress.json').read_text())
|
| 20 |
+
scores=[p['score'] for p in calibration['predictions']]
|
| 21 |
+
card=candidate['categories'][category]
|
| 22 |
+
card.update(previous_threshold=card['threshold'], previous_model_id=card['model_id'],
|
| 23 |
+
threshold=quantile(scores,.8), model_id=card['model_id'].removesuffix('-q95-v1')+'-q80-v1',
|
| 24 |
+
decision_policy='normal-q80-v1')
|
| 25 |
+
threshold=card['threshold'];card['uncertainty_margin']=threshold*.05
|
| 26 |
+
card['calibration'].update(method='Fixed linear 80th percentile of heldout normal scores; no anomalous calibration',
|
| 27 |
+
policy='normal-q80-v1',quantile=.8,calibration_above_threshold=sum(s>=threshold for s in scores))
|
| 28 |
+
card['metrics'].update(metrics(rows,threshold),
|
| 29 |
+
uncertain_fraction=sum(abs(r['scores'][3]-threshold)<=threshold*.05 for r in rows)/len(rows))
|
| 30 |
+
for category in set(baseline['categories'])-{'macaroni1','macaroni2'}:
|
| 31 |
+
assert candidate['categories'][category]==baseline['categories'][category]
|
| 32 |
+
candidate['macro_mean']={key:sum(c['metrics'][key] for c in candidate['categories'].values())/len(candidate['categories'])
|
| 33 |
+
for key in baseline['macro_mean']}
|
| 34 |
+
assert digest(source)==candidate['previous_evaluation_sha256']
|
| 35 |
+
output=ROOT/'results/macaroni_recall_deployment_evaluation.json'
|
| 36 |
+
text=json.dumps(candidate,indent=2)+'\n'
|
| 37 |
+
if output.exists() and output.read_text()!=text:raise ValueError('Preserve differing existing version')
|
| 38 |
+
output.write_text(text,encoding='utf8')
|
| 39 |
+
print(json.dumps({'policy':candidate['decision_policy'],'macro_mean':candidate['macro_mean'],
|
| 40 |
+
'categories':{c:candidate['categories'][c]['metrics'] for c in ('macaroni1','macaroni2')},'other_ten_unchanged':True},indent=2))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__=='__main__':main()
|
scripts/prepare_sensitive_calibration.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create a separate normal-only q95 policy, preserving every baseline artifact.
|
| 2 |
+
|
| 3 |
+
This is a recall-oriented development policy, not new independent validation.
|
| 4 |
+
Test labels are used only to report its retrospective operating metrics.
|
| 5 |
+
"""
|
| 6 |
+
from copy import deepcopy
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
from scripts.audit_recall import ROOT, digest, metrics, quantile
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
source = ROOT / 'results/highres_deployment_evaluation.json'
|
| 14 |
+
baseline_hash = digest(source)
|
| 15 |
+
baseline = json.loads(source.read_text())
|
| 16 |
+
candidate = deepcopy(baseline)
|
| 17 |
+
candidate.update(decision_policy='normal-q95-v1',
|
| 18 |
+
protocol='Official VisA test assignments; same frozen DINOv2 operational banks. Threshold is the fixed linear 95th percentile of the existing content-grouped held-out training-normal scores. All categories use the same quantile; no test-label optimization. Retrospective development evaluation, not independent validation.',
|
| 19 |
+
baseline_evaluation_sha256=baseline_hash,
|
| 20 |
+
validation_scope='Normal-only calibration and cached-score/software consistency checks; future recall and false-alarm rates are not guaranteed.',
|
| 21 |
+
decision_policy_reason='User requested prioritizing anomaly recall and accepts more false alarms.',
|
| 22 |
+
policy_selection_context='Policy adopted after viewing retrospective threshold-sensitivity results; not an independent or test-blind validation.',
|
| 23 |
+
source_sha256={})
|
| 24 |
+
for category, card in candidate['categories'].items():
|
| 25 |
+
directory = ROOT / 'experiments/dinov2_highres_v1' / category
|
| 26 |
+
calibration_path = directory / 'normal_calibration.json'
|
| 27 |
+
predictions_path = directory / 'test_progress.json'
|
| 28 |
+
calibration = json.loads(calibration_path.read_text())
|
| 29 |
+
rows = json.loads(predictions_path.read_text())
|
| 30 |
+
normal_scores = [row['score'] for row in calibration['predictions']]
|
| 31 |
+
assert max(normal_scores) == card['threshold']
|
| 32 |
+
assert len(normal_scores) == card['calibration']['normal']
|
| 33 |
+
# Threshold uses only normal calibration scores. Never optimize on test labels.
|
| 34 |
+
threshold = quantile(normal_scores, .95)
|
| 35 |
+
card.update(baseline_threshold=card['threshold'], threshold=threshold,
|
| 36 |
+
uncertainty_margin=threshold*.05, decision_policy='normal-q95-v1',
|
| 37 |
+
model_id=card['model_id']+'-q95-v1')
|
| 38 |
+
card['calibration'].update(method='Fixed linear 95th percentile of heldout normal scores; no anomalous calibration',
|
| 39 |
+
policy='normal-q95-v1', quantile=.95,
|
| 40 |
+
calibration_above_threshold=sum(s >= threshold for s in normal_scores),
|
| 41 |
+
future_false_positive_rate_guaranteed=False)
|
| 42 |
+
card['metrics'].update(metrics(rows, threshold),
|
| 43 |
+
uncertain_fraction=sum(abs(row['scores'][3]-threshold) <= threshold*.05 for row in rows)/len(rows))
|
| 44 |
+
for path in (calibration_path, predictions_path):
|
| 45 |
+
candidate['source_sha256'][str(path.relative_to(ROOT))] = digest(path)
|
| 46 |
+
candidate['macro_mean'] = {key: sum(c['metrics'][key] for c in candidate['categories'].values()) / len(candidate['categories'])
|
| 47 |
+
for key in (*baseline['macro_mean'], 'false_positive_rate')}
|
| 48 |
+
assert digest(source) == baseline_hash
|
| 49 |
+
output = ROOT / 'results/sensitive_deployment_evaluation.json'
|
| 50 |
+
text = json.dumps(candidate, indent=2) + '\n'
|
| 51 |
+
if output.exists() and output.read_text() != text:
|
| 52 |
+
raise ValueError('Preserve differing existing calibration; use a new policy version')
|
| 53 |
+
output.write_text(text, encoding='utf-8')
|
| 54 |
+
print(json.dumps({'output':str(output),'baseline_preserved_sha256':baseline_hash,'macro_mean':candidate['macro_mean']}, indent=2))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
if __name__ == '__main__':
|
| 58 |
+
main()
|
scripts/profile_inference.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""One bounded serving profile of the existing models; no fitting or threshold changes."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import time
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from backend.config import ROOT,Settings
|
| 10 |
+
from backend.vision import Detector
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
parser=argparse.ArgumentParser();parser.add_argument('--dataset',type=Path,required=True)
|
| 14 |
+
args=parser.parse_args()
|
| 15 |
+
detector=Detector(Settings())
|
| 16 |
+
report={'method':'Existing calibrated models; 6 original held-out images, 5 warm repetitions each; no training',
|
| 17 |
+
'categories':{},'python':__import__('platform').python_version(),'torch':torch.__version__}
|
| 18 |
+
if torch.cuda.is_available():
|
| 19 |
+
free,total=torch.cuda.mem_get_info()
|
| 20 |
+
report['gpu']={'name':torch.cuda.get_device_name(),'free_mb_before':free/1024**2,'total_mb':total/1024**2}
|
| 21 |
+
for category in ('pcb1','capsules','cashew'):
|
| 22 |
+
rows=json.loads((ROOT/'results'/f'{category}_predictions.json').read_text())['test']
|
| 23 |
+
chosen=[next(r for r in rows if r['label']==label) for label in (0,1)]
|
| 24 |
+
load=time.perf_counter();detector.load(category)
|
| 25 |
+
cold_load=(time.perf_counter()-load)*1000
|
| 26 |
+
elapsed,core=[],[]
|
| 27 |
+
for iteration in range(6):
|
| 28 |
+
for row in chosen:
|
| 29 |
+
started=time.perf_counter()
|
| 30 |
+
with Image.open(args.dataset/row['image']) as im:
|
| 31 |
+
im.load();result,_=detector.predict(im,category)
|
| 32 |
+
assert abs(result['score']-row['score'])<1e-5
|
| 33 |
+
if iteration:
|
| 34 |
+
elapsed.append((time.perf_counter()-started)*1000)
|
| 35 |
+
core.append(result['inference_ms'])
|
| 36 |
+
report['categories'][category]={'samples':len(elapsed),'core_median_ms':float(np.median(core)),
|
| 37 |
+
'core_p95_ms':float(np.percentile(core,95)),'decoded_image_to_result_median_ms':float(np.median(elapsed)),
|
| 38 |
+
'decoded_image_to_result_p95_ms':float(np.percentile(elapsed,95)),'category_load_ms':cold_load,
|
| 39 |
+
'peak_torch_allocated_gpu_mb':result['peak_gpu_mb'],'device':result['device']}
|
| 40 |
+
# Verify the Docker default CPU path also executes actual weights. Small
|
| 41 |
+
# floating-point differences from calibrated CUDA/FP16 scores are expected.
|
| 42 |
+
cpu=Detector(Settings(device='cpu'))
|
| 43 |
+
with Image.open(args.dataset/chosen[0]['image']) as im:
|
| 44 |
+
started=time.perf_counter();result,_=cpu.predict(im,'cashew')
|
| 45 |
+
report['cpu_smoke']={'verdict':result['verdict'],'score':result['score'],'reference_cuda_score':chosen[0]['score'],
|
| 46 |
+
'absolute_difference':abs(result['score']-chosen[0]['score']),'total_ms':(time.perf_counter()-started)*1000}
|
| 47 |
+
(ROOT/'results'/'serving_profile.json').write_text(json.dumps(report,indent=2))
|
| 48 |
+
print(json.dumps(report,indent=2),flush=True)
|
| 49 |
+
if __name__=='__main__':main()
|
scripts/qwen_after_training.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run every measurement after training, one step at a time, and save a report.
|
| 2 |
+
|
| 3 |
+
python -m scripts.qwen_after_training --wait-pid 12345
|
| 4 |
+
|
| 5 |
+
It waits for the training process to exit, checks that an adapter was saved, then runs:
|
| 6 |
+
1. a check of my_questions.csv
|
| 7 |
+
2. the short-question test (CPU only)
|
| 8 |
+
3. the fine-tuned model on the 100 test questions and on my_questions.csv
|
| 9 |
+
4. the same untouched base model through the same server, for a fair comparison
|
| 10 |
+
5. the original Ollama model on my_questions.csv
|
| 11 |
+
6. comparison tables
|
| 12 |
+
Only one heavy process runs at a time. Progress goes to experiments/qwen_lora_v1/pipeline.log.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import urllib.request
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
|
| 23 |
+
from backend.config import ROOT
|
| 24 |
+
|
| 25 |
+
OUT = ROOT / "experiments" / "qwen_lora_v1"
|
| 26 |
+
LOG = OUT / "pipeline.log"
|
| 27 |
+
BASE = OUT / "base_model"
|
| 28 |
+
ADAPTER = OUT / "adapter"
|
| 29 |
+
ENV = {**os.environ, "PYTHONUTF8": "1", "USE_TF": "0"}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def log(message):
|
| 33 |
+
line = f"{datetime.now():%H:%M:%S} {message}"
|
| 34 |
+
print(line, flush=True)
|
| 35 |
+
with LOG.open("a", encoding="utf-8") as stream:
|
| 36 |
+
stream.write(line + "\n")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def run(name, *args):
|
| 40 |
+
"""Run one python module as a step. Returns True on success; never raises."""
|
| 41 |
+
log(f"START {name}")
|
| 42 |
+
started = time.time()
|
| 43 |
+
with (OUT / f"step_{name}.log").open("w", encoding="utf-8") as stream:
|
| 44 |
+
code = subprocess.run(
|
| 45 |
+
[sys.executable, "-m", *args], cwd=ROOT, env=ENV, stdout=stream, stderr=subprocess.STDOUT
|
| 46 |
+
).returncode
|
| 47 |
+
log(f"{'DONE ' if code == 0 else 'FAILED'} {name} (exit {code}, {(time.time() - started) / 60:.1f} min)")
|
| 48 |
+
return code == 0
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def serve(adapter, port=11500):
|
| 52 |
+
"""Start the model server and wait until it answers. Returns the process or None."""
|
| 53 |
+
stream = (OUT / f"server_{port}.log").open("w", encoding="utf-8")
|
| 54 |
+
proc = subprocess.Popen(
|
| 55 |
+
[sys.executable, "-m", "scripts.qwen_serve", "--adapter", adapter, "--base", str(BASE), "--port", str(port)],
|
| 56 |
+
cwd=ROOT,
|
| 57 |
+
env=ENV,
|
| 58 |
+
stdout=stream,
|
| 59 |
+
stderr=subprocess.STDOUT,
|
| 60 |
+
)
|
| 61 |
+
for _ in range(120):
|
| 62 |
+
if proc.poll() is not None:
|
| 63 |
+
log(f"FAILED server exited early (exit {proc.returncode})")
|
| 64 |
+
return None
|
| 65 |
+
try:
|
| 66 |
+
urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=3).read()
|
| 67 |
+
log(f"server ready ({adapter})")
|
| 68 |
+
return proc
|
| 69 |
+
except OSError:
|
| 70 |
+
time.sleep(5)
|
| 71 |
+
proc.terminate()
|
| 72 |
+
log("FAILED server did not become ready in 10 minutes")
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def stop(proc):
|
| 77 |
+
proc.terminate()
|
| 78 |
+
try:
|
| 79 |
+
proc.wait(timeout=30)
|
| 80 |
+
except subprocess.TimeoutExpired:
|
| 81 |
+
proc.kill()
|
| 82 |
+
time.sleep(8) # let the GPU memory be released
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def main():
|
| 86 |
+
parser = argparse.ArgumentParser()
|
| 87 |
+
parser.add_argument("--wait-pid", type=int, default=0, help="process id of the training run to wait for")
|
| 88 |
+
args = parser.parse_args()
|
| 89 |
+
log("pipeline started")
|
| 90 |
+
if args.wait_pid:
|
| 91 |
+
import psutil
|
| 92 |
+
|
| 93 |
+
while psutil.pid_exists(args.wait_pid):
|
| 94 |
+
time.sleep(15)
|
| 95 |
+
log("training process has ended")
|
| 96 |
+
if not (ADAPTER / "adapter_model.safetensors").exists():
|
| 97 |
+
log("STOP: no adapter was saved, so training did not finish. See the training window.")
|
| 98 |
+
return
|
| 99 |
+
mine_ok = run("check_mine", "scripts.qwen_eval", "--split", "mine", "--check")
|
| 100 |
+
run("short_questions", "scripts.qwen_short_questions")
|
| 101 |
+
url = "http://127.0.0.1:11500"
|
| 102 |
+
for tag, adapter in (("lora", str(ADAPTER)), ("basehf", "none")):
|
| 103 |
+
proc = serve(adapter)
|
| 104 |
+
if proc is None:
|
| 105 |
+
continue
|
| 106 |
+
try:
|
| 107 |
+
run(f"eval_{tag}_test", "scripts.qwen_eval", "--split", "test", "--tag", tag, "--url", url)
|
| 108 |
+
if mine_ok:
|
| 109 |
+
run(f"eval_{tag}_mine", "scripts.qwen_eval", "--split", "mine", "--tag", tag, "--url", url)
|
| 110 |
+
finally:
|
| 111 |
+
stop(proc)
|
| 112 |
+
if mine_ok:
|
| 113 |
+
run("eval_ollama_mine", "scripts.qwen_eval", "--split", "mine", "--tag", "ollama")
|
| 114 |
+
with (OUT / "pipeline_report.txt").open("w", encoding="utf-8") as report:
|
| 115 |
+
for split, tags in (("test", ["gate50", "basehf", "lora"]), ("mine", ["ollama", "basehf", "lora"])):
|
| 116 |
+
report.write(f"\n===== {split} questions =====\n")
|
| 117 |
+
report.flush()
|
| 118 |
+
subprocess.run(
|
| 119 |
+
[sys.executable, "-m", "scripts.qwen_compare", "--split", split, *tags],
|
| 120 |
+
cwd=ROOT,
|
| 121 |
+
env=ENV,
|
| 122 |
+
stdout=report,
|
| 123 |
+
stderr=subprocess.STDOUT,
|
| 124 |
+
)
|
| 125 |
+
log("ALL DONE: see pipeline_report.txt")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
if __name__ == "__main__":
|
| 129 |
+
main()
|
scripts/qwen_build_training_data.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build the fine-tuning examples for the assistant's language model.
|
| 2 |
+
|
| 3 |
+
python -m scripts.qwen_build_training_data # version 1 -> data/train.jsonl
|
| 4 |
+
python -m scripts.qwen_build_training_data --v2 # version 2 -> data/train_v2.jsonl
|
| 5 |
+
|
| 6 |
+
Each example is the exact prompt the model sees in production (retrieved, numbered sentences)
|
| 7 |
+
and the answer we want back:
|
| 8 |
+
|
| 9 |
+
* answerable question -> the sentence that really answers it and a short restatement. The restatement
|
| 10 |
+
is the base model's own answer when it passed the project's validator, otherwise the sentence itself.
|
| 11 |
+
* question the documents cannot answer -> {"claims": []} (the model must learn to say "nothing fits").
|
| 12 |
+
|
| 13 |
+
Version 1 uses the TRAIN wordings in scripts/qwen_eval.py. Version 2 keeps every version 1 example and adds
|
| 14 |
+
the questions in experiments/qwen_lora_v1/v2_questions.csv (every knowledge sentence, conversational wording).
|
| 15 |
+
Test questions are never used: version 2 refuses any new question that is (nearly) identical to one in the
|
| 16 |
+
test wordings, in my_questions.csv, or in the short-question test.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import csv
|
| 21 |
+
import json
|
| 22 |
+
import random
|
| 23 |
+
import re
|
| 24 |
+
from collections import Counter
|
| 25 |
+
|
| 26 |
+
from backend.config import ROOT, Settings
|
| 27 |
+
from backend.rag import EvidenceWorkflow, KnowledgeIndex
|
| 28 |
+
from scripts.qwen_eval import (
|
| 29 |
+
MY_QUESTIONS,
|
| 30 |
+
OUT,
|
| 31 |
+
TOPICS,
|
| 32 |
+
UNANSWERABLE,
|
| 33 |
+
build_items,
|
| 34 |
+
knowledge_sentences,
|
| 35 |
+
load_cards,
|
| 36 |
+
make_inspection,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
NUMBER = r"\d+(?:\.\d+)?"
|
| 40 |
+
V2_QUESTIONS = OUT / "v2_questions.csv"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def prepare_state(workflow, item):
|
| 44 |
+
"""Run the workflow up to the generation step. Returns None if the model would never be asked."""
|
| 45 |
+
state = {"question": item["question"], "inspection": item["inspection"], "history": []}
|
| 46 |
+
state.update(workflow.route(state))
|
| 47 |
+
if state["mode"] == "abstained":
|
| 48 |
+
return None
|
| 49 |
+
state.update(workflow.retrieve(state))
|
| 50 |
+
state.update(workflow.validate_evidence(state))
|
| 51 |
+
return state if state.get("evidence") else None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def base_restatements(workflow, state, quotes):
|
| 55 |
+
"""Ask the base model once; keep restatements that pass the number check, keyed by quote_id."""
|
| 56 |
+
produced = workflow.generate(dict(state))
|
| 57 |
+
by_quote = {q["quote"]: qid for qid, q in quotes.items()}
|
| 58 |
+
good = {}
|
| 59 |
+
for claim in produced.get("raw_claims", []):
|
| 60 |
+
qid = by_quote.get(claim.get("quote"))
|
| 61 |
+
text = claim.get("text", "").strip()
|
| 62 |
+
if qid and text and set(re.findall(NUMBER, text)) <= set(re.findall(NUMBER, claim["quote"])):
|
| 63 |
+
good[qid] = text
|
| 64 |
+
return good
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def words(text):
|
| 68 |
+
return set(re.findall(r"[a-z0-9]+", text.lower()))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def protected_questions():
|
| 72 |
+
"""Every question that belongs to a test set, so version 2 can be checked against them."""
|
| 73 |
+
from scripts.qwen_short_questions import ONE_WORD, SHORT
|
| 74 |
+
|
| 75 |
+
protected = [q for _, (_, _, _, test) in TOPICS.items() for q in test] + UNANSWERABLE["test"]
|
| 76 |
+
protected += [text for text, _ in SHORT + ONE_WORD]
|
| 77 |
+
lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")]
|
| 78 |
+
protected += [row["question"].strip() for row in csv.DictReader(lines) if row["question"].strip()]
|
| 79 |
+
return protected
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def too_similar(question, protected, threshold=0.7):
|
| 83 |
+
"""True if the question is the same as, or a close rewording of, a protected test question."""
|
| 84 |
+
a = words(question)
|
| 85 |
+
return any(a == words(p) or len(a & words(p)) / len(a | words(p)) >= threshold for p in protected)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def v2_items(rng):
|
| 89 |
+
"""Items from v2_questions.csv: 1 inspection per answerable question, 2 per unanswerable one."""
|
| 90 |
+
cards = load_cards()
|
| 91 |
+
sentences = knowledge_sentences()
|
| 92 |
+
protected = protected_questions()
|
| 93 |
+
lines = [line for line in V2_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")]
|
| 94 |
+
items, dropped = [], []
|
| 95 |
+
for number, row in enumerate(csv.DictReader(lines), start=1):
|
| 96 |
+
question, phrase = row["question"].strip(), row["answer_phrase"].strip()
|
| 97 |
+
if not question:
|
| 98 |
+
continue
|
| 99 |
+
if too_similar(question, protected):
|
| 100 |
+
dropped.append(f"too similar to a test question: {question}")
|
| 101 |
+
continue
|
| 102 |
+
hits = [s for s in sentences if phrase and phrase.lower() in s[2].lower()]
|
| 103 |
+
if phrase and not hits:
|
| 104 |
+
raise SystemExit(f"v2_questions.csv row {number}: phrase not found in any sentence: {phrase!r}")
|
| 105 |
+
sources = {h[0] for h in hits}
|
| 106 |
+
if sources == {"legacy-profile"}:
|
| 107 |
+
families = ["dinov3"]
|
| 108 |
+
elif sources == {"highres-profile"}:
|
| 109 |
+
families = ["dinov2"]
|
| 110 |
+
else:
|
| 111 |
+
families = ["dinov2", "dinov3"]
|
| 112 |
+
for _ in range(1 if phrase else 2):
|
| 113 |
+
items.append(
|
| 114 |
+
{
|
| 115 |
+
"id": f"v2-{len(items)}",
|
| 116 |
+
"kind": "answerable" if phrase else "unanswerable",
|
| 117 |
+
"topic": "v2" if phrase else "none",
|
| 118 |
+
"question": question,
|
| 119 |
+
"pattern": re.escape(phrase) if phrase else "",
|
| 120 |
+
"inspection": make_inspection(cards, rng.choice(families), rng),
|
| 121 |
+
}
|
| 122 |
+
)
|
| 123 |
+
return items, dropped
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def make_example(workflow, item, stats):
|
| 127 |
+
"""One training example for an item, or None when the model would not be asked or the answer is missing."""
|
| 128 |
+
state = prepare_state(workflow, item)
|
| 129 |
+
if state is None:
|
| 130 |
+
stats["skipped: model would not be asked (no evidence or prohibited topic)"] += 1
|
| 131 |
+
return None
|
| 132 |
+
prompt, quotes = workflow.build_prompt(state)
|
| 133 |
+
if item["kind"] == "unanswerable":
|
| 134 |
+
claims = []
|
| 135 |
+
else:
|
| 136 |
+
pattern = re.compile(item["pattern"], re.I)
|
| 137 |
+
wanted = [qid for qid, q in quotes.items() if pattern.search(q["quote"])][:2]
|
| 138 |
+
if not wanted:
|
| 139 |
+
stats["skipped: answer sentence not in retrieved evidence"] += 1
|
| 140 |
+
return None
|
| 141 |
+
restated = base_restatements(workflow, state, quotes)
|
| 142 |
+
claims = [{"quote_id": qid, "text": restated.get(qid, quotes[qid]["quote"])} for qid in wanted]
|
| 143 |
+
stats["restatement from base model"] += sum(qid in restated for qid in wanted)
|
| 144 |
+
stats["restatement = the sentence itself"] += sum(qid not in restated for qid in wanted)
|
| 145 |
+
stats[f"example: {item['kind']}"] += 1
|
| 146 |
+
return {
|
| 147 |
+
"id": item["id"],
|
| 148 |
+
"kind": item["kind"],
|
| 149 |
+
"topic": item["topic"],
|
| 150 |
+
"pattern": item["pattern"],
|
| 151 |
+
"prompt": prompt,
|
| 152 |
+
"completion": json.dumps({"claims": claims}),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def main():
|
| 157 |
+
parser = argparse.ArgumentParser()
|
| 158 |
+
parser.add_argument("--model", default="qwen2.5:3b", help="Ollama model used for restatements")
|
| 159 |
+
parser.add_argument("--contexts", type=int, default=2, help="version 1: inspections per question")
|
| 160 |
+
parser.add_argument("--v2", action="store_true", help="add the version 2 questions to the version 1 examples")
|
| 161 |
+
args = parser.parse_args()
|
| 162 |
+
out_dir = OUT / "data"
|
| 163 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 164 |
+
stats = Counter()
|
| 165 |
+
if args.v2:
|
| 166 |
+
examples = [json.loads(line) for line in (out_dir / "train.jsonl").read_text(encoding="utf-8").splitlines()]
|
| 167 |
+
stats["example: version 1 kept as they are"] = len(examples)
|
| 168 |
+
workflow = EvidenceWorkflow(Settings(ollama_model=args.model), KnowledgeIndex(ROOT, OUT / "index"))
|
| 169 |
+
items, dropped = v2_items(random.Random("v2-7"))
|
| 170 |
+
for message in dropped:
|
| 171 |
+
print("dropped:", message)
|
| 172 |
+
examples += [e for e in (make_example(workflow, item, stats) for item in items) if e]
|
| 173 |
+
path = out_dir / "train_v2.jsonl"
|
| 174 |
+
else:
|
| 175 |
+
workflow = EvidenceWorkflow(Settings(ollama_model=args.model), KnowledgeIndex(ROOT, OUT / "index"))
|
| 176 |
+
examples = [
|
| 177 |
+
e
|
| 178 |
+
for e in (make_example(workflow, item, stats) for item in build_items("train", contexts=args.contexts))
|
| 179 |
+
if e
|
| 180 |
+
]
|
| 181 |
+
path = out_dir / "train.jsonl"
|
| 182 |
+
path.write_text("\n".join(json.dumps(e) for e in examples) + "\n", encoding="utf-8")
|
| 183 |
+
print(f"wrote {len(examples)} examples to {path}")
|
| 184 |
+
for key, value in sorted(stats.items()):
|
| 185 |
+
print(f" {value:4d} {key}")
|
| 186 |
+
lengths = sorted(len(e["prompt"]) + len(e["completion"]) for e in examples)
|
| 187 |
+
print(f"characters per example: min {lengths[0]}, median {lengths[len(lengths) // 2]}, max {lengths[-1]}")
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if __name__ == "__main__":
|
| 191 |
+
main()
|
scripts/qwen_compare.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Print saved evaluation runs side by side.
|
| 2 |
+
|
| 3 |
+
python -m scripts.qwen_compare gate50 lora
|
| 4 |
+
|
| 5 |
+
Each name is the --tag of a run made with scripts.qwen_eval on the test split.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from scripts.qwen_eval import OUT
|
| 12 |
+
|
| 13 |
+
ROWS = [
|
| 14 |
+
("retrieval_hit", "right chunk retrieved", "higher"),
|
| 15 |
+
("correct_all", "fully correct answers", "higher"),
|
| 16 |
+
("wrong_source", "answered with a wrong sentence", "lower"),
|
| 17 |
+
("no_answer_on_answerable", "no answer although one exists", "lower"),
|
| 18 |
+
("false_answer_on_unanswerable", "answered an unanswerable question", "lower"),
|
| 19 |
+
("generation_failed", "model output unusable (JSON/timeout)", "lower"),
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cell(v):
|
| 24 |
+
lo, hi = v["ci95"]
|
| 25 |
+
return f"{v['k']}/{v['n']} = {v['rate']:.0%} [{lo:.0%}-{hi:.0%}]"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
args = sys.argv[1:]
|
| 30 |
+
split = "test"
|
| 31 |
+
if "--split" in args:
|
| 32 |
+
split = args[args.index("--split") + 1]
|
| 33 |
+
del args[args.index("--split") : args.index("--split") + 2]
|
| 34 |
+
tags = args
|
| 35 |
+
if not tags:
|
| 36 |
+
sys.exit("usage: python -m scripts.qwen_compare [--split test|mine] TAG [TAG ...]")
|
| 37 |
+
data = {t: json.loads((OUT / f"summary_{t}_{split}.json").read_text()) for t in tags}
|
| 38 |
+
print(f"{'measure':38s}" + "".join(f"{t:30s}" for t in tags) + "better is")
|
| 39 |
+
for key, label, better in ROWS:
|
| 40 |
+
print(f"{label:38s}" + "".join(f"{cell(data[t][key]):30s}" for t in tags) + better)
|
| 41 |
+
print(f"{'seconds per generated answer':38s}" + "".join(f"{data[t]['mean_seconds_generated']!s:30s}" for t in tags))
|
| 42 |
+
print("\n[...] is a 95% confidence interval. If two intervals overlap a lot, the difference may be noise.")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if __name__ == "__main__":
|
| 46 |
+
main()
|
scripts/qwen_eval.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measure how well the assistant's language model picks and paraphrases evidence.
|
| 2 |
+
|
| 3 |
+
Builds a labelled question set from the knowledge documents, runs the real answer workflow
|
| 4 |
+
(retrieve, validate, generate, validate) and scores it with the project's own validator.
|
| 5 |
+
|
| 6 |
+
python -m scripts.qwen_eval --split test --model qwen2.5:3b --tag base
|
| 7 |
+
|
| 8 |
+
Results are appended to experiments/qwen_lora_v1/runs/<tag>_<split>.jsonl and can be resumed.
|
| 9 |
+
Only the language-model step changes between runs; retrieval and checks are identical.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
+
import random
|
| 16 |
+
import re
|
| 17 |
+
import time
|
| 18 |
+
import uuid
|
| 19 |
+
|
| 20 |
+
from backend.config import CATEGORIES, ROOT, Settings
|
| 21 |
+
from backend.rag import EvidenceWorkflow, KnowledgeIndex
|
| 22 |
+
|
| 23 |
+
OUT = ROOT / "experiments" / "qwen_lora_v1"
|
| 24 |
+
|
| 25 |
+
# Each topic: which model family the inspection must have (evidence is filtered by family),
|
| 26 |
+
# regex patterns that identify a correct supporting sentence, and question wordings.
|
| 27 |
+
# Wordings in "test" are never used for training.
|
| 28 |
+
TOPICS = {
|
| 29 |
+
"score_meaning": (
|
| 30 |
+
"any",
|
| 31 |
+
r"score is not a defect probability|larger anomaly score",
|
| 32 |
+
[
|
| 33 |
+
"What does the anomaly score mean?",
|
| 34 |
+
"Is the score a probability that this part is defective?",
|
| 35 |
+
"How should I read the score number?",
|
| 36 |
+
"Does a higher score mean more defects?",
|
| 37 |
+
],
|
| 38 |
+
["Explain what this score tells me.", "Can I treat the score as the chance of a defect?"],
|
| 39 |
+
),
|
| 40 |
+
"verdict_good": (
|
| 41 |
+
"any",
|
| 42 |
+
r"Good means",
|
| 43 |
+
[
|
| 44 |
+
"What does a Good verdict mean?",
|
| 45 |
+
"When is a result labelled Good?",
|
| 46 |
+
"How does the system decide something is Good?",
|
| 47 |
+
"What makes an inspection Good?",
|
| 48 |
+
],
|
| 49 |
+
["Explain the Good label.", "Under what condition do I get Good?"],
|
| 50 |
+
),
|
| 51 |
+
"verdict_anomalous": (
|
| 52 |
+
"any",
|
| 53 |
+
r"Anomalous means",
|
| 54 |
+
[
|
| 55 |
+
"What does Anomalous mean?",
|
| 56 |
+
"When is an inspection flagged as Anomalous?",
|
| 57 |
+
"How does a result become Anomalous?",
|
| 58 |
+
"What is needed for an Anomalous verdict?",
|
| 59 |
+
],
|
| 60 |
+
["Explain the Anomalous label.", "Why would a result be called Anomalous?"],
|
| 61 |
+
),
|
| 62 |
+
"verdict_uncertain": (
|
| 63 |
+
"any",
|
| 64 |
+
r"Uncertain means|five-percent band",
|
| 65 |
+
[
|
| 66 |
+
"What does Uncertain mean?",
|
| 67 |
+
"What is the Uncertain verdict?",
|
| 68 |
+
"How wide is the Uncertain zone?",
|
| 69 |
+
"When is a result Uncertain?",
|
| 70 |
+
],
|
| 71 |
+
["Explain the Uncertain label.", "How is the uncertain range defined?"],
|
| 72 |
+
),
|
| 73 |
+
"review_band": (
|
| 74 |
+
"any",
|
| 75 |
+
r"review band is an operational heuristic|five-percent band",
|
| 76 |
+
[
|
| 77 |
+
"What is the review band?",
|
| 78 |
+
"Is the review band a statistical confidence interval?",
|
| 79 |
+
"How reliable is the review band?",
|
| 80 |
+
"What kind of measure is the five percent band?",
|
| 81 |
+
],
|
| 82 |
+
["Tell me about the review band.", "Is the review band calibrated?"],
|
| 83 |
+
),
|
| 84 |
+
"good_not_proof": (
|
| 85 |
+
"any",
|
| 86 |
+
r"not proof of factory acceptance",
|
| 87 |
+
[
|
| 88 |
+
"Does Good mean the product is safe?",
|
| 89 |
+
"Can I ship a part just because it is Good?",
|
| 90 |
+
"Is a Good result proof of acceptance?",
|
| 91 |
+
"Does Good guarantee the part has no defects?",
|
| 92 |
+
],
|
| 93 |
+
["Is Good a guarantee of quality?", "Can I rely on Good as factory acceptance?"],
|
| 94 |
+
),
|
| 95 |
+
"historical": (
|
| 96 |
+
"any",
|
| 97 |
+
r"Historical inspections retain|newer active model does not change",
|
| 98 |
+
[
|
| 99 |
+
"Will an old inspection change when a new model is installed?",
|
| 100 |
+
"Do past results keep their original model?",
|
| 101 |
+
"Does updating the model rewrite earlier verdicts?",
|
| 102 |
+
"What happens to historical inspections after a model update?",
|
| 103 |
+
],
|
| 104 |
+
["Are earlier verdicts recalculated with the newer model?", "Do old heatmaps change after an upgrade?"],
|
| 105 |
+
),
|
| 106 |
+
"saved_fields": (
|
| 107 |
+
"any",
|
| 108 |
+
r"saves its model ID",
|
| 109 |
+
[
|
| 110 |
+
"What information is saved with each inspection?",
|
| 111 |
+
"Which details does an inspection record store?",
|
| 112 |
+
"What gets saved for every inspection?",
|
| 113 |
+
"Which fields are kept in a saved inspection?",
|
| 114 |
+
],
|
| 115 |
+
["What does the saved record contain?", "List what is stored for an inspection."],
|
| 116 |
+
),
|
| 117 |
+
"heatmap": (
|
| 118 |
+
"any",
|
| 119 |
+
r"heatmap shows cosine distance|Larger distances indicate",
|
| 120 |
+
[
|
| 121 |
+
"What does the heatmap show?",
|
| 122 |
+
"How is the heatmap computed?",
|
| 123 |
+
"What do the brighter areas on the heatmap mean?",
|
| 124 |
+
"What is measured by the heatmap?",
|
| 125 |
+
],
|
| 126 |
+
["Explain this heatmap.", "How do I read the heatmap?"],
|
| 127 |
+
),
|
| 128 |
+
"coarse_localization": (
|
| 129 |
+
"any",
|
| 130 |
+
r"coarse localization|interpolation does not add",
|
| 131 |
+
[
|
| 132 |
+
"Is the heatmap a precise defect outline?",
|
| 133 |
+
"Can the heatmap segment the exact defect?",
|
| 134 |
+
"How precise is the localization?",
|
| 135 |
+
"Does the heatmap name the defect?",
|
| 136 |
+
],
|
| 137 |
+
["Is localization exact?", "Does interpolation add detail to the heatmap?"],
|
| 138 |
+
),
|
| 139 |
+
"product_scope": (
|
| 140 |
+
"any",
|
| 141 |
+
r"wrong-product uploads|operator selects the product category",
|
| 142 |
+
[
|
| 143 |
+
"What if I choose the wrong product category?",
|
| 144 |
+
"Can I upload any kind of photo?",
|
| 145 |
+
"Who selects the product category?",
|
| 146 |
+
"Are wrong-product uploads supported?",
|
| 147 |
+
],
|
| 148 |
+
["What happens with an unsupported kind of image?", "Does the system detect the product type itself?"],
|
| 149 |
+
),
|
| 150 |
+
"alerts_errors": (
|
| 151 |
+
"any",
|
| 152 |
+
r"create local review alerts|error event",
|
| 153 |
+
[
|
| 154 |
+
"What happens when a model failure occurs?",
|
| 155 |
+
"When are review alerts created?",
|
| 156 |
+
"Do failed runs create inspections?",
|
| 157 |
+
"Which results trigger alerts?",
|
| 158 |
+
],
|
| 159 |
+
["What events create alerts?", "Is an error saved as a successful inspection?"],
|
| 160 |
+
),
|
| 161 |
+
"visa": (
|
| 162 |
+
"any",
|
| 163 |
+
r"VisA provides|official one-class split|PCB1, capsules|Image-level labels|Multiclass masks|Normal images have no stored",
|
| 164 |
+
[
|
| 165 |
+
"What is the VisA dataset?",
|
| 166 |
+
"How does the official VisA split work?",
|
| 167 |
+
"What does VisA contain?",
|
| 168 |
+
"Which products does VisA include?",
|
| 169 |
+
],
|
| 170 |
+
["Tell me about VisA.", "Does VisA include anomaly masks?"],
|
| 171 |
+
),
|
| 172 |
+
"visa_license": (
|
| 173 |
+
"any",
|
| 174 |
+
r"CC BY 4\.0|SPot-the-Difference|Amazon Science",
|
| 175 |
+
[
|
| 176 |
+
"What licence is the VisA dataset under?",
|
| 177 |
+
"Who should be credited for VisA?",
|
| 178 |
+
"Who released the VisA dataset?",
|
| 179 |
+
"How must VisA be attributed?",
|
| 180 |
+
],
|
| 181 |
+
["What is the VisA licence?", "Which paper introduced VisA?"],
|
| 182 |
+
),
|
| 183 |
+
"legacy_profile": (
|
| 184 |
+
"dinov3",
|
| 185 |
+
r"frozen DINOv3 ViT-S/16|224 by 224|64 normal images|Original DINOv3|identifies the original|maximizes validation F1|Calibration uses 32",
|
| 186 |
+
[
|
| 187 |
+
"What is the original DINOv3 profile?",
|
| 188 |
+
"What number of normal images does the original profile fit per product?",
|
| 189 |
+
"What input size does the DINOv3 profile use?",
|
| 190 |
+
"How is the original profile calibrated?",
|
| 191 |
+
],
|
| 192 |
+
["Describe the legacy model profile.", "What patch grid does the original profile use?"],
|
| 193 |
+
),
|
| 194 |
+
"highres_profile": (
|
| 195 |
+
"dinov2",
|
| 196 |
+
r"frozen DINOv2 ViT-S/14|448-pixel|PCA-based foreground|averages the largest one percent|identifies the AnomalyDINO",
|
| 197 |
+
[
|
| 198 |
+
"What is the DINOv2 high-resolution profile?",
|
| 199 |
+
"What image size does the high-resolution profile use?",
|
| 200 |
+
"How is the anomaly score computed in this profile?",
|
| 201 |
+
"What does the foreground heuristic do?",
|
| 202 |
+
],
|
| 203 |
+
["Describe the high-resolution model.", "Is the PCA foreground filter reliable?"],
|
| 204 |
+
),
|
| 205 |
+
"calibration": (
|
| 206 |
+
"dinov2",
|
| 207 |
+
r"maximum heldout normal score|ten-percent holdout|no anomalous images",
|
| 208 |
+
[
|
| 209 |
+
"How is the decision threshold chosen?",
|
| 210 |
+
"Which images set the threshold?",
|
| 211 |
+
"Are anomalous images used to pick the threshold?",
|
| 212 |
+
"How is the operational threshold calibrated?",
|
| 213 |
+
],
|
| 214 |
+
["Explain how the threshold is calibrated.", "What is the threshold based on?"],
|
| 215 |
+
),
|
| 216 |
+
"metrics": (
|
| 217 |
+
"dinov2",
|
| 218 |
+
r"Image mAP is|Mean image AUROC|Pixel mAP|not bounding-box mAP",
|
| 219 |
+
[
|
| 220 |
+
"What is image mAP?",
|
| 221 |
+
"How is mean image AUROC computed?",
|
| 222 |
+
"Is mAP here the same as YOLO box mAP?",
|
| 223 |
+
"Does DefectRAG predict bounding boxes?",
|
| 224 |
+
],
|
| 225 |
+
["Explain pixel mAP.", "Is this mAP measured at an IoU threshold?"],
|
| 226 |
+
),
|
| 227 |
+
"retrospective": (
|
| 228 |
+
"dinov2",
|
| 229 |
+
r"retrospective development evaluation|Earlier official test exposure",
|
| 230 |
+
[
|
| 231 |
+
"Is the evaluation an untouched external test?",
|
| 232 |
+
"Was the model evaluated on unseen data?",
|
| 233 |
+
"How trustworthy is the reported accuracy?",
|
| 234 |
+
"Why is the evaluation called retrospective?",
|
| 235 |
+
],
|
| 236 |
+
["Is the benchmark independent?", "Does earlier test exposure affect the results?"],
|
| 237 |
+
),
|
| 238 |
+
"dinomaly": (
|
| 239 |
+
"any",
|
| 240 |
+
r"Dinomaly uses|compact nearest-normal fallback|does not establish|reconstruction|different method",
|
| 241 |
+
[
|
| 242 |
+
"How does Dinomaly differ from this detector?",
|
| 243 |
+
"Does this app use Dinomaly reconstruction?",
|
| 244 |
+
"What is Dinomaly?",
|
| 245 |
+
"Can Dinomaly benchmark numbers describe this application?",
|
| 246 |
+
],
|
| 247 |
+
["Compare this model with Dinomaly.", "Is reconstruction used here?"],
|
| 248 |
+
),
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
# Questions the documents cannot answer. A good assistant returns no claim for these.
|
| 252 |
+
UNANSWERABLE = {
|
| 253 |
+
"train": [
|
| 254 |
+
"What is the capital of France?",
|
| 255 |
+
"Give me a recipe for fried rice.",
|
| 256 |
+
"Write a short poem about spring.",
|
| 257 |
+
"What will the weather be tomorrow?",
|
| 258 |
+
"How do I sort a list in Python?",
|
| 259 |
+
"Who won the last football world cup?",
|
| 260 |
+
"Translate 'good morning' into Malay.",
|
| 261 |
+
"Tell me a joke.",
|
| 262 |
+
"Who funded the VisA dataset?",
|
| 263 |
+
"What is the total number of images in VisA?",
|
| 264 |
+
"Which GPU does the high-resolution profile need?",
|
| 265 |
+
"How long does one inspection take on a CPU?",
|
| 266 |
+
"Does the system work on metal screws?",
|
| 267 |
+
"What is the false alarm rate in production?",
|
| 268 |
+
"Which camera should I use for the photos?",
|
| 269 |
+
"What is the AUROC of the original profile on cashew?",
|
| 270 |
+
"Is this approved for medical device inspection?",
|
| 271 |
+
"Who wrote the DefectRAG project?",
|
| 272 |
+
],
|
| 273 |
+
"test": [
|
| 274 |
+
"What is the tallest mountain in the world?",
|
| 275 |
+
"Suggest a name for my cat.",
|
| 276 |
+
"How do I reverse a string in JavaScript?",
|
| 277 |
+
"What is 17 times 23?",
|
| 278 |
+
"Who paid for the VisA benchmark?",
|
| 279 |
+
"What resolution in megapixels should the photos have?",
|
| 280 |
+
"Does it work on bottle caps?",
|
| 281 |
+
"What is the precision on macaroni?",
|
| 282 |
+
"Which lighting setup is best?",
|
| 283 |
+
"Is the system certified for aerospace parts?",
|
| 284 |
+
],
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def load_cards():
|
| 289 |
+
legacy = {c: json.loads((ROOT / "models" / f"{c}.json").read_text()) for c in CATEGORIES}
|
| 290 |
+
high = {c: json.loads((ROOT / "models" / "highres" / f"{c}.json").read_text()) for c in CATEGORIES}
|
| 291 |
+
return {"dinov3": legacy, "dinov2": high}
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def make_inspection(cards, family, rng):
|
| 295 |
+
category = rng.choice(CATEGORIES)
|
| 296 |
+
card = cards[family][category]
|
| 297 |
+
threshold, margin = card["threshold"], card["uncertainty_margin"]
|
| 298 |
+
verdict = rng.choice(["Good", "Uncertain", "Anomalous"])
|
| 299 |
+
if verdict == "Good":
|
| 300 |
+
score = threshold - margin * rng.uniform(1.5, 8)
|
| 301 |
+
elif verdict == "Anomalous":
|
| 302 |
+
score = threshold + margin * rng.uniform(1.5, 8)
|
| 303 |
+
else:
|
| 304 |
+
score = threshold + margin * rng.uniform(-0.9, 0.9)
|
| 305 |
+
return {
|
| 306 |
+
"id": uuid.UUID(int=rng.getrandbits(128)).hex,
|
| 307 |
+
"category": category,
|
| 308 |
+
"verdict": verdict,
|
| 309 |
+
"score": round(score, 5),
|
| 310 |
+
"threshold": round(threshold, 5),
|
| 311 |
+
"uncertainty_margin": round(margin, 5),
|
| 312 |
+
"model_id": card["model_id"],
|
| 313 |
+
"scope": "VisA benchmark appearance anomaly screening; category is user-selected and not verified by this model.",
|
| 314 |
+
"localization": card.get("localization", "patch distances, interpolated; not a defect segmentation classifier"),
|
| 315 |
+
"calibration": card.get("calibration"),
|
| 316 |
+
"profile": card.get("profile"),
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
MY_QUESTIONS = OUT / "my_questions.csv"
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def knowledge_sentences():
|
| 324 |
+
"""Every sentence the assistant can quote, split exactly like rag.evidence_quotes does."""
|
| 325 |
+
sources = json.loads((ROOT / "knowledge" / "sources.json").read_text(encoding="utf-8"))
|
| 326 |
+
found = []
|
| 327 |
+
for source in sources:
|
| 328 |
+
text = (ROOT / "knowledge" / source["file"]).read_text(encoding="utf-8")
|
| 329 |
+
for sentence in re.split(r"(?<=[.!?])\s+|\n", text):
|
| 330 |
+
sentence = sentence.strip()
|
| 331 |
+
if len(sentence) >= 15 and not sentence.startswith("#"):
|
| 332 |
+
found.append((source["id"], source["file"], sentence))
|
| 333 |
+
return found
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def load_my_questions(cards, rng):
|
| 337 |
+
"""Questions written by a person: columns 'question' and 'answer_phrase' (empty = unanswerable)."""
|
| 338 |
+
import csv
|
| 339 |
+
|
| 340 |
+
if not MY_QUESTIONS.exists():
|
| 341 |
+
raise SystemExit(f"{MY_QUESTIONS} does not exist yet.")
|
| 342 |
+
lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")]
|
| 343 |
+
sentences = knowledge_sentences()
|
| 344 |
+
items = []
|
| 345 |
+
problems = []
|
| 346 |
+
for number, row in enumerate(csv.DictReader(lines), start=1):
|
| 347 |
+
question = (row.get("question") or "").strip()
|
| 348 |
+
phrase = (row.get("answer_phrase") or "").strip()
|
| 349 |
+
if not question:
|
| 350 |
+
continue
|
| 351 |
+
if not phrase:
|
| 352 |
+
family = rng.choice(["dinov2", "dinov3"])
|
| 353 |
+
items.append(("unanswerable", "none", question, "", family))
|
| 354 |
+
continue
|
| 355 |
+
hits = [s for s in sentences if phrase.lower() in s[2].lower()]
|
| 356 |
+
if not hits:
|
| 357 |
+
problems.append(
|
| 358 |
+
f"question {number} ({question[:50]!r}): answer_phrase {phrase!r} is not in any knowledge sentence"
|
| 359 |
+
)
|
| 360 |
+
continue
|
| 361 |
+
sources = {h[0] for h in hits}
|
| 362 |
+
family = (
|
| 363 |
+
"dinov3"
|
| 364 |
+
if sources == {"legacy-profile"}
|
| 365 |
+
else "dinov2"
|
| 366 |
+
if sources == {"highres-profile"}
|
| 367 |
+
else rng.choice(["dinov2", "dinov3"])
|
| 368 |
+
)
|
| 369 |
+
items.append(("answerable", "mine", question, re.escape(phrase), family))
|
| 370 |
+
if problems:
|
| 371 |
+
raise SystemExit("Fix these rows in my_questions.csv:\n " + "\n ".join(problems))
|
| 372 |
+
return [
|
| 373 |
+
{
|
| 374 |
+
"id": f"mine-{index}",
|
| 375 |
+
"split": "mine",
|
| 376 |
+
"kind": kind,
|
| 377 |
+
"topic": topic,
|
| 378 |
+
"question": question,
|
| 379 |
+
"pattern": pattern,
|
| 380 |
+
"inspection": make_inspection(cards, family, rng),
|
| 381 |
+
}
|
| 382 |
+
for index, (kind, topic, question, pattern, family) in enumerate(items)
|
| 383 |
+
]
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def build_items(split, contexts=2, seed=7):
|
| 387 |
+
"""Deterministic list of labelled items for 'train', 'test' or 'mine' (your own CSV)."""
|
| 388 |
+
rng = random.Random(f"{seed}-{split}")
|
| 389 |
+
cards = load_cards()
|
| 390 |
+
if split == "mine":
|
| 391 |
+
return load_my_questions(cards, rng)
|
| 392 |
+
items = []
|
| 393 |
+
for topic, (family, pattern, train, test) in TOPICS.items():
|
| 394 |
+
for question in train if split == "train" else test:
|
| 395 |
+
for _ in range(contexts):
|
| 396 |
+
fam = rng.choice(["dinov2", "dinov3"]) if family == "any" else family
|
| 397 |
+
items.append(
|
| 398 |
+
{
|
| 399 |
+
"id": f"{split}-{topic}-{len(items)}",
|
| 400 |
+
"split": split,
|
| 401 |
+
"kind": "answerable",
|
| 402 |
+
"topic": topic,
|
| 403 |
+
"question": question,
|
| 404 |
+
"pattern": pattern,
|
| 405 |
+
"inspection": make_inspection(cards, fam, rng),
|
| 406 |
+
}
|
| 407 |
+
)
|
| 408 |
+
for question in UNANSWERABLE[split]:
|
| 409 |
+
for _ in range(contexts):
|
| 410 |
+
fam = rng.choice(["dinov2", "dinov3"])
|
| 411 |
+
items.append(
|
| 412 |
+
{
|
| 413 |
+
"id": f"{split}-none-{len(items)}",
|
| 414 |
+
"split": split,
|
| 415 |
+
"kind": "unanswerable",
|
| 416 |
+
"topic": "none",
|
| 417 |
+
"question": question,
|
| 418 |
+
"pattern": "",
|
| 419 |
+
"inspection": make_inspection(cards, fam, rng),
|
| 420 |
+
}
|
| 421 |
+
)
|
| 422 |
+
return items
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def score_item(item, state, seconds):
|
| 426 |
+
"""Turn one workflow result into measured outcomes."""
|
| 427 |
+
claims = state.get("claims") or []
|
| 428 |
+
raw = state.get("raw_claims") or []
|
| 429 |
+
trace = state.get("trace") or []
|
| 430 |
+
evidence = state.get("evidence") or []
|
| 431 |
+
pattern = re.compile(item["pattern"], re.I) if item["pattern"] else None
|
| 432 |
+
row = {
|
| 433 |
+
"id": item["id"],
|
| 434 |
+
"kind": item["kind"],
|
| 435 |
+
"topic": item["topic"],
|
| 436 |
+
"question": item["question"],
|
| 437 |
+
"seconds": round(seconds, 2),
|
| 438 |
+
"mode": state.get("mode"),
|
| 439 |
+
"generated": "generate" in trace,
|
| 440 |
+
"generation_failed": "generation_fallback" in trace,
|
| 441 |
+
"n_raw": len(raw),
|
| 442 |
+
"n_valid": len(claims),
|
| 443 |
+
"claims": [{"text": c["text"], "source_id": c["source_id"], "quote": c["quote"]} for c in claims],
|
| 444 |
+
}
|
| 445 |
+
if item["kind"] == "answerable":
|
| 446 |
+
row["retrieval_hit"] = any(pattern.search(e["text"]) for e in evidence)
|
| 447 |
+
row["correct"] = bool(claims) and all(pattern.search(c["quote"]) for c in claims)
|
| 448 |
+
row["wrong_source"] = bool(claims) and not row["correct"]
|
| 449 |
+
else:
|
| 450 |
+
row["false_answer"] = bool(claims)
|
| 451 |
+
return row
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def wilson(k, n, z=1.96):
|
| 455 |
+
if n == 0:
|
| 456 |
+
return (0.0, 0.0)
|
| 457 |
+
p = k / n
|
| 458 |
+
d = 1 + z * z / n
|
| 459 |
+
c = (p + z * z / (2 * n)) / d
|
| 460 |
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 461 |
+
return (max(0.0, c - h), min(1.0, c + h))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def summarize(rows):
|
| 465 |
+
ans = [r for r in rows if r["kind"] == "answerable"]
|
| 466 |
+
una = [r for r in rows if r["kind"] == "unanswerable"]
|
| 467 |
+
hit = [r for r in ans if r["retrieval_hit"]]
|
| 468 |
+
out = {"items": len(rows), "answerable": len(ans), "unanswerable": len(una)}
|
| 469 |
+
|
| 470 |
+
def rate(name, k, n):
|
| 471 |
+
lo, hi = wilson(k, n)
|
| 472 |
+
out[name] = {"k": k, "n": n, "rate": round(k / n, 3) if n else None, "ci95": [round(lo, 3), round(hi, 3)]}
|
| 473 |
+
|
| 474 |
+
rate("retrieval_hit", len(hit), len(ans))
|
| 475 |
+
rate("correct_all", sum(r["correct"] for r in ans), len(ans))
|
| 476 |
+
rate("correct_given_retrieval", sum(r["correct"] for r in hit), len(hit))
|
| 477 |
+
rate("wrong_source", sum(r["wrong_source"] for r in ans), len(ans))
|
| 478 |
+
rate("no_answer_on_answerable", sum(not r["n_valid"] for r in ans), len(ans))
|
| 479 |
+
rate("false_answer_on_unanswerable", sum(r["false_answer"] for r in una), len(una))
|
| 480 |
+
gen = [r for r in rows if r["generated"]]
|
| 481 |
+
reached = [r for r in rows if r["generated"] or r["generation_failed"]]
|
| 482 |
+
rate("generation_failed", sum(r["generation_failed"] for r in reached), len(reached))
|
| 483 |
+
raw_total = sum(r["n_raw"] for r in gen)
|
| 484 |
+
out["validator_dropped_claims"] = {"raw": raw_total, "kept": sum(r["n_valid"] for r in gen)}
|
| 485 |
+
out["mean_seconds_generated"] = round(sum(r["seconds"] for r in gen) / len(gen), 2) if gen else None
|
| 486 |
+
return out
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def require_server(url):
|
| 490 |
+
"""Stop with a clear message if nothing answers at the model server address."""
|
| 491 |
+
import urllib.request
|
| 492 |
+
|
| 493 |
+
for path in ("/api/tags", "/"):
|
| 494 |
+
try:
|
| 495 |
+
urllib.request.urlopen(url.rstrip("/") + path, timeout=5).read()
|
| 496 |
+
return
|
| 497 |
+
except OSError:
|
| 498 |
+
continue
|
| 499 |
+
raise SystemExit(
|
| 500 |
+
f"No model server is answering at {url}. Start it first (scripts.qwen_serve, or Ollama) and retry."
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
SPACE_SYSTEM = (
|
| 505 |
+
"Follow the application instructions. Return only valid JSON matching the supplied schema. "
|
| 506 |
+
"No markdown fences or commentary."
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def make_local_generator(model_dir, style):
|
| 511 |
+
"""Generate the way the Hugging Face Space does: bf16 weights, greedy decoding, output format NOT forced.
|
| 512 |
+
|
| 513 |
+
style "space": the Space's own wrapper (system message + 'JSON schema: ...' appended to the prompt).
|
| 514 |
+
style "plain": the prompt exactly as used in training.
|
| 515 |
+
Returns a function with the same (prompt, schema) -> {"json": text} contract as deployment/space/generation.py.
|
| 516 |
+
"""
|
| 517 |
+
import torch
|
| 518 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 519 |
+
|
| 520 |
+
tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
| 521 |
+
model = AutoModelForCausalLM.from_pretrained(model_dir, dtype=torch.bfloat16, device_map="cuda").eval()
|
| 522 |
+
|
| 523 |
+
@torch.inference_mode()
|
| 524 |
+
def generate(prompt, schema):
|
| 525 |
+
if style == "space":
|
| 526 |
+
messages = [
|
| 527 |
+
{"role": "system", "content": SPACE_SYSTEM},
|
| 528 |
+
{"role": "user", "content": prompt + "\nJSON schema: " + json.dumps(schema)},
|
| 529 |
+
]
|
| 530 |
+
else:
|
| 531 |
+
messages = [{"role": "user", "content": prompt}]
|
| 532 |
+
values = tokenizer.apply_chat_template(
|
| 533 |
+
messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", return_dict=True
|
| 534 |
+
)
|
| 535 |
+
if values["input_ids"].shape[-1] > 4096:
|
| 536 |
+
raise ValueError("Evidence request exceeds the bounded generation context")
|
| 537 |
+
values = {key: value.to("cuda") for key, value in values.items()}
|
| 538 |
+
output = model.generate(**values, max_new_tokens=384, do_sample=False, use_cache=True)
|
| 539 |
+
text = tokenizer.decode(output[0, values["input_ids"].shape[-1] :], skip_special_tokens=True).strip()
|
| 540 |
+
return {"json": text, "metadata": {}}
|
| 541 |
+
|
| 542 |
+
return generate
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def main():
|
| 546 |
+
parser = argparse.ArgumentParser()
|
| 547 |
+
parser.add_argument(
|
| 548 |
+
"--local-model", default=None, help="folder of a merged model: run it in-process like the Space"
|
| 549 |
+
)
|
| 550 |
+
parser.add_argument("--style", choices=["space", "plain"], default="space", help="with --local-model")
|
| 551 |
+
parser.add_argument("--split", choices=["train", "test", "mine"], default="test")
|
| 552 |
+
parser.add_argument("--model", default="qwen2.5:3b")
|
| 553 |
+
parser.add_argument("--tag", default="base")
|
| 554 |
+
parser.add_argument("--limit", type=int, default=0)
|
| 555 |
+
parser.add_argument("--url", default=None, help="Ollama-compatible server (default: your Ollama)")
|
| 556 |
+
parser.add_argument("--list-sentences", action="store_true", help="write the quotable sentences to a file and exit")
|
| 557 |
+
parser.add_argument("--check", action="store_true", help="with --split mine: only check the CSV, run nothing")
|
| 558 |
+
args = parser.parse_args()
|
| 559 |
+
if args.list_sentences:
|
| 560 |
+
path = OUT / "knowledge_sentences.txt"
|
| 561 |
+
rows = knowledge_sentences()
|
| 562 |
+
path.write_text("\n".join(f"[{source}] {sentence}" for source, _, sentence in rows) + "\n", encoding="utf-8")
|
| 563 |
+
print(f"wrote {len(rows)} sentences to {path}")
|
| 564 |
+
return
|
| 565 |
+
if args.check:
|
| 566 |
+
items = build_items("mine")
|
| 567 |
+
answerable = sum(i["kind"] == "answerable" for i in items)
|
| 568 |
+
print(
|
| 569 |
+
f"my_questions.csv is valid: {len(items)} questions ({answerable} answerable, {len(items) - answerable} unanswerable)"
|
| 570 |
+
)
|
| 571 |
+
return
|
| 572 |
+
runs = OUT / "runs"
|
| 573 |
+
runs.mkdir(parents=True, exist_ok=True)
|
| 574 |
+
path = runs / f"{args.tag}_{args.split}.jsonl"
|
| 575 |
+
done = {json.loads(l)["id"]: json.loads(l) for l in path.read_text().splitlines()} if path.exists() else {}
|
| 576 |
+
settings = Settings(ollama_model=args.model)
|
| 577 |
+
if args.url:
|
| 578 |
+
settings.ollama_url = args.url
|
| 579 |
+
generator = None
|
| 580 |
+
if args.local_model:
|
| 581 |
+
generator = make_local_generator(args.local_model, args.style)
|
| 582 |
+
else:
|
| 583 |
+
require_server(settings.ollama_url)
|
| 584 |
+
workflow = EvidenceWorkflow(settings, KnowledgeIndex(ROOT, OUT / "index"), generator)
|
| 585 |
+
items = build_items(args.split)
|
| 586 |
+
if args.limit:
|
| 587 |
+
items = items[: args.limit]
|
| 588 |
+
failures_in_a_row = 0
|
| 589 |
+
for n, item in enumerate(items, 1):
|
| 590 |
+
if item["id"] in done:
|
| 591 |
+
continue
|
| 592 |
+
start = time.perf_counter()
|
| 593 |
+
state = workflow.graph.invoke({"question": item["question"], "inspection": item["inspection"], "history": []})
|
| 594 |
+
row = score_item(item, state, time.perf_counter() - start)
|
| 595 |
+
failures_in_a_row = failures_in_a_row + 1 if row["generation_failed"] else 0
|
| 596 |
+
if failures_in_a_row >= 3:
|
| 597 |
+
raise SystemExit(
|
| 598 |
+
"STOPPED: the language model failed 3 times in a row, so these results would be meaningless. "
|
| 599 |
+
"Is the server still running? Nothing from the failed items was saved."
|
| 600 |
+
)
|
| 601 |
+
done[item["id"]] = row
|
| 602 |
+
with path.open("a", encoding="utf-8") as stream:
|
| 603 |
+
stream.write(json.dumps(row) + "\n")
|
| 604 |
+
print(
|
| 605 |
+
f"{n}/{len(items)} {item['kind'][:3]} {row['mode']:<15} {row['seconds']:>5}s {item['question'][:60]}",
|
| 606 |
+
flush=True,
|
| 607 |
+
)
|
| 608 |
+
summary = summarize([done[i["id"]] for i in items if i["id"] in done])
|
| 609 |
+
(OUT / f"summary_{args.tag}_{args.split}.json").write_text(json.dumps(summary, indent=2))
|
| 610 |
+
print(json.dumps(summary, indent=2))
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
if __name__ == "__main__":
|
| 614 |
+
main()
|
scripts/qwen_finetune.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""QLoRA fine-tuning of Qwen2.5-3B-Instruct on the evidence-selection examples.
|
| 2 |
+
|
| 3 |
+
Run this in the SEPARATE training environment (defectrag-ft), not the app environment:
|
| 4 |
+
|
| 5 |
+
python -m scripts.qwen_finetune
|
| 6 |
+
|
| 7 |
+
What happens, in order:
|
| 8 |
+
1. Load the base model in 4-bit (QLoRA): the big weights are frozen and compressed.
|
| 9 |
+
2. Attach small trainable LoRA matrices to the attention and MLP layers (about 1% of the size).
|
| 10 |
+
3. Turn each example into tokens. Loss is computed only on the ANSWER part, never on the prompt.
|
| 11 |
+
4. Train for a few epochs with gradient accumulation (several small steps act like one big batch).
|
| 12 |
+
5. Report training and validation loss each epoch, then save only the small adapter (tens of MB).
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
import random
|
| 19 |
+
import time
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
|
| 24 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 25 |
+
|
| 26 |
+
OUT = Path(__file__).resolve().parents[1] / "experiments" / "qwen_lora_v1"
|
| 27 |
+
BASE = "Qwen/Qwen2.5-3B-Instruct"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def encode(tokenizer, example, max_len):
|
| 31 |
+
"""Tokens for one example; labels are -100 (ignored) for the prompt and real ids for the answer."""
|
| 32 |
+
chat = [{"role": "user", "content": example["prompt"]}]
|
| 33 |
+
prompt_text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
| 34 |
+
prompt_ids = tokenizer(prompt_text, add_special_tokens=False)["input_ids"]
|
| 35 |
+
answer_ids = tokenizer(example["completion"] + "<|im_end|>", add_special_tokens=False)["input_ids"]
|
| 36 |
+
ids = prompt_ids + answer_ids
|
| 37 |
+
if len(ids) > max_len:
|
| 38 |
+
return None
|
| 39 |
+
return {"input_ids": ids, "labels": [-100] * len(prompt_ids) + answer_ids}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def batch_loss(model, row, device):
|
| 43 |
+
ids = torch.tensor([row["input_ids"]], device=device)
|
| 44 |
+
labels = torch.tensor([row["labels"]], device=device)
|
| 45 |
+
return model(input_ids=ids, labels=labels).loss
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@torch.no_grad()
|
| 49 |
+
def validation_loss(model, rows, device):
|
| 50 |
+
model.eval()
|
| 51 |
+
total = sum(batch_loss(model, r, device).item() for r in rows)
|
| 52 |
+
model.train()
|
| 53 |
+
return total / max(1, len(rows))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
parser = argparse.ArgumentParser()
|
| 58 |
+
parser.add_argument("--model", default=BASE)
|
| 59 |
+
parser.add_argument("--data", default=str(OUT / "data" / "train.jsonl"))
|
| 60 |
+
parser.add_argument("--out", default=str(OUT / "adapter"))
|
| 61 |
+
parser.add_argument("--epochs", type=int, default=3)
|
| 62 |
+
parser.add_argument("--lr", type=float, default=2e-4)
|
| 63 |
+
parser.add_argument("--accum", type=int, default=8, help="examples per optimizer step")
|
| 64 |
+
parser.add_argument("--rank", type=int, default=16)
|
| 65 |
+
parser.add_argument("--max-len", type=int, default=2048)
|
| 66 |
+
parser.add_argument("--max-steps", type=int, default=0, help="stop early (smoke test)")
|
| 67 |
+
parser.add_argument("--limit", type=int, default=0, help="use only the first N examples (smoke test)")
|
| 68 |
+
parser.add_argument("--seed", type=int, default=7)
|
| 69 |
+
args = parser.parse_args()
|
| 70 |
+
|
| 71 |
+
random.seed(args.seed)
|
| 72 |
+
torch.manual_seed(args.seed)
|
| 73 |
+
device = "cuda"
|
| 74 |
+
print(
|
| 75 |
+
f"GPU: {torch.cuda.get_device_name(0)} free memory before loading: "
|
| 76 |
+
f"{torch.cuda.mem_get_info()[0] / 2**30:.1f} GiB",
|
| 77 |
+
flush=True,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model)
|
| 81 |
+
examples = [json.loads(line) for line in Path(args.data).read_text(encoding="utf-8").splitlines() if line.strip()]
|
| 82 |
+
if args.limit:
|
| 83 |
+
examples = examples[: args.limit]
|
| 84 |
+
random.shuffle(examples)
|
| 85 |
+
rows = [r for r in (encode(tokenizer, e, args.max_len) for e in examples) if r]
|
| 86 |
+
cut = max(1, len(rows) // 10)
|
| 87 |
+
val, train = rows[:cut], rows[cut:]
|
| 88 |
+
print(
|
| 89 |
+
f"examples: {len(train)} train, {len(val)} validation "
|
| 90 |
+
f"({len(examples) - len(rows)} dropped as too long); "
|
| 91 |
+
f"tokens per example: median {sorted(len(r['input_ids']) for r in rows)[len(rows) // 2]}",
|
| 92 |
+
flush=True,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
quant = BitsAndBytesConfig(
|
| 96 |
+
load_in_4bit=True,
|
| 97 |
+
bnb_4bit_quant_type="nf4",
|
| 98 |
+
bnb_4bit_use_double_quant=True,
|
| 99 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 100 |
+
)
|
| 101 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 102 |
+
args.model, quantization_config=quant, device_map={"": 0}, dtype=torch.bfloat16
|
| 103 |
+
)
|
| 104 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
|
| 105 |
+
lora = LoraConfig(
|
| 106 |
+
r=args.rank,
|
| 107 |
+
lora_alpha=2 * args.rank,
|
| 108 |
+
lora_dropout=0.05,
|
| 109 |
+
task_type="CAUSAL_LM",
|
| 110 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
| 111 |
+
)
|
| 112 |
+
model = get_peft_model(model, lora)
|
| 113 |
+
model.print_trainable_parameters()
|
| 114 |
+
model.train()
|
| 115 |
+
|
| 116 |
+
params = [p for p in model.parameters() if p.requires_grad]
|
| 117 |
+
optimizer = torch.optim.AdamW(params, lr=args.lr, weight_decay=0.0)
|
| 118 |
+
steps_per_epoch = math.ceil(len(train) / args.accum)
|
| 119 |
+
total_steps = steps_per_epoch * args.epochs
|
| 120 |
+
if args.max_steps:
|
| 121 |
+
total_steps = min(total_steps, args.max_steps)
|
| 122 |
+
warmup = max(1, int(0.05 * total_steps))
|
| 123 |
+
|
| 124 |
+
def lr_at(step): # linear warm-up, then cosine decay to 10%
|
| 125 |
+
if step < warmup:
|
| 126 |
+
return args.lr * (step + 1) / warmup
|
| 127 |
+
progress = (step - warmup) / max(1, total_steps - warmup)
|
| 128 |
+
return args.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress)))
|
| 129 |
+
|
| 130 |
+
log = {"args": vars(args), "epochs": [], "steps": []}
|
| 131 |
+
step, started = 0, time.time()
|
| 132 |
+
val_before = validation_loss(model, val, device)
|
| 133 |
+
print(f"validation loss BEFORE training: {val_before:.4f}", flush=True)
|
| 134 |
+
log["validation_loss_before"] = val_before
|
| 135 |
+
for epoch in range(args.epochs):
|
| 136 |
+
random.shuffle(train)
|
| 137 |
+
running = []
|
| 138 |
+
for start in range(0, len(train), args.accum):
|
| 139 |
+
group = train[start : start + args.accum]
|
| 140 |
+
for g in optimizer.param_groups:
|
| 141 |
+
g["lr"] = lr_at(step)
|
| 142 |
+
total = 0.0
|
| 143 |
+
for row in group:
|
| 144 |
+
loss = batch_loss(model, row, device) / len(group)
|
| 145 |
+
loss.backward()
|
| 146 |
+
total += loss.item()
|
| 147 |
+
torch.nn.utils.clip_grad_norm_(params, 1.0)
|
| 148 |
+
optimizer.step()
|
| 149 |
+
optimizer.zero_grad(set_to_none=True)
|
| 150 |
+
step += 1
|
| 151 |
+
running.append(total)
|
| 152 |
+
log["steps"].append({"step": step, "loss": total, "lr": lr_at(step - 1)})
|
| 153 |
+
print(
|
| 154 |
+
f"epoch {epoch + 1}/{args.epochs} step {step}/{total_steps} loss {total:.4f} "
|
| 155 |
+
f"lr {lr_at(step - 1):.2e} {time.time() - started:.0f}s "
|
| 156 |
+
f"peak GPU {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB",
|
| 157 |
+
flush=True,
|
| 158 |
+
)
|
| 159 |
+
if args.max_steps and step >= args.max_steps:
|
| 160 |
+
break
|
| 161 |
+
val_loss = validation_loss(model, val, device)
|
| 162 |
+
log["epochs"].append(
|
| 163 |
+
{"epoch": epoch + 1, "train_loss": sum(running) / len(running), "validation_loss": val_loss}
|
| 164 |
+
)
|
| 165 |
+
print(
|
| 166 |
+
f"== epoch {epoch + 1}: train loss {sum(running) / len(running):.4f}, validation loss {val_loss:.4f}",
|
| 167 |
+
flush=True,
|
| 168 |
+
)
|
| 169 |
+
if args.max_steps and step >= args.max_steps:
|
| 170 |
+
break
|
| 171 |
+
|
| 172 |
+
Path(args.out).mkdir(parents=True, exist_ok=True)
|
| 173 |
+
model.save_pretrained(args.out)
|
| 174 |
+
tokenizer.save_pretrained(args.out)
|
| 175 |
+
log["seconds"] = time.time() - started
|
| 176 |
+
(Path(args.out) / "training_log.json").write_text(json.dumps(log, indent=1), encoding="utf-8")
|
| 177 |
+
print(f"saved adapter to {args.out} (total {log['seconds'] / 60:.1f} minutes)", flush=True)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
main()
|
scripts/qwen_merge.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Merge a trained LoRA adapter into the base model and save a plain model folder.
|
| 2 |
+
|
| 3 |
+
python -m scripts.qwen_merge --adapter experiments/qwen_lora_v1/adapter_v2 --out experiments/qwen_lora_v1/merged_v2
|
| 4 |
+
|
| 5 |
+
The result is an ordinary Hugging Face model folder (no adapter needed), which Ollama can import.
|
| 6 |
+
The merge runs on the GPU so it needs very little system memory. Nothing in the app is touched.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from peft import PeftModel
|
| 14 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 15 |
+
|
| 16 |
+
from backend.config import ROOT
|
| 17 |
+
|
| 18 |
+
BASE = ROOT / "experiments" / "qwen_lora_v1" / "base_model"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main():
|
| 22 |
+
parser = argparse.ArgumentParser()
|
| 23 |
+
parser.add_argument("--adapter", required=True)
|
| 24 |
+
parser.add_argument("--base", default=str(BASE))
|
| 25 |
+
parser.add_argument("--out", required=True)
|
| 26 |
+
args = parser.parse_args()
|
| 27 |
+
out = Path(args.out)
|
| 28 |
+
if out.exists() and any(out.iterdir()):
|
| 29 |
+
raise SystemExit(f"{out} already has files; choose an empty folder so nothing is overwritten.")
|
| 30 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 31 |
+
# bf16 is the dtype the base model was published in; the adapter was trained on its 4-bit form.
|
| 32 |
+
model = AutoModelForCausalLM.from_pretrained(args.base, torch_dtype=torch.bfloat16, device_map=device)
|
| 33 |
+
model = PeftModel.from_pretrained(model, args.adapter)
|
| 34 |
+
merged = model.merge_and_unload()
|
| 35 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 36 |
+
merged.save_pretrained(out, safe_serialization=True, max_shard_size="1GB")
|
| 37 |
+
AutoTokenizer.from_pretrained(args.base).save_pretrained(out)
|
| 38 |
+
print(f"saved merged model to {out}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
main()
|
scripts/qwen_serve.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Serve Qwen (with or without the fine-tuned adapter) through an Ollama-compatible endpoint.
|
| 2 |
+
|
| 3 |
+
Run in the training environment (defectrag-ft):
|
| 4 |
+
|
| 5 |
+
python -m scripts.qwen_serve --adapter experiments/qwen_lora_v1/adapter # fine-tuned
|
| 6 |
+
python -m scripts.qwen_serve --adapter none --port 11501 # same base, no adapter
|
| 7 |
+
|
| 8 |
+
It implements only POST /api/generate, which is all the assistant's workflow uses, so
|
| 9 |
+
`python -m scripts.qwen_eval --url http://127.0.0.1:11500` measures it with the same
|
| 10 |
+
questions, retrieval and checks as before. Decoding is greedy (temperature 0), and the output is
|
| 11 |
+
forced to follow the same JSON schema the assistant sends, as Ollama does.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
import time
|
| 17 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
from lmformatenforcer import JsonSchemaParser
|
| 21 |
+
from lmformatenforcer.integrations.transformers import build_transformers_prefix_allowed_tokens_fn
|
| 22 |
+
from peft import PeftModel
|
| 23 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 24 |
+
|
| 25 |
+
BASE = "Qwen/Qwen2.5-3B-Instruct"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load(adapter, base=BASE):
|
| 29 |
+
tokenizer = AutoTokenizer.from_pretrained(base)
|
| 30 |
+
quant = BitsAndBytesConfig(
|
| 31 |
+
load_in_4bit=True,
|
| 32 |
+
bnb_4bit_quant_type="nf4",
|
| 33 |
+
bnb_4bit_use_double_quant=True,
|
| 34 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 35 |
+
)
|
| 36 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 37 |
+
base, quantization_config=quant, device_map={"": 0}, dtype=torch.bfloat16
|
| 38 |
+
)
|
| 39 |
+
if adapter != "none":
|
| 40 |
+
model = PeftModel.from_pretrained(model, adapter)
|
| 41 |
+
return tokenizer, model.eval()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def make_handler(tokenizer, model, label):
|
| 45 |
+
class Handler(BaseHTTPRequestHandler):
|
| 46 |
+
def log_message(self, *args): # keep the terminal readable
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
def _send(self, status, payload):
|
| 50 |
+
data = json.dumps(payload).encode()
|
| 51 |
+
self.send_response(status)
|
| 52 |
+
self.send_header("Content-Type", "application/json")
|
| 53 |
+
self.send_header("Content-Length", str(len(data)))
|
| 54 |
+
self.end_headers()
|
| 55 |
+
self.wfile.write(data)
|
| 56 |
+
|
| 57 |
+
def do_GET(self):
|
| 58 |
+
self._send(200, {"status": "ok", "model": label})
|
| 59 |
+
|
| 60 |
+
def do_POST(self):
|
| 61 |
+
if self.path != "/api/generate":
|
| 62 |
+
return self._send(404, {"error": "only /api/generate is implemented"})
|
| 63 |
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
| 64 |
+
chat = [{"role": "user", "content": body["prompt"]}]
|
| 65 |
+
text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
| 66 |
+
inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False).to(model.device)
|
| 67 |
+
kwargs = {}
|
| 68 |
+
if isinstance(body.get("format"), dict):
|
| 69 |
+
parser = JsonSchemaParser(body["format"])
|
| 70 |
+
kwargs["prefix_allowed_tokens_fn"] = build_transformers_prefix_allowed_tokens_fn(tokenizer, parser)
|
| 71 |
+
start = time.perf_counter()
|
| 72 |
+
with torch.no_grad():
|
| 73 |
+
out = model.generate(
|
| 74 |
+
**inputs, max_new_tokens=400, do_sample=False, pad_token_id=tokenizer.eos_token_id, **kwargs
|
| 75 |
+
)
|
| 76 |
+
answer = tokenizer.decode(out[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True)
|
| 77 |
+
print(f"{time.perf_counter() - start:5.1f}s {answer[:110]!r}", flush=True)
|
| 78 |
+
self._send(200, {"model": label, "response": answer, "done": True})
|
| 79 |
+
|
| 80 |
+
return Handler
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
parser = argparse.ArgumentParser()
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--adapter", default="experiments/qwen_lora_v1/adapter", help="folder, or 'none' for the base model"
|
| 87 |
+
)
|
| 88 |
+
parser.add_argument("--port", type=int, default=11500)
|
| 89 |
+
parser.add_argument("--base", default=BASE, help="base model: Hugging Face id or a local folder")
|
| 90 |
+
args = parser.parse_args()
|
| 91 |
+
print("loading model ...", flush=True)
|
| 92 |
+
tokenizer, model = load(args.adapter, args.base)
|
| 93 |
+
label = "base" if args.adapter == "none" else "fine-tuned"
|
| 94 |
+
print(f"ready: {label} model at http://127.0.0.1:{args.port}", flush=True)
|
| 95 |
+
HTTPServer(("127.0.0.1", args.port), make_handler(tokenizer, model, label)).serve_forever()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
scripts/qwen_short_questions.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""How do short or vague questions behave at different similarity cutoffs? (CPU only, no language model)
|
| 2 |
+
|
| 3 |
+
python -m scripts.qwen_short_questions
|
| 4 |
+
|
| 5 |
+
For every question this finds the 3 most similar document chunks and records the best similarity.
|
| 6 |
+
A question "succeeds" at a cutoff if a chunk containing the answer sentence is among the results with
|
| 7 |
+
similarity >= cutoff. An unrelated question "leaks" if any chunk passes (so the language model would be asked).
|
| 8 |
+
Output: experiments/qwen_lora_v1/short_question_report.json
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import csv
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
from backend.config import ROOT
|
| 17 |
+
from backend.rag import KnowledgeIndex
|
| 18 |
+
from scripts.qwen_eval import MY_QUESTIONS, OUT, UNANSWERABLE
|
| 19 |
+
|
| 20 |
+
CUTOFFS = [0.30, 0.35, 0.40, 0.45, 0.50]
|
| 21 |
+
|
| 22 |
+
# (3 to 4 word version of the full question, phrase from the answering sentence)
|
| 23 |
+
SHORT = [
|
| 24 |
+
("anomaly score meaning", "not a defect probability"),
|
| 25 |
+
("Uncertain result meaning", "within a fixed five-percent band around the threshold"),
|
| 26 |
+
("Good result guarantee", "not proof of factory acceptance or product safety"),
|
| 27 |
+
("heatmap colours meaning", "shows cosine distance between each image patch feature"),
|
| 28 |
+
("warning what next", "Review source images and heatmaps before acting"),
|
| 29 |
+
("detect defect type", "does not predict specific defect types"),
|
| 30 |
+
("which model old result", "Consult that saved record"),
|
| 31 |
+
("new model old results", "does not change a historical verdict or heatmap"),
|
| 32 |
+
("analysis fails what happens", "Model failures create an error event"),
|
| 33 |
+
("alerts when", "Anomaly and uncertain events create local review alerts"),
|
| 34 |
+
("which products allowed", "wrong-product uploads are outside validated scope"),
|
| 35 |
+
("what is VisA", "VisA provides normal and anomalous product images"),
|
| 36 |
+
("sample photos source", "sample previews are resized JPEG derivatives"),
|
| 37 |
+
("VisA licence", "released by Amazon Science under CC BY 4.0"),
|
| 38 |
+
("trained on defects", "fits on normal images"),
|
| 39 |
+
("original model image size", "a 224 by 224 input"),
|
| 40 |
+
("background filtering", "PCA-based foreground heuristic filters background patches"),
|
| 41 |
+
("how threshold chosen", "maximum heldout normal score"),
|
| 42 |
+
("precision recall threshold", "use a frozen threshold"),
|
| 43 |
+
("accuracy fair test", "not an untouched external test"),
|
| 44 |
+
("copy of published method", "rather than an exact reproduction of AnomalyDINO"),
|
| 45 |
+
("normal images masks", "Normal images have no stored anomaly mask"),
|
| 46 |
+
("explanation about my photo", "must remain separate from saved image measurements"),
|
| 47 |
+
]
|
| 48 |
+
ONE_WORD = [
|
| 49 |
+
("heatmap", "shows cosine distance between each image patch feature"),
|
| 50 |
+
("VisA", "VisA provides normal and anomalous product images"),
|
| 51 |
+
("licence", "released by Amazon Science under CC BY 4.0"),
|
| 52 |
+
("alerts", "Anomaly and uncertain events create local review alerts"),
|
| 53 |
+
("Uncertain", "within a fixed five-percent band around the threshold"),
|
| 54 |
+
("score", "not a defect probability"),
|
| 55 |
+
("AnomalyDINO", "rather than an exact reproduction of AnomalyDINO"),
|
| 56 |
+
("Good", "Good means the score lies below the decision threshold"),
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_full():
|
| 61 |
+
lines = [line for line in MY_QUESTIONS.read_text(encoding="utf-8-sig").splitlines() if not line.startswith("#")]
|
| 62 |
+
rows = list(csv.DictReader(lines))
|
| 63 |
+
full = [(r["question"].strip(), r["answer_phrase"].strip()) for r in rows if r["answer_phrase"].strip()]
|
| 64 |
+
unrelated = [r["question"].strip() for r in rows if r["question"].strip() and not r["answer_phrase"].strip()]
|
| 65 |
+
return full, unrelated
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main():
|
| 69 |
+
index = KnowledgeIndex(ROOT, OUT / "index")
|
| 70 |
+
index.ensure()
|
| 71 |
+
chunks = [d.page_content.lower() for d in index.documents]
|
| 72 |
+
|
| 73 |
+
def probe(text):
|
| 74 |
+
vector = np.asarray(index.embeddings.embed_query(text), dtype="float32")
|
| 75 |
+
scores = index.matrix @ vector
|
| 76 |
+
order = [int(i) for i in np.argsort(scores)[::-1][:3]]
|
| 77 |
+
return [(i, float(scores[i])) for i in order]
|
| 78 |
+
|
| 79 |
+
def success(phrase, hits, cutoff):
|
| 80 |
+
return any(score >= cutoff and phrase.lower() in chunks[i] for i, score in hits)
|
| 81 |
+
|
| 82 |
+
full, unrelated = load_full()
|
| 83 |
+
groups = {"full question": full, "3-4 words": SHORT, "one word": ONE_WORD}
|
| 84 |
+
report = {"cutoffs": CUTOFFS, "on_topic": {}, "unrelated_leak": {}}
|
| 85 |
+
print(f"{'on-topic questions, right answer retrieved':44s}" + "".join(f"{c:>8.2f}" for c in CUTOFFS))
|
| 86 |
+
for name, items in groups.items():
|
| 87 |
+
probes = [(text, phrase, probe(text)) for text, phrase in items]
|
| 88 |
+
row = [sum(success(p, h, c) for _, p, h in probes) for c in CUTOFFS]
|
| 89 |
+
best = sorted(h[0][1] for _, _, h in probes)
|
| 90 |
+
report["on_topic"][name] = {
|
| 91 |
+
"n": len(items),
|
| 92 |
+
"retrieved_at_cutoff": row,
|
| 93 |
+
"lowest_best_similarity": round(best[0], 3),
|
| 94 |
+
"median_best_similarity": round(best[len(best) // 2], 3),
|
| 95 |
+
"below_050": [t for t, _, h in probes if h[0][1] < 0.50],
|
| 96 |
+
}
|
| 97 |
+
print(
|
| 98 |
+
f"{name + f' (n={len(items)})':44s}"
|
| 99 |
+
+ "".join(f"{v:>8d}" for v in row)
|
| 100 |
+
+ f" median best similarity {best[len(best) // 2]:.2f}, lowest {best[0]:.2f}"
|
| 101 |
+
)
|
| 102 |
+
others = unrelated + UNANSWERABLE["train"] + UNANSWERABLE["test"]
|
| 103 |
+
probes = [(text, probe(text)) for text in others]
|
| 104 |
+
print(f"\n{'unrelated questions that still reach the model':44s}" + "".join(f"{c:>8.2f}" for c in CUTOFFS))
|
| 105 |
+
row = [sum(any(score >= c for _, score in hits) for _, hits in probes) for c in CUTOFFS]
|
| 106 |
+
report["unrelated_leak"] = {"n": len(others), "reach_model_at_cutoff": row}
|
| 107 |
+
print(f"{f'unrelated (n={len(others)})':44s}" + "".join(f"{v:>8d}" for v in row))
|
| 108 |
+
(OUT / "short_question_report.json").write_text(json.dumps(report, indent=1), encoding="utf-8")
|
| 109 |
+
print("\nsaved short_question_report.json")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
main()
|
scripts/space_dry_run.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dry run of switching the Hugging Face Space to the fine-tuned model.
|
| 2 |
+
|
| 3 |
+
python -m scripts.space_dry_run
|
| 4 |
+
|
| 5 |
+
It copies deployment/space/generation.py into a temporary folder, applies the proposed change there, checks that the
|
| 6 |
+
result is valid Python and prints what would change. It never writes to deployment/ and uploads nothing.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import ast
|
| 10 |
+
import difflib
|
| 11 |
+
import tempfile
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from backend.config import ROOT
|
| 15 |
+
|
| 16 |
+
LIVE = ROOT / "deployment" / "space" / "generation.py"
|
| 17 |
+
|
| 18 |
+
OLD = """MODEL_ID='Qwen/Qwen3-4B-Instruct-2507'
|
| 19 |
+
REVISION='cdbee75f17c01a7cc42f958dc650907174af0554'
|
| 20 |
+
TOKENIZER=None
|
| 21 |
+
MODEL=None
|
| 22 |
+
if os.getenv('SPACES_ZERO_GPU')=='1' and os.getenv('DEFECTRAG_LIVE_RAG')=='1':
|
| 23 |
+
# Download/cache in the Space only. Never place another 8 GB on the laptop.
|
| 24 |
+
TOKENIZER=AutoTokenizer.from_pretrained(MODEL_ID,revision=REVISION)
|
| 25 |
+
MODEL=AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=REVISION,
|
| 26 |
+
dtype=torch.bfloat16,attn_implementation='sdpa').eval().to('cuda')"""
|
| 27 |
+
|
| 28 |
+
NEW = """# Fine-tuned Qwen2.5-3B-Instruct (QLoRA adapter merged into the base weights, bf16, about 6 GB).
|
| 29 |
+
# Results: docs/QWEN_FINETUNING_RESULTS.md. Improved using Qwen (Qwen Research License, non-commercial).
|
| 30 |
+
MODEL_ID=os.getenv('DEFECTRAG_MODEL_ID','Wizzas/defectrag-qwen2.5-3b-evidence')
|
| 31 |
+
REVISION=os.getenv('DEFECTRAG_MODEL_REVISION','') # pin to the uploaded commit hash before going live
|
| 32 |
+
HF_TOKEN=os.getenv('HF_TOKEN') # Space secret; needed while the model repo is private
|
| 33 |
+
TOKENIZER=None
|
| 34 |
+
MODEL=None
|
| 35 |
+
if os.getenv('SPACES_ZERO_GPU')=='1' and os.getenv('DEFECTRAG_LIVE_RAG')=='1':
|
| 36 |
+
if not REVISION:
|
| 37 |
+
raise RuntimeError('Set DEFECTRAG_MODEL_REVISION to the pinned commit of the fine-tuned model')
|
| 38 |
+
# Download/cache in the Space only. Never place another 6 GB on the laptop.
|
| 39 |
+
TOKENIZER=AutoTokenizer.from_pretrained(MODEL_ID,revision=REVISION,token=HF_TOKEN)
|
| 40 |
+
MODEL=AutoModelForCausalLM.from_pretrained(MODEL_ID,revision=REVISION,token=HF_TOKEN,
|
| 41 |
+
dtype=torch.bfloat16,attn_implementation='sdpa').eval().to('cuda')"""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def main():
|
| 45 |
+
original = LIVE.read_text(encoding="utf-8")
|
| 46 |
+
if OLD not in original:
|
| 47 |
+
raise SystemExit("The live file no longer contains the expected block, so the proposal needs updating.")
|
| 48 |
+
proposed = original.replace(OLD, NEW)
|
| 49 |
+
ast.parse(proposed) # raises if the result is not valid Python
|
| 50 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 51 |
+
copy = Path(folder) / "generation.py"
|
| 52 |
+
copy.write_text(proposed, encoding="utf-8")
|
| 53 |
+
print(f"1. proposal written to a temporary copy ({copy.name}) and checked: valid Python")
|
| 54 |
+
print("2. live file left unchanged:", LIVE)
|
| 55 |
+
print("3. what would change:\n")
|
| 56 |
+
diff = difflib.unified_diff(original.splitlines(), proposed.splitlines(), "live", "proposed", lineterm="", n=1)
|
| 57 |
+
print("\n".join(diff))
|
| 58 |
+
print("\nNothing was uploaded and nothing in deployment/ was modified.")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
main()
|
scripts/summarize_accuracy.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare saved official test predictions and reports, without model execution."""
|
| 2 |
+
import csv,json
|
| 3 |
+
import numpy as np
|
| 4 |
+
from backend.config import ROOT,CATEGORIES
|
| 5 |
+
from scripts.benchmark_official import write
|
| 6 |
+
|
| 7 |
+
if __name__=='__main__':
|
| 8 |
+
old=json.loads((ROOT/'results/official_evaluation.json').read_text())
|
| 9 |
+
new=json.loads((ROOT/'results/highres_evaluation.json').read_text())
|
| 10 |
+
assert set(new['categories'])==set(CATEGORIES)
|
| 11 |
+
rows=[]
|
| 12 |
+
for category in CATEGORIES:
|
| 13 |
+
a=json.loads((ROOT/'experiments/official_visa_v1'/category/'split.json').read_text())
|
| 14 |
+
b=json.loads((ROOT/'experiments/dinov2_highres_v1'/category/'split.json').read_text())
|
| 15 |
+
assert {r['image']:r['sha256'] for r in a['test']}=={r['image']:r['sha256'] for r in b['test']}
|
| 16 |
+
before=old['categories'][category]['benchmark_mean'];after=new['categories'][category]['benchmark_mean']
|
| 17 |
+
rows.append({'category':category,'old_image_auroc':before['auroc'],'new_image_auroc':after['auroc'],
|
| 18 |
+
'auroc_change_pp':(after['auroc']-before['auroc'])*100,'old_image_ap':before['average_precision'],
|
| 19 |
+
'new_image_ap':after['average_precision'],'old_pixel_ap':before['pixel_average_precision'],
|
| 20 |
+
'new_pixel_ap':after['pixel_average_precision']})
|
| 21 |
+
for report in (old,new):
|
| 22 |
+
for metric in report['macro_mean']:
|
| 23 |
+
assert abs(report['macro_mean'][metric]-np.mean([c['benchmark_mean'][metric] for c in report['categories'].values()]))<1e-12
|
| 24 |
+
result={'status':'passed','same_official_test_identities_and_content_hashes':True,
|
| 25 |
+
'baseline_macro':old['macro_mean'],'candidate_macro':new['macro_mean'],'candidate_macro_std':new['macro_std'],
|
| 26 |
+
'all_categories':rows,'image_auroc_regressions':[r['category'] for r in rows if r['auroc_change_pp']<0],
|
| 27 |
+
'pixel_ap_regressions':[r['category'] for r in rows if r['new_pixel_ap']<r['old_pixel_ap']],
|
| 28 |
+
'metric_definitions':'Image mAP=unweighted mean of12 category image APs, averaged over3 seeds. Pixel mAP analogous. AU-PR trapezoidal, AP non-interpolated. Seed SD is bank variability, not a generalization confidence interval.',
|
| 29 |
+
'exposure':'Retrospective model development comparison; not an untouched external test.'}
|
| 30 |
+
write(ROOT/'results/highres_comparison.json',result)
|
| 31 |
+
with (ROOT/'results/highres_comparison.csv').open('w',newline='',encoding='utf-8') as stream:
|
| 32 |
+
writer=csv.DictWriter(stream,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
|
| 33 |
+
lines=['# Measured accuracy comparison','',
|
| 34 |
+
'Same official test identities and content hashes. Three fixed seeds, all12 categories. Retrospective development evaluation; no new untouched-test claim.','',
|
| 35 |
+
'| Product | Original AUROC | DINOv2 AUROC | Change (pp) | Original AP | DINOv2 AP |',
|
| 36 |
+
'|---|---:|---:|---:|---:|---:|']
|
| 37 |
+
lines += [f"| {r['category']} | {r['old_image_auroc']:.4f} | {r['new_image_auroc']:.4f} | {r['auroc_change_pp']:+.2f} | {r['old_image_ap']:.4f} | {r['new_image_ap']:.4f} |" for r in rows]
|
| 38 |
+
lines += ['', '| Overall metric | Original | DINOv2 |','|---|---:|---:|']
|
| 39 |
+
for label,key in [('Mean image AUROC · headline','auroc'),('Mean image AU-PR','au_pr'),('Mean pixel AUROC','pixel_auroc'),('Mean pixel AU-PR','pixel_au_pr'),('Supplementary mean image AP','average_precision'),('Supplementary mean pixel AP','pixel_average_precision')]:
|
| 40 |
+
lines.append(f"| {label} | {old['macro_mean'][key]*100:.2f}% | {new['macro_mean'][key]*100:.2f}% |")
|
| 41 |
+
lines += ['', 'Image AUROC regressions: '+(', '.join(result['image_auroc_regressions']) or 'none')+'.',
|
| 42 |
+
'Pixel AP regressions: '+(', '.join(result['pixel_ap_regressions']) or 'none')+'.',
|
| 43 |
+
'mAP here averages anomaly-ranking AP across products; it is not bounding-box mAP@IoU.','',
|
| 44 |
+
'The benchmark uses all training normals. The deployed bank is a separate fixed-seed profile with a normal-only calibration holdout; see results/highres_deployment_evaluation.json. Historical inspections keep their original model IDs.']
|
| 45 |
+
(ROOT/'docs/ACCURACY_RESULTS.md').write_text('\n'.join(lines)+'\n',encoding='utf-8')
|
| 46 |
+
print(json.dumps({k:v for k,v in result.items() if k not in ('all_categories',)},indent=2),flush=True)
|
scripts/train.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded normal-only memory fitting, independent calibration and final evaluation.
|
| 2 |
+
Run as python -m scripts.train --dataset PATH --encoder PATH.
|
| 3 |
+
"""
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
import platform
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from sklearn.metrics import (roc_auc_score, average_precision_score, precision_score, recall_score,
|
| 15 |
+
f1_score, confusion_matrix, precision_recall_curve)
|
| 16 |
+
from backend.vision import Encoder, map_and_score, sha256
|
| 17 |
+
from backend.config import ROOT, CATEGORIES
|
| 18 |
+
|
| 19 |
+
def make_split(rows, category, seed=42, train_count=64):
|
| 20 |
+
rng = np.random.default_rng(seed)
|
| 21 |
+
normal = sorted([r for r in rows if r['object'] == category and r['split']=='train' and r['label']=='normal'], key=lambda x:x['image'])
|
| 22 |
+
test_good = sorted([r for r in rows if r['object']==category and r['split']=='test' and r['label']=='normal'], key=lambda x:x['image'])
|
| 23 |
+
test_bad = sorted([r for r in rows if r['object']==category and r['split']=='test' and r['label']!='normal'], key=lambda x:x['image'])
|
| 24 |
+
rng.shuffle(normal); rng.shuffle(test_bad)
|
| 25 |
+
if len(normal) < train_count+32 or len(test_bad)<40 or not test_good:
|
| 26 |
+
raise ValueError('Dataset split is incomplete')
|
| 27 |
+
# No labelled anomalies enter fitting. Twenty test anomalies are explicitly
|
| 28 |
+
# reassigned to calibration; the result is NOT the full official test protocol.
|
| 29 |
+
return {'train':normal[:train_count], 'validation':normal[train_count:train_count+32]+test_bad[:20], 'test':test_good+test_bad[20:]}
|
| 30 |
+
|
| 31 |
+
def binary_metrics(labels, scores, threshold):
|
| 32 |
+
prediction = np.asarray(scores) >= threshold
|
| 33 |
+
return {'image_auroc':float(roc_auc_score(labels,scores)), 'average_precision':float(average_precision_score(labels,scores)),
|
| 34 |
+
'precision':float(precision_score(labels,prediction,zero_division=0)), 'recall':float(recall_score(labels,prediction,zero_division=0)),
|
| 35 |
+
'f1':float(f1_score(labels,prediction,zero_division=0)), 'confusion_matrix':confusion_matrix(labels,prediction,labels=[0,1]).tolist(),
|
| 36 |
+
'n_images':len(labels)}
|
| 37 |
+
|
| 38 |
+
def calibrate(labels, scores):
|
| 39 |
+
p,r,t = precision_recall_curve(labels,scores)
|
| 40 |
+
f = 2*p[:-1]*r[:-1]/np.maximum(p[:-1]+r[:-1],1e-12)
|
| 41 |
+
return float(t[int(np.argmax(f))])
|
| 42 |
+
|
| 43 |
+
def evaluate(encoder, bank, rows, dataset):
|
| 44 |
+
predictions, maps, masks = [], [], []
|
| 45 |
+
for row in rows:
|
| 46 |
+
start = time.perf_counter()
|
| 47 |
+
with Image.open(dataset / row['image']) as im:
|
| 48 |
+
raw,score = map_and_score(encoder,bank,im)
|
| 49 |
+
elapsed = (time.perf_counter()-start)*1000
|
| 50 |
+
label = int(row['label']!='normal')
|
| 51 |
+
predictions.append({'image':row['image'], 'sha256':sha256(dataset/row['image']), 'label':label, 'score':score, 'latency_ms':elapsed})
|
| 52 |
+
# Explicitly report reduced-resolution pixel metrics including normal images.
|
| 53 |
+
maps.append(np.asarray(Image.fromarray(raw).resize((64,64),Image.Resampling.BILINEAR)).ravel())
|
| 54 |
+
if label:
|
| 55 |
+
with Image.open(dataset/row['mask']) as mask:
|
| 56 |
+
masks.append((np.asarray(mask.convert('L').resize((64,64),Image.Resampling.NEAREST))>0).ravel())
|
| 57 |
+
else:
|
| 58 |
+
masks.append(np.zeros(64*64,dtype=bool))
|
| 59 |
+
return predictions,np.concatenate(maps),np.concatenate(masks)
|
| 60 |
+
|
| 61 |
+
def main():
|
| 62 |
+
parser=argparse.ArgumentParser()
|
| 63 |
+
parser.add_argument('--dataset',type=Path,required=True)
|
| 64 |
+
parser.add_argument('--encoder',required=True)
|
| 65 |
+
parser.add_argument('--device',default='auto')
|
| 66 |
+
parser.add_argument('--train-count',type=int,default=64)
|
| 67 |
+
parser.add_argument('--categories',nargs='+',choices=CATEGORIES,default=list(CATEGORIES))
|
| 68 |
+
parser.add_argument('--resume',action='store_true',help='Skip completed categories; preserve and extend existing evaluation')
|
| 69 |
+
args=parser.parse_args()
|
| 70 |
+
report_path=ROOT/'results'/'evaluation.json'
|
| 71 |
+
previous=json.loads(report_path.read_text()) if report_path.exists() else None
|
| 72 |
+
completed=[]
|
| 73 |
+
for category in args.categories:
|
| 74 |
+
files=[ROOT/'models'/f'{category}.npz',ROOT/'models'/f'{category}.json',
|
| 75 |
+
ROOT/'results'/f'{category}_splits.json',ROOT/'results'/f'{category}_predictions.json']
|
| 76 |
+
if any(p.exists() for p in files):
|
| 77 |
+
if not (args.resume and all(p.exists() for p in files) and category in (previous or {}).get('categories',{})):
|
| 78 |
+
raise RuntimeError('Existing artifacts preserved; inspect category before continuing: '+category)
|
| 79 |
+
card=json.loads(files[1].read_text())
|
| 80 |
+
if card['bank_sha256']!=sha256(files[0]) or card['train_normal_count']!=args.train_count:
|
| 81 |
+
raise RuntimeError('Saved category does not match requested configuration: '+category)
|
| 82 |
+
completed.append(category)
|
| 83 |
+
print('Preserved completed category: '+category,flush=True)
|
| 84 |
+
pending=[c for c in args.categories if c not in completed]
|
| 85 |
+
if not pending:
|
| 86 |
+
print('All requested categories already complete; no experiment repeated.',flush=True)
|
| 87 |
+
return
|
| 88 |
+
rows=list(csv.DictReader((args.dataset/'split_csv'/'1cls.csv').open(newline='')))
|
| 89 |
+
# Profile one forward before fitting all categories. No gradient training here.
|
| 90 |
+
encoder=Encoder(args.encoder,args.device)
|
| 91 |
+
encoder_path=Path(args.encoder)
|
| 92 |
+
if not encoder_path.is_dir():
|
| 93 |
+
from huggingface_hub import snapshot_download
|
| 94 |
+
encoder_path=Path(snapshot_download(args.encoder,local_files_only=True))
|
| 95 |
+
fingerprint=sha256(encoder_path/'model.safetensors')
|
| 96 |
+
report={'method':'Frozen DINOv3 ViT-S/16 + cosine nearest-normal patch bank',
|
| 97 |
+
'protocol':'64 normal fit images; 32 distinct training normals + 20 official test anomalies for calibration; remaining official test images for final evaluation. Seed 42. Not the full official VisA test protocol.',
|
| 98 |
+
'platform':platform.platform(),'python':platform.python_version(),'torch':torch.__version__,
|
| 99 |
+
'device':str(encoder.device),'encoder_sha256':fingerprint,'categories':{}}
|
| 100 |
+
if previous:
|
| 101 |
+
if previous['encoder_sha256']!=fingerprint:
|
| 102 |
+
raise RuntimeError('Encoder differs from existing evaluation; use a separate experiment')
|
| 103 |
+
report=previous
|
| 104 |
+
for category in pending:
|
| 105 |
+
start=time.perf_counter()
|
| 106 |
+
splits=make_split(rows,category,train_count=args.train_count)
|
| 107 |
+
hashes={name:{sha256(args.dataset/r['image']) for r in group} for name,group in splits.items()}
|
| 108 |
+
if any(hashes[a]&hashes[b] for a,b in [('train','validation'),('train','test'),('validation','test')]):
|
| 109 |
+
raise ValueError('Cross-split content overlap detected')
|
| 110 |
+
if encoder.device.type=='cuda':
|
| 111 |
+
torch.cuda.reset_peak_memory_stats()
|
| 112 |
+
features=[]
|
| 113 |
+
for row in splits['train']:
|
| 114 |
+
with Image.open(args.dataset/row['image']) as im:
|
| 115 |
+
features.append(encoder.patches(im)[0].cpu())
|
| 116 |
+
bank=torch.cat(features)
|
| 117 |
+
indices=np.random.default_rng(42).choice(len(bank),min(8192,len(bank)),replace=False)
|
| 118 |
+
bank=bank[indices]
|
| 119 |
+
staging=ROOT/'runtime'/'training';staging.mkdir(parents=True,exist_ok=True)
|
| 120 |
+
bank_path=staging/f'{category}.npz'
|
| 121 |
+
np.savez_compressed(bank_path,patches=bank.numpy().astype('float16'))
|
| 122 |
+
# Use exactly the saved bank precision for calibration and test.
|
| 123 |
+
bank=F.normalize(torch.from_numpy(np.load(bank_path)['patches'].astype('float32')).to(encoder.device),dim=-1)
|
| 124 |
+
val,vmaps,vmasks=evaluate(encoder,bank,splits['validation'],args.dataset)
|
| 125 |
+
threshold=calibrate([x['label'] for x in val],[x['score'] for x in val])
|
| 126 |
+
pixel_threshold=calibrate(vmasks,vmaps)
|
| 127 |
+
test,tmaps,tmasks=evaluate(encoder,bank,splits['test'],args.dataset)
|
| 128 |
+
metrics=binary_metrics([x['label'] for x in test],[x['score'] for x in test],threshold)
|
| 129 |
+
metrics.update({'pixel_auroc_64':float(roc_auc_score(tmasks,tmaps)),
|
| 130 |
+
'pixel_average_precision_64':float(average_precision_score(tmasks,tmaps)),
|
| 131 |
+
'pixel_f1_64':float(f1_score(tmasks,tmaps>=pixel_threshold,zero_division=0)),
|
| 132 |
+
'pixel_threshold':pixel_threshold,
|
| 133 |
+
'latency_median_ms':float(np.median([x['latency_ms'] for x in test])),
|
| 134 |
+
'latency_p95_ms':float(np.percentile([x['latency_ms'] for x in test],95)),
|
| 135 |
+
'peak_gpu_mb':torch.cuda.max_memory_allocated()/1024**2 if encoder.device.type=='cuda' else None})
|
| 136 |
+
margin=threshold*.05
|
| 137 |
+
metrics['uncertain_fraction']=float(np.mean([abs(x['score']-threshold)<=margin for x in test]))
|
| 138 |
+
card={'category':category,'available':True,'model_id':f'dinov3-normal-bank-{category}-v1','method':report['method'],
|
| 139 |
+
'encoder_sha256':fingerprint,'bank_sha256':sha256(bank_path),'threshold':threshold,'uncertainty_margin':margin,
|
| 140 |
+
'uncertainty_policy':'Fixed ±5% of validated threshold. Operational review band, not calibrated confidence.',
|
| 141 |
+
'heatmap_scale':float(np.quantile(vmaps,.995)),'bank_size_bytes':bank_path.stat().st_size,
|
| 142 |
+
'encoder_size_bytes':(encoder_path/'model.safetensors').stat().st_size,
|
| 143 |
+
'calibration':{'method':'Max F1 on separate validation identities','normal':32,'anomalous':20,'seed':42},
|
| 144 |
+
'train_normal_count':len(splits['train']),'metrics':metrics,'fit_and_evaluation_seconds':time.perf_counter()-start}
|
| 145 |
+
manifest={name:[{**r,'sha256':sha256(args.dataset/r['image'])} for r in group] for name,group in splits.items()}
|
| 146 |
+
(ROOT/'results'/f'{category}_splits.json').write_text(json.dumps(manifest,indent=2))
|
| 147 |
+
(ROOT/'results'/f'{category}_predictions.json').write_text(json.dumps({'validation':val,'test':test},indent=2))
|
| 148 |
+
final_bank=ROOT/'models'/f'{category}.npz'
|
| 149 |
+
if final_bank.exists():raise RuntimeError('Refusing to overwrite an existing bank')
|
| 150 |
+
bank_path.replace(final_bank)
|
| 151 |
+
(ROOT/'models'/f'{category}.json').write_text(json.dumps(card,indent=2))
|
| 152 |
+
report['categories'][category]=card
|
| 153 |
+
(ROOT/'results'/'evaluation.json').write_text(json.dumps(report,indent=2))
|
| 154 |
+
print(category,json.dumps(metrics),flush=True)
|
| 155 |
+
for label,name in [('normal','good'),('anomaly','anomalous')]:
|
| 156 |
+
row=next(r for r in splits['test'] if (r['label']=='normal')==(label=='normal'))
|
| 157 |
+
with Image.open(args.dataset/row['image']) as im:
|
| 158 |
+
im=im.convert('RGB'); im.thumbnail((640,640)); im.save(ROOT/'samples'/f'{category}_{name}.jpg',quality=90)
|
| 159 |
+
print('Completed. Final metrics are frozen; do not tune against final-test labels.',flush=True)
|
| 160 |
+
|
| 161 |
+
if __name__=='__main__': main()
|
scripts/train_anomalib.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional Anomalib Dinomaly experiment; unverified, never started automatically.
|
| 2 |
+
|
| 3 |
+
Uses the same frozen identity manifest as the compact detector. DINOv3 is not
|
| 4 |
+
silently passed to a DINOv2-only interface. Export is deliberately separate from
|
| 5 |
+
the shipped memory-bank API until independently evaluated and integrated.
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from backend.config import ROOT
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
parser=argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument('--dataset',type=Path,required=True)
|
| 15 |
+
parser.add_argument('--category',choices=['pcb1','capsules','cashew'],required=True)
|
| 16 |
+
parser.add_argument('--authorize-training',action='store_true')
|
| 17 |
+
parser.add_argument('--steps',type=int,default=500)
|
| 18 |
+
args=parser.parse_args()
|
| 19 |
+
if not args.authorize_training: parser.error('Requires approval via --authorize-training; may download a DINOv2 backbone')
|
| 20 |
+
from anomalib.models import Dinomaly
|
| 21 |
+
from anomalib.engine import Engine
|
| 22 |
+
from anomalib.data import Folder
|
| 23 |
+
import shutil
|
| 24 |
+
import torch
|
| 25 |
+
if not torch.cuda.is_available(): raise RuntimeError('This optional training path requires a compatible CUDA runtime')
|
| 26 |
+
free,total=torch.cuda.mem_get_info()
|
| 27 |
+
print(f'GPU memory before model: {free/1024**3:.2f} GiB free / {total/1024**3:.2f} GiB total')
|
| 28 |
+
if free<4*1024**3: raise RuntimeError('Less than 4 GiB free; stop and profile before training')
|
| 29 |
+
split=json.loads((ROOT/'results'/f'{args.category}_splits.json').read_text())
|
| 30 |
+
staging=ROOT/'runtime'/'anomalib-data'/args.category
|
| 31 |
+
for partition,rows in split.items():
|
| 32 |
+
for row in rows:
|
| 33 |
+
label='good' if row['label']=='normal' else 'bad'
|
| 34 |
+
destination=staging/partition/label/Path(row['image']).name
|
| 35 |
+
destination.parent.mkdir(parents=True,exist_ok=True)
|
| 36 |
+
if not destination.exists():shutil.copyfile(args.dataset/row['image'],destination)
|
| 37 |
+
# Folder automatic validation must not consume final test images: the
|
| 38 |
+
# manifest validation set is passed explicitly using validation directories.
|
| 39 |
+
datamodule=Folder(name=args.category,root=staging,normal_dir='train/good',normal_test_dir='validation/good',abnormal_dir='validation/bad',val_split_mode='same_as_test',train_batch_size=2,eval_batch_size=2,num_workers=0)
|
| 40 |
+
model=Dinomaly(encoder_name='vit_small_patch14_dinov2',decoder_depth=4,
|
| 41 |
+
target_layers=[2,3,4,5],fuse_layer_encoder=[[0,1],[2,3]],fuse_layer_decoder=[[0,1],[2,3]])
|
| 42 |
+
engine=Engine(default_root_dir=str(ROOT/'runtime'/'anomalib-training'),max_steps=args.steps,accelerator='gpu',devices=1)
|
| 43 |
+
engine.fit(model,datamodule=datamodule)
|
| 44 |
+
engine.trainer.save_checkpoint(str(ROOT/'runtime'/'anomalib-training'/f'{args.category}.ckpt'))
|
| 45 |
+
print('Experimental checkpoint saved. Final-test evaluation and API adapter remain required; do not replace calibrated production cards.')
|
| 46 |
+
if __name__=='__main__':main()
|
scripts/verify_all_categories.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verify new categories through the real API, preserving existing runtime history."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
from backend.main import create_app
|
| 6 |
+
from backend.config import ROOT, Settings, CATEGORIES
|
| 7 |
+
from backend.storage import SQLiteRepository
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
dataset=Path(r'C:\Users\User\Downloads\VisA_20220922')
|
| 12 |
+
evaluation=json.loads((ROOT/'results/evaluation.json').read_text())
|
| 13 |
+
assert set(evaluation['categories'])==set(CATEGORIES)
|
| 14 |
+
records=[]
|
| 15 |
+
# Separate persistent verification history; never replace the user's database.
|
| 16 |
+
data=ROOT/'runtime'/'verification12'
|
| 17 |
+
repo=SQLiteRepository(data/'inspection.sqlite3')
|
| 18 |
+
app=create_app(Settings(data=data))
|
| 19 |
+
with TestClient(app) as client:
|
| 20 |
+
for category in CATEGORIES:
|
| 21 |
+
manifest=json.loads((ROOT/'results'/f'{category}_splits.json').read_text())
|
| 22 |
+
hashes={k:{r['sha256'] for r in rows} for k,rows in manifest.items()}
|
| 23 |
+
assert all(not hashes[a]&hashes[b] for a,b in [('train','validation'),('train','test'),('validation','test')])
|
| 24 |
+
if category in ('pcb1','capsules','cashew'):continue
|
| 25 |
+
predictions=json.loads((ROOT/'results'/f'{category}_predictions.json').read_text())['test']
|
| 26 |
+
for truth in (0,1):
|
| 27 |
+
row=next(r for r in predictions if r['label']==truth)
|
| 28 |
+
existing=next((r for r in repo.list(category=category,limit=100) if r.get('filename')==Path(row['image']).name),None)
|
| 29 |
+
if existing:record=existing
|
| 30 |
+
else:
|
| 31 |
+
path=dataset/row['image']
|
| 32 |
+
response=client.post('/api/inspect',data={'category':category,'batch':'All-category verification'},
|
| 33 |
+
files={'file':(path.name,path.read_bytes(),'image/jpeg')})
|
| 34 |
+
assert response.status_code==200,response.text
|
| 35 |
+
record=response.json()['data']
|
| 36 |
+
assert abs(record['score']-row['score'])<1e-6
|
| 37 |
+
assert client.get(record['heatmap_url']).status_code==200
|
| 38 |
+
assert client.get('/api/inspections/'+record['id']+'/report').status_code==200
|
| 39 |
+
records.append({'id':record['id'],'category':category,'truth':truth,'score':record['score'],'verdict':record['verdict']})
|
| 40 |
+
print('API verified: '+category,flush=True)
|
| 41 |
+
receipt={'status':'passed','categories':list(CATEGORIES),'real_images':records,
|
| 42 |
+
'data_directory':'runtime/verification12','new_records':len(records),'split_hash_checks':'passed',
|
| 43 |
+
'scores_match_saved_evaluation':True,'original_three':'preserved; not repeated'}
|
| 44 |
+
(ROOT/'results/all_categories_acceptance.json').write_text(json.dumps(receipt,indent=2))
|
| 45 |
+
print(json.dumps({'status':'passed','categories':12,'new_real_api_images':len(records)}),flush=True)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__=='__main__':main()
|
scripts/verify_assistant_quality.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture real upgraded answers against an isolated running inspection workspace."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import httpx
|
| 5 |
+
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
IDENTIFIER='a6226ef392eb417e8991369e890d816b'
|
| 8 |
+
QUESTIONS=['So this product is anomaly right?','Does 0.09 mean 9% accurate?',
|
| 9 |
+
'What does this inspection heatmap show?','How does that map relate to the anomaly score?',
|
| 10 |
+
'What caused this defect?']
|
| 11 |
+
|
| 12 |
+
if __name__=='__main__':
|
| 13 |
+
path=ROOT/'results/assistant_quality_verification.json'
|
| 14 |
+
report=json.loads(path.read_text()) if path.exists() else {'status':'running','inspection_id':IDENTIFIER,'answers':[]}
|
| 15 |
+
with httpx.Client(base_url='http://127.0.0.1:8780',timeout=120,trust_env=False) as client:
|
| 16 |
+
record=client.get('/api/inspections/'+IDENTIFIER).json()['data']
|
| 17 |
+
for question in QUESTIONS:
|
| 18 |
+
if any(a['question']==question for a in report['answers']):continue
|
| 19 |
+
response=client.post('/api/assistant',json={'inspection_id':IDENTIFIER,'question':question});response.raise_for_status()
|
| 20 |
+
answer=response.json()['data']
|
| 21 |
+
assert f"{record['score']:.5f}" in answer['answer']
|
| 22 |
+
report['answers'].append({'question':question,**answer})
|
| 23 |
+
path.write_text(json.dumps(report,indent=2))
|
| 24 |
+
print(question+' -> '+answer['mode'],flush=True)
|
| 25 |
+
assert report['answers'][0]['mode']=='measurement_only' and report['answers'][0]['answer'].startswith('Yes—')
|
| 26 |
+
assert report['answers'][1]['mode']=='measurement_only' and 'not an accuracy percentage' in report['answers'][1]['answer']
|
| 27 |
+
assert all(a['mode']=='llm' for a in report['answers'][2:4])
|
| 28 |
+
for answer in report['answers'][2:4]:
|
| 29 |
+
sources={s['chunk_id']:s for s in answer['evidence']}
|
| 30 |
+
assert answer['claims']
|
| 31 |
+
assert all(c['quote'] in sources[c['source_id']]['text'] for c in answer['claims'])
|
| 32 |
+
assert report['answers'][4]['mode']=='abstained'
|
| 33 |
+
report.update(status='passed',checks={'saved_verdict_and_score':True,'score_not_accuracy':True,
|
| 34 |
+
'real_local_qwen_explanations':2,'followup_with_quotes':True,'unsupported_root_cause_abstains':True,
|
| 35 |
+
'scope':'five developer acceptance cases; not a general RAG accuracy benchmark'})
|
| 36 |
+
path.write_text(json.dumps(report,indent=2))
|
| 37 |
+
print(json.dumps(report['checks']),flush=True)
|
scripts/verify_evidence_scope.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real local RAG verification of the previously failing heatmap explanation."""
|
| 2 |
+
import json
|
| 3 |
+
import time
|
| 4 |
+
import httpx
|
| 5 |
+
from backend.config import ROOT
|
| 6 |
+
|
| 7 |
+
if __name__=='__main__':
|
| 8 |
+
report={'status':'running','answers':[]}
|
| 9 |
+
path=ROOT/'results'/'evidence_scope_verification.json'
|
| 10 |
+
try:
|
| 11 |
+
with httpx.Client(base_url='http://127.0.0.1:8766',timeout=120,trust_env=False) as client:
|
| 12 |
+
record=client.get('/api/inspections?category=pcb1').json()['data'][0]
|
| 13 |
+
report['inspection_id']=record['id']
|
| 14 |
+
for question in ('What does this inspection heatmap show?','How does that map relate to anomaly scoring?'):
|
| 15 |
+
started=time.perf_counter()
|
| 16 |
+
response=client.post('/api/assistant',json={'inspection_id':record['id'],'question':question})
|
| 17 |
+
response.raise_for_status();answer=response.json()['data']
|
| 18 |
+
report['answers'].append({'question':question,'seconds':time.perf_counter()-started,**answer})
|
| 19 |
+
path.write_text(json.dumps(report,indent=2))
|
| 20 |
+
assert answer['mode']=='llm',answer
|
| 21 |
+
assert not any(d['id']=='dinomaly' for d in answer['evidence'])
|
| 22 |
+
assert any('cosine distance' in d['text'] for d in answer['evidence'])
|
| 23 |
+
for claim in answer['claims']:
|
| 24 |
+
source=next(d for d in answer['evidence'] if d['chunk_id']==claim['source_id'])
|
| 25 |
+
assert claim['quote'] in source['text']
|
| 26 |
+
print(question,answer['answer'],flush=True)
|
| 27 |
+
report['status']='passed'
|
| 28 |
+
except Exception as exc:
|
| 29 |
+
report['status']='failed';report['failure']=str(exc)
|
| 30 |
+
raise
|
| 31 |
+
finally:path.write_text(json.dumps(report,indent=2))
|
scripts/verify_highres_application.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real isolated API/CPU/RAG acceptance of the installed high-resolution profile."""
|
| 2 |
+
import json
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from fastapi.testclient import TestClient
|
| 5 |
+
from backend.config import ROOT,CATEGORIES,Settings
|
| 6 |
+
from backend.main import create_app
|
| 7 |
+
from backend.highres import HighResolutionDetector
|
| 8 |
+
from backend.vision import sha256
|
| 9 |
+
from scripts.benchmark_official import write
|
| 10 |
+
|
| 11 |
+
if __name__=='__main__':
|
| 12 |
+
output=ROOT/'results/highres_application_verification.json'
|
| 13 |
+
report=json.loads(output.read_text()) if output.exists() else {'status':'running','examples':[],'answers':[]}
|
| 14 |
+
app=create_app(Settings(data=ROOT/'runtime/highres-acceptance',profile='dinov2_highres_v1'))
|
| 15 |
+
with TestClient(app) as client:
|
| 16 |
+
health=client.get('/api/health').json()['data']
|
| 17 |
+
assert len(health['models'])==12 and all(c['model_id'].startswith('dinov2-highres-') for c in health['models'])
|
| 18 |
+
for category in CATEGORIES:
|
| 19 |
+
for label,truth in [('good',0),('anomalous',1)]:
|
| 20 |
+
if any(e['category']==category and e['truth']==truth for e in report['examples']):continue
|
| 21 |
+
sample=ROOT/'samples'/f'{category}_{label}.jpg'
|
| 22 |
+
response=client.post('/api/inspect',data={'category':category,'batch':'highres-acceptance'},
|
| 23 |
+
files={'file':(sample.name,sample.read_bytes(),'image/jpeg')})
|
| 24 |
+
response.raise_for_status();record=response.json()['data']
|
| 25 |
+
assert record['model_id']==f'dinov2-highres-{category}-v1'
|
| 26 |
+
assert record['model_sha256']==sha256(ROOT/'models/highres'/f'{category}.npz')
|
| 27 |
+
assert record['calibration']['anomalous']==0 and 'PCA' in record['localization']
|
| 28 |
+
for url in (record['image_url'],record['heatmap_url'],f"/api/inspections/{record['id']}/report"):
|
| 29 |
+
assert client.get(url).status_code==200
|
| 30 |
+
actual=client.get('/api/inspections/'+record['id']).json()['data']
|
| 31 |
+
assert actual['score']==record['score']
|
| 32 |
+
report['examples'].append({'category':category,'truth':truth,**{k:record[k] for k in ('id','model_id','verdict','score','threshold','inference_ms','peak_gpu_mb','localization','foreground_fraction')}})
|
| 33 |
+
write(output,report);print(category+' '+label+' -> '+record['verdict']+' '+str(round(record['score'],5)),flush=True)
|
| 34 |
+
target=next(e for e in report['examples'] if e['category']=='macaroni2' and e['truth']==1)
|
| 35 |
+
questions=['Is this image anomalous?','Does the score mean accuracy?',
|
| 36 |
+
'What does this saved inspection heatmap show?','How was this model threshold calibrated?',
|
| 37 |
+
'What caused this defect?']
|
| 38 |
+
for question in questions:
|
| 39 |
+
if any(a['question']==question for a in report['answers']):continue
|
| 40 |
+
response=client.post('/api/assistant',json={'inspection_id':target['id'],'question':question})
|
| 41 |
+
response.raise_for_status();answer=response.json()['data']
|
| 42 |
+
assert f"{target['score']:.5f}" in answer['answer']
|
| 43 |
+
assert all(s.get('model_family')!='dinov3' for s in answer['evidence'])
|
| 44 |
+
report['answers'].append({'question':question,**answer});write(output,report)
|
| 45 |
+
print(question+' -> '+answer['mode'],flush=True)
|
| 46 |
+
assert all(a['mode']=='measurement_only' for a in report['answers'][:2])
|
| 47 |
+
assert report['answers'][2]['mode']=='llm',report['answers'][2]
|
| 48 |
+
assert report['answers'][-1]['mode']=='abstained'
|
| 49 |
+
assert client.get('/api/evaluation').json()['data']['profile']=='dinov2_highres_v1'
|
| 50 |
+
official=client.get('/api/benchmark/official').json()['data']
|
| 51 |
+
assert len(official['candidate']['categories'])==12
|
| 52 |
+
assert target['id'] in client.get('/api/export.csv').text
|
| 53 |
+
if not report.get('cpu_smoke'):
|
| 54 |
+
cpu=HighResolutionDetector(Settings(device='cpu',profile='dinov2_highres_v1'))
|
| 55 |
+
with Image.open(ROOT/'samples/macaroni2_anomalous.jpg') as image:prediction,overlay=cpu.predict(image,'macaroni2')
|
| 56 |
+
assert prediction['device']=='cpu' and overlay.width>0
|
| 57 |
+
report['cpu_smoke']={k:prediction[k] for k in ('model_id','score','verdict','inference_ms','device')}
|
| 58 |
+
report.update(status='passed',checks={'real_images':24,'all12_highres_profiles':True,'separate_normal_only_calibration':True,
|
| 59 |
+
'images_reports_saved_records':True,'trusted_measurement_answers':2,'real_qwen_heatmap':True,
|
| 60 |
+
'wrong_family_documents_excluded':True,'unsupported_cause_abstains':True,'cpu_smoke':True,
|
| 61 |
+
'scope':'software/runtime acceptance on resized sample derivatives; not a new accuracy benchmark'})
|
| 62 |
+
write(output,report);print(json.dumps(report['checks']),flush=True)
|
scripts/verify_packaged.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exercise an extracted archive's real API, weights and local RAG assets.
|
| 2 |
+
May be executed as a file from outside the extraction; imports are pinned to cwd.
|
| 3 |
+
"""
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import platform
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
def main():
|
| 12 |
+
parser=argparse.ArgumentParser();parser.add_argument('--output',type=Path,required=True)
|
| 13 |
+
args=parser.parse_args()
|
| 14 |
+
project=Path.cwd().resolve()
|
| 15 |
+
if not (project/'RELEASE_MANIFEST.json').exists():raise RuntimeError('Run inside a newly extracted release')
|
| 16 |
+
if (project/'runtime').exists():raise RuntimeError('Extraction already used; choose a fresh extraction')
|
| 17 |
+
os.environ['DEFECTRAG_ENCODER']=str(project/'models'/'encoder')
|
| 18 |
+
os.environ['DEFECTRAG_EMBEDDING']=str(project/'models'/'embedding')
|
| 19 |
+
os.environ['DEFECTRAG_DATA']=str(project/'runtime')
|
| 20 |
+
sys.path.insert(0,str(project))
|
| 21 |
+
import backend.main as implementation
|
| 22 |
+
from backend.config import Settings
|
| 23 |
+
from fastapi.testclient import TestClient
|
| 24 |
+
assert Path(implementation.__file__).resolve().is_relative_to(project)
|
| 25 |
+
report={'status':'running','python':platform.python_version(),'loaded_from_extraction':True,'checks':{}}
|
| 26 |
+
try:
|
| 27 |
+
app=implementation.create_app(Settings(data=project/'runtime'))
|
| 28 |
+
with TestClient(app) as client:
|
| 29 |
+
report['checks']['dashboard']=client.get('/').status_code==200
|
| 30 |
+
assert client.get('/api/inspections').json()['data']==[]
|
| 31 |
+
sample=project/'samples'/'pcb1_anomalous.jpg'
|
| 32 |
+
response=client.post('/api/inspect',data={'category':'pcb1','batch':'extracted-release'},files={'file':(sample.name,sample.read_bytes(),'image/jpeg')})
|
| 33 |
+
response.raise_for_status();record=response.json()['data']
|
| 34 |
+
expected='dinov2-tuned-' if (project/'models/highres_tuned/PROFILE.json').exists() else 'dinov2-highres-' if (project/'models/highres/PROFILE.json').exists() else 'dinov3-'
|
| 35 |
+
assert record['score']>=0 and record['model_id'].startswith(expected)
|
| 36 |
+
report['prediction']={k:record[k] for k in ('category','verdict','score','threshold','inference_ms','model_sha256')}
|
| 37 |
+
report['checks']['genuine_inference']=True
|
| 38 |
+
report['checks']['heatmap']=client.get(record['heatmap_url']).status_code==200
|
| 39 |
+
report['checks']['saved_history']=client.get('/api/inspections').json()['data'][0]['id']==record['id']
|
| 40 |
+
response=client.post('/api/assistant',json={'inspection_id':record['id'],'question':'What does this heatmap measure?'})
|
| 41 |
+
response.raise_for_status();answer=response.json()['data']
|
| 42 |
+
assert answer['mode']=='llm',answer
|
| 43 |
+
assert all(s['id']!='dinomaly' for s in answer['evidence'])
|
| 44 |
+
assert answer['claims']
|
| 45 |
+
report['answer']=answer
|
| 46 |
+
report['checks']['bundled_retrieval_and_genuine_generation']=True
|
| 47 |
+
report['checks']['report']=client.get('/api/inspections/'+record['id']+'/report').status_code==200
|
| 48 |
+
report['checks']['csv']=record['id'] in client.get('/api/export.csv').text
|
| 49 |
+
assert all(report['checks'].values())
|
| 50 |
+
report['status']='passed'
|
| 51 |
+
print(json.dumps({'status':report['status'],'checks':report['checks'],'prediction':report['prediction']},indent=2),flush=True)
|
| 52 |
+
except Exception as exc:
|
| 53 |
+
report['status']='failed';report['error']=str(exc)
|
| 54 |
+
raise
|
| 55 |
+
finally:
|
| 56 |
+
args.output.parent.mkdir(parents=True,exist_ok=True)
|
| 57 |
+
args.output.write_text(json.dumps(report,indent=2))
|
| 58 |
+
if __name__=='__main__':main()
|
scripts/verify_showcase.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Verify snapshot provenance, privacy, asset closure and copied report resources."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import re
|
| 6 |
+
|
| 7 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def verify():
|
| 11 |
+
output = ROOT / 'frontend/dist-static'
|
| 12 |
+
bundle = output / 'showcase'
|
| 13 |
+
manifest = json.loads((bundle / 'manifest.json').read_text())
|
| 14 |
+
for name, expected in manifest['files'].items():
|
| 15 |
+
path = (bundle / name).resolve()
|
| 16 |
+
assert path.is_relative_to(bundle.resolve())
|
| 17 |
+
assert hashlib.sha256(path.read_bytes()).hexdigest() == expected, name
|
| 18 |
+
data = json.loads((bundle / 'data.json').read_text(encoding='utf-8'))
|
| 19 |
+
expected = {e['id']: e for e in json.loads((ROOT / 'results/acceptance.json').read_text())['real_images']}
|
| 20 |
+
scope = json.loads((ROOT / 'results/evidence_scope_verification.json').read_text())
|
| 21 |
+
expected[scope['inspection_id']] = scope['answers'][0]['observation']
|
| 22 |
+
extra=ROOT/'results/all_categories_acceptance.json'
|
| 23 |
+
if extra.exists():expected.update({e['id']:e for e in json.loads(extra.read_text())['real_images']})
|
| 24 |
+
assert len(data['records']) == len(expected)
|
| 25 |
+
assert {r['id'] for r in data['records']} == set(expected)
|
| 26 |
+
for record in data['records']:
|
| 27 |
+
assert record['score'] == expected[record['id']]['score']
|
| 28 |
+
assert record['verdict'] == expected[record['id']]['verdict']
|
| 29 |
+
assert (output / record['image_url']).is_file()
|
| 30 |
+
assert (output / record['heatmap_url']).is_file()
|
| 31 |
+
report = bundle / 'reports' / (record['id'] + '.html')
|
| 32 |
+
for image in re.findall(r'src="([^"]+)"', report.read_text(encoding='utf-8')):
|
| 33 |
+
assert (report.parent / image).is_file()
|
| 34 |
+
text = (bundle / 'data.json').read_text(encoding='utf-8')
|
| 35 |
+
assert not re.search(r'localhost|127\.0\.0\.1|[A-Z]:\\\\|api[_-]?key|password|service_role', text, re.I)
|
| 36 |
+
for path in output.rglob('*'):
|
| 37 |
+
assert path.suffix not in {'.sqlite3', '.safetensors', '.pt', '.npz', '.env'}
|
| 38 |
+
assert any(m.get('mode') == 'llm' for messages in data['messages'].values() for m in messages)
|
| 39 |
+
receipt = {'status': 'passed', 'records': len(expected), 'snapshot_hashes': 'passed',
|
| 40 |
+
'scores_match_saved_acceptance': True, 'report_images_exist': True,
|
| 41 |
+
'saved_llm_conversation_present': True, 'no_private_paths_or_model_files': True}
|
| 42 |
+
(ROOT / 'results/static_verification.json').write_text(json.dumps(receipt, indent=2))
|
| 43 |
+
print(json.dumps(receipt, indent=2))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if __name__ == '__main__':
|
| 47 |
+
verify()
|
scripts/verify_startup.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import platform
|
| 3 |
+
import importlib.metadata
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from fastapi.testclient import TestClient
|
| 6 |
+
from backend.main import app
|
| 7 |
+
|
| 8 |
+
if __name__=='__main__':
|
| 9 |
+
with TestClient(app) as client:
|
| 10 |
+
assert client.get('/api/health').status_code==200
|
| 11 |
+
assert client.get('/').status_code==200
|
| 12 |
+
sample=next((app.state.detector.settings.root/'samples').glob('*.jpg'))
|
| 13 |
+
result,_=app.state.detector.predict(Image.open(sample),sample.stem.rsplit('_',1)[0])
|
| 14 |
+
assert result['score']>=0
|
| 15 |
+
report={'startup':'passed','python':platform.python_version(),'torch':importlib.metadata.version('torch'),
|
| 16 |
+
'transformers':importlib.metadata.version('transformers'),'real_model_prediction':result}
|
| 17 |
+
(app.state.detector.settings.root/'results'/'startup_verification.json').write_text(json.dumps(report,indent=2))
|
| 18 |
+
print(json.dumps(report,indent=2))
|
tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""DefectRAG software and protocol checks."""
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared pytest setup.
|
| 2 |
+
|
| 3 |
+
A fresh GitHub clone (and the GitHub Actions CI run) has no model weights: they
|
| 4 |
+
are large and are downloaded separately with `python -m scripts.fetch_public_assets`.
|
| 5 |
+
Tests that build the full app need the local text-embedding model, so on such a
|
| 6 |
+
checkout they are skipped with a printed reason instead of failing. On a full
|
| 7 |
+
installation (models/embedding present) every test runs as before.
|
| 8 |
+
"""
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
# `import backend.main` normally builds the real application (detector and knowledge
|
| 15 |
+
# index) at import time. Tests build their own app with fakes through create_app(),
|
| 16 |
+
# so importing the module must not load model files.
|
| 17 |
+
os.environ.setdefault('DEFECTRAG_FACTORY_ONLY', '1')
|
| 18 |
+
|
| 19 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 20 |
+
# DEFECTRAG_SIMULATE_CI=1 pretends the model files are absent, to reproduce the CI run locally.
|
| 21 |
+
HAS_MODELS = (ROOT / 'models' / 'embedding').is_dir() and os.getenv('DEFECTRAG_SIMULATE_CI') != '1'
|
| 22 |
+
|
| 23 |
+
# Test files that create the whole application at import time.
|
| 24 |
+
NEEDS_MODELS = []
|
| 25 |
+
# Single tests elsewhere that start the app.
|
| 26 |
+
NEEDS_MODELS_TESTS = {
|
| 27 |
+
'test_calibration_policy.py::test_evaluation_endpoint_reports_the_active_policy',
|
| 28 |
+
'test_macaroni_policy.py::test_public_evaluation_and_model_cards_agree_on_the_targeted_policy',
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
collect_ignore = [] if HAS_MODELS else NEEDS_MODELS
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.fixture
|
| 35 |
+
def client(tmp_path):
|
| 36 |
+
"""A test client for an app that uses software fixtures instead of real models."""
|
| 37 |
+
from fastapi.testclient import TestClient
|
| 38 |
+
from backend.config import Settings
|
| 39 |
+
from backend.main import create_app
|
| 40 |
+
from tests.test_application import SoftwareDetector, SoftwareWorkflow
|
| 41 |
+
app = create_app(Settings(data=tmp_path), SoftwareDetector(), SoftwareWorkflow())
|
| 42 |
+
with TestClient(app) as test_client:
|
| 43 |
+
yield test_client
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def pytest_report_header(config):
|
| 47 |
+
if not HAS_MODELS:
|
| 48 |
+
return 'models/embedding not found: %d app-level test files skipped (fresh clone / CI).' % len(NEEDS_MODELS)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# The Desktop sync script is a Windows operator tool (it defaults to a C:\ path).
|
| 52 |
+
WINDOWS_ONLY = {'test_desktop_sync.py'}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def pytest_collection_modifyitems(config, items):
|
| 56 |
+
no_models = pytest.mark.skip(reason='needs local model files (models/embedding); run on a full installation')
|
| 57 |
+
not_windows = pytest.mark.skip(reason='Windows-only Desktop sync tool')
|
| 58 |
+
for item in items:
|
| 59 |
+
name = item.nodeid.split('/')[-1]
|
| 60 |
+
if not HAS_MODELS and name in NEEDS_MODELS_TESTS:
|
| 61 |
+
item.add_marker(no_models)
|
| 62 |
+
if sys.platform != 'win32' and name.split('::')[0] in WINDOWS_ONLY:
|
| 63 |
+
item.add_marker(not_windows)
|